Java Code Examples for org.apache.http.message.BasicHttpResponse

The following are top voted examples for showing how to use org.apache.http.message.BasicHttpResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 7 votes vote down vote up
public void testPerformRequestOnResponseExceptionWithBrokenEntity2() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Unable to parse response body", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
    assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IllegalStateException.class));
}
 
Example 2
Project: teamcity-msteams-notifier   File: MsTeamsNotificationTest.java   View source code 7 votes vote down vote up
@Test
public void post_whenResponseIsFailure_logsException() throws IOException {
    ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class);
    HttpClient httpClient = mock(HttpClient.class);
    BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, ""));
    response.setEntity(new StringEntity("failure reason here"));

    when(httpClient.execute(requestCaptor.capture())).thenReturn(response);

    MsTeamsNotification w = factory.getMsTeamsNotification(httpClient);

    MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent();
    content.setBuildDescriptionWithLinkSyntax("http://foo");
    content.setCommits(new ArrayList<Commit>());

    w.setPayload(content);
    w.setEnabled(true);
    w.post();

    assertNotNull(w.getResponse());
    assertFalse(w.getResponse().getOk());
}
 
Example 3
Project: q-mail   File: WebDavStoreTest.java   View source code 6 votes vote down vote up
private BasicHttpResponse createOkSearchResponse() throws UnsupportedEncodingException {
    BasicHttpResponse okSearchResponse = createOkResponse();
    HttpEntity searchResponseEntity = new StringEntity("" +
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "   <D:multistatus xmlns:D=\"DAV:\"\n" +
            "      xmlns:R=\"http://example.org/propschema\">\n" +
            "     <D:response>" +
            "       <D:propstat>\n" +
            "       <uid>Inbox</uid>" +
            "       <href>http://example.org/Exchange/user/Inbox</href>\n" +
            "     </D:propstat></D:response>\n" +
            "     <D:response>" +
            "       <D:propstat>\n" +
            "       <uid>Drafts</uid>" +
            "       <href>http://example.org/Exchange/user/Drafts</href>\n" +
            "     </D:propstat></D:response>\n" +
            "     <D:response>" +
            "       <D:propstat>\n" +
            "       <uid>Folder2</uid>" +
            "       <href>http://example.org/Exchange/user/Folder2</href>\n" +
            "     </D:propstat></D:response>\n" +
            "   </D:multistatus>");
    okSearchResponse.setEntity(searchResponseEntity);

    return okSearchResponse;
}
 
Example 4
Project: GitHub   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 5
Project: GitHub   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 6
Project: gmusic-java   File: GMusicClientTest.java   View source code 6 votes vote down vote up
@Test
public void testOAuthStepTwo() throws IOException {
    //Create the mock response
    HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
    postResponse.setEntity(new StringEntity(oauthStepTwoTestJSON));

    //Set the call providers mock response
    callProvider.setPostResponse(postResponse);


    //Perform mock oauth step 2
    Credentials credentials = client.oauthStepTwo(null, null);

    //Check null is not returned
    assertNotNull(credentials);

    //Check the info is what it should be
    assertEquals("access_token", credentials.getAccessToken());
    assertEquals("refresh_token", credentials.getRefreshToken());
    assertEquals("1234567890", credentials.getDateGenerated());
}
 
Example 7
Project: gmusic-java   File: CredentialsTest.java   View source code 6 votes vote down vote up
/**
 * Checks to make sure that tokens and dates are refreshed given a valid response from google
 * Gives a mock response from google with "new" access code
 * @throws IOException
 */
@Test
public void checkRefreshToken() throws IOException {
    long dateGenerated = Instant.now().getEpochSecond() - (3600*2);
    credentials = new Credentials(jsonWithoutDate, dateGenerated);

    //Create mock response
    MockCall callProvider = new MockCall();
    HttpResponse postResponse =  new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
    postResponse.setEntity(new StringEntity("{ \"access_token\":\"new_access_token\", \"expires_in\":3920, \"token_type\":\"Bearer\" }"));
    callProvider.setPostResponse(postResponse);

    //Make assertions
    assertTrue(credentials.refreshToken(null, null, callProvider));
    assertEquals("new_access_token", credentials.getAccessToken());
    assertNotEquals(String.valueOf(dateGenerated), credentials.getDateGenerated());
}
 
Example 8
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 6 votes vote down vote up
public void testPerformRequestOnSuccess() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenReturn(mockResponse);
    {
        Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter,
                response -> response.getStatusLine().getStatusCode(), Collections.emptySet());
        assertEquals(restStatus.getStatus(), result.intValue());
    }
    {
        IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest,
                requestConverter, response -> {throw new IllegalStateException();}, Collections.emptySet()));
        assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " +
                "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage());
    }
}
 
Example 9
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 6 votes vote down vote up
public void testPerformRequestOnResponseExceptionWithoutEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals(responseException.getMessage(), elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
}
 
Example 10
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 6 votes vote down vote up
public void testPerformRequestOnResponseExceptionWithIgnoresErrorNoBody() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> {throw new IllegalStateException();}, Collections.singleton(404)));
    assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
    assertEquals(responseException.getMessage(), elasticsearchException.getMessage());
}
 
Example 11
Project: elasticsearch_my   File: RestHighLevelClientTests.java   View source code 6 votes vote down vote up
public void testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND));
    httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":404}",
            ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> {throw new IllegalStateException();}, Collections.singleton(404)));
    assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getSuppressed()[0]);
    assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
}
 
Example 12
Project: elasticsearch_my   File: HeapBufferedAsyncResponseConsumerTests.java   View source code 6 votes vote down vote up
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    consumer.onResponseReceived(new BasicHttpResponse(statusLine));

    final AtomicReference<Long> contentLength = new AtomicReference<>();
    HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) {
        @Override
        public long getContentLength() {
            return contentLength.get();
        }
    };
    contentLength.set(randomLong(bufferLimit));
    consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);

    contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE));
    try {
        consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
    } catch(ContentTooLongException e) {
        assertEquals("entity content is too long [" + entity.getContentLength() +
                "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage());
    }
}
 
Example 13
Project: apigateway-generic-java-sdk   File: GenericApiGatewayClientTest.java   View source code 6 votes vote down vote up
@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());
    }
}
 
Example 14
Project: aws-xray-sdk-java   File: TracedResponseHandlerTest.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: java-logging   File: OutboundRequestLoggingInterceptorTest.java   View source code 6 votes vote down vote up
@Test
public void logsRequestAndResponseFields() {
    HttpContext context = new BasicHttpContext();
    context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");

    OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(new FakeClock(20));

    interceptor.process(new BasicHttpRequest("GET", "/something"), context);
    interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);

    Map<String, Object> fields = new ConcurrentHashMap<>();
    fields.put("requestMethod", "GET");
    fields.put("requestURI", "http://www.google.com/something");
    testAppender.assertEvent(0, INFO, "Outbound request start", appendEntries(fields));

    fields.put("responseTime", 20L);
    fields.put("responseCode", 200);
    testAppender.assertEvent(1, INFO, "Outbound request finish", appendEntries(fields));
}
 
Example 16
Project: java-logging   File: OutboundRequestLoggingInterceptorTest.java   View source code 6 votes vote down vote up
@Test
public void allowEmptyConstructorToBuildDefaultClock() {
    testAppender.clearEvents();

    HttpContext context = new BasicHttpContext();
    context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");

    OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor();

    interceptor.process(new BasicHttpRequest("GET", "/something"), context);
    interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);

    assertThat(testAppender.getEvents()).extracting("message")
        .contains("Outbound request start", Index.atIndex(0))
        .contains("Outbound request finish", Index.atIndex(1));
}
 
Example 17
Project: bootstrap   File: AbstractRestTest.java   View source code 6 votes vote down vote up
/**
 * Wait for the server is ready.
 */
private void waitForServerReady() throws IOException, InterruptedException {
	final HttpGet httpget = new HttpGet(getPingUri());
	HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, ""));
	int counter = 0;
	while (true) {
		try {
			response = httpclient.execute(httpget);
			final int status = response.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				break;
			}
			checkRetries(counter);
		} catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later
			log.info("Check failed, retrying...");
			checkRetries(counter);
		} finally {
			EntityUtils.consume(response.getEntity());
		}
		counter++;
	}
}
 
Example 18
Project: purecloud-iot   File: TestCachingExecChain.java   View source code 6 votes vote down vote up
@Test
public void testSetsViaHeaderOnResponseIfRequestServedFromCache() throws Exception {
    impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT);
    final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet(
        "http://foo.example.com/"));
    final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet(
        "http://foo.example.com/"));
    final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK,
        "OK");
    resp1.setEntity(HttpTestUtils.makeBody(128));
    resp1.setHeader("Content-Length", "128");
    resp1.setHeader("ETag", "\"etag\"");
    resp1.setHeader("Date", DateUtils.formatDate(new Date()));
    resp1.setHeader("Cache-Control", "public, max-age=3600");

    backendExpectsAnyRequestAndReturn(resp1);

    replayMocks();
    impl.execute(route, req1, context, null);
    final HttpResponse result = impl.execute(route, req2, context, null);
    verifyMocks();
    Assert.assertNotNull(result.getFirstHeader("Via"));
}
 
Example 19
Project: purecloud-iot   File: TestHttpAuthenticator.java   View source code 6 votes vote down vote up
@Test
public void testAuthenticationHandshaking() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", stale=true, nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(new DigestScheme(), this.credentials);

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));

    Assert.assertEquals(AuthProtocolState.HANDSHAKE, this.authState.getState());
}
 
Example 20
Project: Okhttp   File: OkApacheClient.java   View source code 6 votes vote down vote up
private static HttpResponse transformResponse(Response response) {
  int code = response.code();
  String message = response.message();
  BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

  ResponseBody body = response.body();
  InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
  httpResponse.setEntity(entity);

  Headers headers = response.headers();
  for (int i = 0, size = headers.size(); i < size; i++) {
    String name = headers.name(i);
    String value = headers.value(i);
    httpResponse.addHeader(name, value);
    if ("Content-Type".equalsIgnoreCase(name)) {
      entity.setContentType(value);
    } else if ("Content-Encoding".equalsIgnoreCase(name)) {
      entity.setContentEncoding(value);
    }
  }

  return httpResponse;
}
 
Example 21
Project: purecloud-iot   File: TestCacheEntryUpdater.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    requestDate = new Date(System.currentTimeMillis() - 1000);
    responseDate = new Date();

    now = new Date();
    oneSecondAgo = new Date(now.getTime() - 1000L);
    twoSecondsAgo = new Date(now.getTime() - 2000L);
    eightSecondsAgo = new Date(now.getTime() - 8000L);
    tenSecondsAgo = new Date(now.getTime() - 10000L);

    response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
            HttpStatus.SC_NOT_MODIFIED, "Not Modified");

    impl = new CacheEntryUpdater();
}
 
Example 22
Project: purecloud-iot   File: TestResponseProcessCookies.java   View source code 6 votes vote down vote up
@Test
public void testCookieRejected() throws Exception {
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    response.addHeader(SM.SET_COOKIE2, "name=value; Domain=www.somedomain.com; Version=1");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
    context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);

    final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
    interceptor.process(response, context);

    final List<Cookie> cookies = this.cookieStore.getCookies();
    Assert.assertNotNull(cookies);
    Assert.assertTrue(cookies.isEmpty());
}
 
Example 23
Project: Jacket-   File: BasicNetworkTest.java   View source code 6 votes vote down vote up
@Test public void unauthorized() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            401, "Unauthorized");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example 24
Project: purecloud-iot   File: TestProtocolRequirements.java   View source code 6 votes vote down vote up
protected void testUnsafeMethodDoesNotInvalidateCacheForHeaderUri(
        final HttpRequestWrapper unsafeReq) throws Exception, IOException {

    final HttpHost otherHost = new HttpHost("bar.example.com", 80);
    final HttpRoute otherRoute = new HttpRoute(otherHost);
    final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(
            new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1));
    final HttpResponse resp1 = HttpTestUtils.make200Response();
    resp1.setHeader("Cache-Control","public, max-age=3600");

    backendExpectsAnyRequestAndReturn(resp1);

    final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content");

    backendExpectsAnyRequestAndReturn(resp2);

    final HttpRequestWrapper req3 = HttpRequestWrapper.wrap(
            new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1));

    replayMocks();
    impl.execute(otherRoute, req1, context, null);
    impl.execute(route, unsafeReq, context, null);
    impl.execute(otherRoute, req3, context, null);
    verifyMocks();
}
 
Example 25
Project: purecloud-iot   File: TestMinimalClientExec.java   View source code 6 votes vote down vote up
@Test
public void testSocketTimeoutExistingConnection() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    context.setRequestConfig(config);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    Mockito.when(managedConn.isOpen()).thenReturn(true);
    Mockito.when(requestExecutor.execute(
            Mockito.same(request),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenReturn(response);

    minimalClientExec.execute(route, request, context, execAware);
    Mockito.verify(managedConn).setSocketTimeout(3000);
}
 
Example 26
Project: purecloud-iot   File: TestMainClientExec.java   View source code 6 votes vote down vote up
@Test(expected = HttpException.class)
public void testEstablishRouteViaProxyTunnelFailure() throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Boom");
    response.setEntity(new StringEntity("Ka-boom"));

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(requestExecutor.execute(
            Mockito.<HttpRequest>any(),
            Mockito.<HttpClientConnection>any(),
            Mockito.<HttpClientContext>any())).thenReturn(response);

    try {
        mainClientExec.establishRoute(authState, managedConn, route, request, context);
    } catch (final TunnelRefusedException ex) {
        final HttpResponse r = ex.getResponse();
        Assert.assertEquals("Ka-boom", EntityUtils.toString(r.getEntity()));

        Mockito.verify(managedConn).close();

        throw ex;
    }
}
 
Example 27
Project: purecloud-iot   File: TestHttpAuthenticator.java   View source code 6 votes vote down vote up
@Test
public void testAuthenticationRequestedAfterSuccess() throws Exception {
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    Mockito.when(this.defltAuthStrategy.isAuthenticationRequested(
            Mockito.any(HttpHost.class),
            Mockito.any(HttpResponse.class),
            Mockito.any(HttpContext.class))).thenReturn(Boolean.TRUE);

    this.authState.update(this.authScheme, this.credentials);
    this.authState.setState(AuthProtocolState.SUCCESS);

    Assert.assertTrue(this.httpAuthenticator.isAuthenticationRequested(
            this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context));

    Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context);
    Mockito.verify(this.defltAuthStrategy).authFailed(this.defaultHost, this.authScheme, this.context);
}
 
Example 28
Project: purecloud-iot   File: TestCachingExecChain.java   View source code 6 votes vote down vote up
@Test
public void testReturns304ForIfNoneMatchHeaderIfRequestServedFromCache() throws Exception {
    impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT);
    final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet(
        "http://foo.example.com/"));
    final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet(
        "http://foo.example.com/"));
    req2.addHeader("If-None-Match", "*");
    final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK,
        "OK");
    resp1.setEntity(HttpTestUtils.makeBody(128));
    resp1.setHeader("Content-Length", "128");
    resp1.setHeader("ETag", "\"etag\"");
    resp1.setHeader("Date", DateUtils.formatDate(new Date()));
    resp1.setHeader("Cache-Control", "public, max-age=3600");

    backendExpectsAnyRequestAndReturn(resp1);

    replayMocks();
    impl.execute(route, req1, context, null);
    final HttpResponse result = impl.execute(route, req2, context, null);
    verifyMocks();
    Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode());

}
 
Example 29
Project: Jacket-   File: BasicNetworkTest.java   View source code 6 votes vote down vote up
@Test public void redirect() throws Exception {
    for (int i = 300; i <= 399; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry 300 responses.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example 30
Project: InfoQ-Android-App   File: BasicNetworkTest.java   View source code 6 votes vote down vote up
@Test public void otherClientError() throws Exception {
    for (int i = 400; i <= 499; i++) {
        if (i == 401 || i == 403) {
            // covered above.
            continue;
        }
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry other 400 errors.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example 31
Project: SaveVolley   File: BasicNetworkTest.java   View source code 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse = new BasicHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example 32
Project: java-triton   File: InstancesTest.java   View source code 6 votes vote down vote up
public void canCreateInstance() throws IOException {
    final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_CREATED, "Created");
    final HttpResponse response = new BasicHttpResponse(statusLine);
    final File file = new File("src/test/data/instances/created.json");
    final HttpEntity entity = new FileEntity(file);
    response.setEntity(entity);

    Instance instance = new Instance()
            .setName("some_name")
            .setPackageId(new UUID(12L, 24L))
            .setImage(new UUID(8L, 16L))
            .setTags(Collections.singletonMap(TEST_TAG_KEY, TEST_TAG));

    try (CloudApiConnectionContext context = createMockContext(response)) {
        final Instance created = instanceApi.create(context, instance);
        assertNotNull(created);
        assertNotNull(created.getId());
    }
}
 
Example 33
Project: purecloud-iot   File: TestResponseProcessCookies.java   View source code 6 votes vote down vote up
@Test
public void testNoCookieStore() throws Exception {
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    response.addHeader(SM.SET_COOKIE, "name1=value1");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
    context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec);
    context.setAttribute(HttpClientContext.COOKIE_STORE, null);

    final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
    interceptor.process(response, context);

    final List<Cookie> cookies = this.cookieStore.getCookies();
    Assert.assertNotNull(cookies);
    Assert.assertEquals(0, cookies.size());
}
 
Example 34
Project: purecloud-iot   File: TestHttpAuthenticator.java   View source code 6 votes vote down vote up
@Test
public void testAuthentication() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));
    Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

    final Queue<AuthOption> options = this.authState.getAuthOptions();
    Assert.assertNotNull(options);
    final AuthOption option1 = options.poll();
    Assert.assertNotNull(option1);
    Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
    final AuthOption option2 = options.poll();
    Assert.assertNotNull(option2);
    Assert.assertEquals("basic", option2.getAuthScheme().getSchemeName());
    Assert.assertNull(options.poll());
}
 
Example 35
Project: purecloud-iot   File: TestAuthenticationStrategy.java   View source code 6 votes vote down vote up
@Test
public void testSelectNoCredentialsProvider() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
 
Example 36
Project: purecloud-iot   File: TestResponseProcessCookies.java   View source code 6 votes vote down vote up
@Test
public void testSetCookie2OverrideSetCookie() throws Exception {
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    response.addHeader(SM.SET_COOKIE, "name1=value1");
    response.addHeader(SM.SET_COOKIE2, "name1=value2; Version=1");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
    context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec);
    context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);

    final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
    interceptor.process(response, context);

    final List<Cookie> cookies = this.cookieStore.getCookies();
    Assert.assertNotNull(cookies);
    Assert.assertEquals(1, cookies.size());
    final Cookie cookie = cookies.get(0);
    Assert.assertEquals(1, cookie.getVersion());
    Assert.assertEquals("name1", cookie.getName());
    Assert.assertEquals("value2", cookie.getValue());
    Assert.assertEquals("localhost.local", cookie.getDomain());
    Assert.assertEquals("/", cookie.getPath());
}
 
Example 37
Project: purecloud-iot   File: TestBasicHttpCache.java   View source code 6 votes vote down vote up
@Test
public void testOriginalResponseWithNoContentSizeHeaderIsReleased() throws Exception {
    final HttpHost host = new HttpHost("foo.example.com");
    final HttpRequest request = new HttpGet("http://foo.example.com/bar");

    final Date now = new Date();
    final Date requestSent = new Date(now.getTime() - 3 * 1000L);
    final Date responseGenerated = new Date(now.getTime() - 2 * 1000L);
    final Date responseReceived = new Date(now.getTime() - 1 * 1000L);

    final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    final BasicHttpEntity entity = new BasicHttpEntity();
    final ConsumableInputStream inputStream = new ConsumableInputStream(new ByteArrayInputStream(HttpTestUtils.getRandomBytes(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1)));
    entity.setContent(inputStream);
    originResponse.setEntity(entity);
    originResponse.setHeader("Cache-Control","public, max-age=3600");
    originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated));
    originResponse.setHeader("ETag", "\"etag\"");

    final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived);
    IOUtils.consume(result.getEntity());
    assertTrue(inputStream.wasClosed());
}
 
Example 38
Project: java-triton   File: InstancesTest.java   View source code 6 votes vote down vote up
public void canAddAdditionalTagsToAnInstance() throws IOException {
    final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK");
    final HttpResponse response = new BasicHttpResponse(statusLine);
    final File file = new File("src/test/data/instances/additional_tags.json");
    final HttpEntity entity = new FileEntity(file);
    response.setEntity(entity);

    final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9");

    try (CloudApiConnectionContext context = createMockContext(response)) {
        Map<String, String> tags = instanceApi.addTags(context, instanceId,
                ImmutableMap.of("additional_1", "val1", "additional_2", "val2"));

        assertEquals(tags.size(), 3, "Expecting 3 tags");
        assertEquals(tags.get("name"), "value");
        assertEquals(tags.get("additional_1"), "val1");
        assertEquals(tags.get("additional_2"), "val2");
    }
}
 
Example 39
Project: purecloud-iot   File: CachingHttpClient.java   View source code 6 votes vote down vote up
private HttpResponse handleCacheMiss(final HttpHost target, final HttpRequestWrapper request,
        final HttpContext context) throws IOException {
    recordCacheMiss(target, request);

    if (!mayCallBackend(request)) {
        return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
                "Gateway Timeout");
    }

    final Map<String, Variant> variants =
        getExistingCacheVariants(target, request);
    if (variants != null && variants.size() > 0) {
        return negotiateResponseFromVariants(target, request, context, variants);
    }

    return callBackend(target, request, context);
}
 
Example 40
Project: java-triton   File: PackagesTest.java   View source code 6 votes vote down vote up
public void canFindTheSmallestMemoryPackages() throws IOException {
    final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK");
    final HttpResponse response = new BasicHttpResponse(statusLine);
    final File file = new File("src/test/data/packages/packages.json");
    final HttpEntity entity = new FileEntity(file);
    response.setEntity(entity);

    try (CloudApiConnectionContext context = createMockContext(response)) {
        Collection<Package> packages = packagesApi.smallestMemory(context);
        assertFalse(packages.isEmpty(), "This should not be an empty collection");
        assertEquals(packages.size(), 1);

        final Package pkg = packages.iterator().next();
        assertEquals(pkg.getName(), "t4-standard-128M",
                "Package name is unexpected. Actual package:\n" + pkg);
    }
}