org.apache.http.HttpResponse

Here are the examples of the java api class org.apache.http.HttpResponse taken from open source projects.

1. TestDefaultConnectionReuseStrategy#testConnectionTokens5()

View license
public void testConnectionTokens5() throws Exception {
    // Use HTTP 1.1
    HttpResponse response = createResponse(HttpVersion.HTTP_1_1, 200, "OK", true, -1);
    response.addHeader("Connection", "yadda, dumdy");
    response.addHeader("Proxy-Connection", "close");
    // Connection takes precedence over Proxy-Connection,
    // even if it doesn't contain a recognized token.
    // Default for HTTP/1.1 is to keep alive.
    assertTrue(reuseStrategy.keepAlive(response, context));
}

2. TestDefaultConnectionReuseStrategy#createResponse()

View license
// createResponse/empty
/**
     * Creates a response with an entity.
     *
     * @param version   the HTTP version
     * @param status    the status code
     * @param message   the status message
     * @param chunked   whether the entity should indicate chunked encoding
     * @param length    the content length to be indicated by the entity
     *
     * @return  a response with the argument attributes, but no headers
     */
private static final HttpResponse createResponse(HttpVersion version, int status, String message, boolean chunked, int length) {
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setChunked(chunked);
    entity.setContentLength(length);
    HttpResponse response = createResponse(version, status, message);
    response.setEntity(entity);
    return response;
}

3. TestHttpClient#execute()

Project: httpcore
Source File: TestHttpClient.java
View license
public HttpResponse execute(final HttpRequest request, final HttpHost targetHost, final HttpClientConnection conn) throws HttpException, IOException {
    this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
    this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
    this.httpexecutor.preProcess(request, this.httpproc, this.context);
    HttpResponse response = this.httpexecutor.execute(request, conn, this.context);
    response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
    this.httpexecutor.postProcess(response, this.httpproc, this.context);
    return response;
}

4. TestStandardInterceptors#testResponseConnControlEntityUnknownContentLength()

View license
public void testResponseConnControlEntityUnknownContentLength() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
    request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    response.setEntity(entity);
    ResponseConnControl interceptor = new ResponseConnControl();
    interceptor.process(response, context);
    Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
    assertNotNull(header);
    assertEquals(HTTP.CONN_CLOSE, header.getValue());
}

5. TestStandardInterceptors#testResponseConnControlClientRequest()

View license
public void testResponseConnControlClientRequest() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
    request.addHeader(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    StringEntity entity = new StringEntity("whatever");
    response.setEntity(entity);
    ResponseConnControl interceptor = new ResponseConnControl();
    interceptor.process(response, context);
    Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
    assertNotNull(header);
    assertEquals(HTTP.CONN_KEEP_ALIVE, header.getValue());
}

6. TestStandardInterceptors#testResponseConnControlClientRequest2()

View license
public void testResponseConnControlClientRequest2() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    StringEntity entity = new StringEntity("whatever");
    response.setEntity(entity);
    ResponseConnControl interceptor = new ResponseConnControl();
    interceptor.process(response, context);
    Header header = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
    assertNull(header);
}

7. TestStandardInterceptors#testResponseContentEntityChunked()

View license
public void testResponseContentEntityChunked() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setChunked(true);
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
    assertNotNull(h1);
    assertEquals(HTTP.CHUNK_CODING, h1.getValue());
    Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN);
    assertNull(h2);
}

8. TestStandardInterceptors#testResponseContentEntityContentLenghtDelimited()

View license
public void testResponseContentEntityContentLenghtDelimited() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContentLength(10);
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.CONTENT_LEN);
    assertNotNull(h1);
    assertEquals("10", h1.getValue());
    Header h2 = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
    assertNull(h2);
}

9. TestStandardInterceptors#testResponseContentEntityUnknownContentLength()

View license
public void testResponseContentEntityUnknownContentLength() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
    assertNull(h1);
    Header h2 = response.getFirstHeader(HTTP.CONTENT_LEN);
    assertNull(h2);
}

10. TestStandardInterceptors#testResponseContentEntityNoContentTypeAndEncoding()

View license
public void testResponseContentEntityNoContentTypeAndEncoding() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.CONTENT_TYPE);
    assertNull(h1);
    Header h2 = response.getFirstHeader(HTTP.CONTENT_ENCODING);
    assertNull(h2);
}

11. TestStandardInterceptors#testResponseContentEntityContentTypeAndEncoding()

View license
public void testResponseContentEntityContentTypeAndEncoding() throws Exception {
    HttpContext context = new BasicHttpContext(null);
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContentEncoding("whatever");
    entity.setContentType("whatever");
    response.setEntity(entity);
    ResponseContent interceptor = new ResponseContent();
    interceptor.process(response, context);
    Header h1 = response.getFirstHeader(HTTP.CONTENT_TYPE);
    assertNotNull(h1);
    assertEquals("whatever", h1.getValue());
    Header h2 = response.getFirstHeader(HTTP.CONTENT_ENCODING);
    assertNotNull(h2);
    assertEquals("whatever", h2.getValue());
}

12. AwsMvcConfigUnitTests#cantGetHostname()

Project: genie
Source File: AwsMvcConfigUnitTests.java
View license
/**
     * Make sure if both fails we throw an exception.
     *
     * @throws IOException on any problem
     */
@Test(expected = IOException.class)
public void cantGetHostname() throws IOException {
    final HttpClient client = Mockito.mock(HttpClient.class);
    final HttpResponse response = Mockito.mock(HttpResponse.class);
    Mockito.when(client.execute(this.awsMvcConfig.publicHostNameGet)).thenReturn(response);
    final StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(response.getStatusLine()).thenReturn(statusLine);
    Mockito.when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NOT_FOUND);
    final HttpResponse ip4Response = Mockito.mock(HttpResponse.class);
    Mockito.when(client.execute(this.awsMvcConfig.localIPV4HostNameGet)).thenReturn(ip4Response);
    final StatusLine ip4StatusLine = Mockito.mock(StatusLine.class);
    Mockito.when(ip4Response.getStatusLine()).thenReturn(ip4StatusLine);
    Mockito.when(ip4StatusLine.getStatusCode()).thenReturn(HttpStatus.SC_BAD_REQUEST);
    this.awsMvcConfig.hostName(client);
}

13. CxfCacheUriInfoIssue2Test#testServletContextPath()

View license
@Test
public void testServletContextPath() throws Exception {
    URI uri1 = URI.create(server1.getEndpoint().toASCIIString() + "$metadata");
    final HttpGet get1 = new HttpGet(uri1);
    HttpResponse r1 = new DefaultHttpClient().execute(get1);
    assertNotNull(r1);
    assertEquals(uri1, CxfCacheUriInfoIssueService1Factory.service.getProcessor().getContext().getPathInfo().getRequestUri());
    assertEquals(server1.getEndpoint(), CxfCacheUriInfoIssueService1Factory.service.getProcessor().getContext().getPathInfo().getServiceRoot());
    URI uri2 = URI.create(server2.getEndpoint().toASCIIString() + "$metadata");
    final HttpGet get2 = new HttpGet(uri2);
    HttpResponse r2 = new DefaultHttpClient().execute(get2);
    assertNotNull(r2);
    assertEquals(uri2, CxfCacheUriInfoIssueService2Factory.service.getProcessor().getContext().getPathInfo().getRequestUri());
    assertEquals(server2.getEndpoint(), CxfCacheUriInfoIssueService2Factory.service.getProcessor().getContext().getPathInfo().getServiceRoot());
}

14. CxfCacheUriInfoIssueTest#checkContextForDifferentHostNamesRequests()

View license
@Test
public void checkContextForDifferentHostNamesRequests() throws ClientProtocolException, IOException, ODataException, URISyntaxException {
    URI uri1 = URI.create(getEndpoint().toString() + "$metadata");
    HttpGet get1 = new HttpGet(uri1);
    HttpResponse response1 = getHttpClient().execute(get1);
    assertNotNull(response1);
    URI serviceRoot1 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
    assertEquals(uri1.getHost(), serviceRoot1.getHost());
    get1.reset();
    URI uri2 = new URI(uri1.getScheme(), uri1.getUserInfo(), "127.0.0.1", uri1.getPort(), uri1.getPath(), uri1.getQuery(), uri1.getFragment());
    HttpGet get2 = new HttpGet(uri2);
    HttpResponse response2 = getHttpClient().execute(get2);
    assertNotNull(response2);
    URI serviceRoot2 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
    assertEquals(uri2.getHost(), serviceRoot2.getHost());
}

15. AwsMvcConfig#hostName()

Project: genie
Source File: AwsMvcConfig.java
View license
/**
     * Get the host name for this application by calling the AWS metadata endpoints. Overrides default implementation
     * which defaults to using InetAddress class. Only active when profile enabled.
     *
     * @param httpClient The http client to use to call the Amazon endpoints
     * @return The hostname
     * @throws IOException When the host can't be calculated
     */
@Bean
public String hostName(final HttpClient httpClient) throws IOException {
    final HttpResponse publicHostnameResponse = httpClient.execute(this.publicHostNameGet);
    if (publicHostnameResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        final String hostname = EntityUtils.toString(publicHostnameResponse.getEntity(), UTF_8);
        log.debug("AWS Public Hostname: {}", hostname);
        return hostname;
    }
    final HttpResponse ipv4Response = httpClient.execute(this.localIPV4HostNameGet);
    if (ipv4Response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        final String hostname = EntityUtils.toString(ipv4Response.getEntity(), UTF_8);
        log.debug("AWS IPV4 Hostname: {}", hostname);
        return hostname;
    }
    throw new IOException("Unable to get instance metadata from AWS");
}

16. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromSameHost()

View license
@Test
public void reusesWrapperForRequestsFromSameHost() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("http://foo.example.com/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

17. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromEquivalentHostsDefaultHttpPort()

View license
@Test
public void reusesWrapperForRequestsFromEquivalentHostsDefaultHttpPort() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("http://foo.example.com:80/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

18. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromEquivalentHostsDefaultHttpsPort()

View license
@Test
public void reusesWrapperForRequestsFromEquivalentHostsDefaultHttpsPort() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("https://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("https://foo.example.com:443/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

19. TestPerHostServiceWrappedHttpClient#reusesWrapperForRequestsFromEquivalentHostsCaseInsensitiveHostName()

View license
@Test
public void reusesWrapperForRequestsFromEquivalentHostsCaseInsensitiveHostName() throws Exception {
    ServiceWrapper wrapper = new NullWrapper();
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/bar");
    HttpUriRequest req2 = new HttpGet("http://FOO.Example.cOM/baz");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName(isA(String.class))).andReturn(wrapper);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    impl.execute(req2, ctx);
    verifyMocks();
}

20. TestPerHostServiceWrappedHttpClient#usesDifferentWrappersForDifferentHosts()

View license
@Test
public void usesDifferentWrappersForDifferentHosts() throws Exception {
    Flag f1 = new Flag();
    ServiceWrapper wrapper1 = new NullWrapper(f1);
    Flag f2 = new Flag();
    ServiceWrapper wrapper2 = new NullWrapper(f2);
    HttpUriRequest req1 = new HttpGet("http://foo.example.com/");
    HttpUriRequest req2 = new HttpGet("http://bar.example.com/");
    HttpResponse resp1 = resp;
    HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    expect(mockFactory.getWrapperWithName("foo.example.com:80")).andReturn(wrapper1);
    expect(mockFactory.getWrapperWithName("bar.example.com:80")).andReturn(wrapper2);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp1);
    expect(mockBackend.execute(isA(HttpHost.class), isA(HttpRequest.class), isA(HttpContext.class))).andReturn(resp2);
    replayMocks();
    impl.execute(req1, ctx);
    assertTrue(f1.set && !f2.set);
    impl.execute(req2, ctx);
    assertTrue(f1.set && f2.set);
    verifyMocks();
}

21. OkApacheClientTest#headers()

Project: okhttp
Source File: OkApacheClientTest.java
View license
@Test
public void headers() throws Exception {
    server.enqueue(new MockResponse().addHeader("Foo", "Bar"));
    server.enqueue(new MockResponse().addHeader("Foo", "Bar").addHeader("Foo", "Baz"));
    HttpGet request1 = new HttpGet(server.url("/").url().toURI());
    HttpResponse response1 = client.execute(request1);
    Header[] headers1 = response1.getHeaders("Foo");
    assertEquals(1, headers1.length);
    assertEquals("Bar", headers1[0].getValue());
    HttpGet request2 = new HttpGet(server.url("/").url().toURI());
    HttpResponse response2 = client.execute(request2);
    Header[] headers2 = response2.getHeaders("Foo");
    assertEquals(2, headers2.length);
    assertEquals("Bar", headers2[0].getValue());
    assertEquals("Baz", headers2[1].getValue());
}

22. DefaultRequestDirectorTest#shouldReturnRequestsByRule_AnyMethod()

View license
@Test
public void shouldReturnRequestsByRule_AnyMethod() throws Exception {
    Robolectric.addHttpResponseRule("http://some.uri", new TestHttpResponse(200, "a cheery response body"));
    HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
    assertNotNull(getResponse);
    assertThat(getResponse.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(Strings.fromStream(getResponse.getEntity().getContent()), equalTo("a cheery response body"));
    HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
    assertNotNull(postResponse);
    assertThat(postResponse.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(Strings.fromStream(postResponse.getEntity().getContent()), equalTo("a cheery response body"));
}

23. DefaultRequestDirectorTest#shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams()

View license
@Test
public void shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams() throws Exception {
    TestHttpResponse testHttpResponse = new TestHttpResponse(200, "a cheery response body");
    Robolectric.addHttpResponseRule("http://some.uri", testHttpResponse);
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
    HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
    InputStream getResponseStream = getResponse.getEntity().getContent();
    assertThat(Strings.fromStream(getResponseStream), equalTo("a cheery response body"));
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
    InputStream postResponseStream = postResponse.getEntity().getContent();
    assertThat(Strings.fromStream(postResponseStream), equalTo("a cheery response body"));
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    getResponseStream.close();
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    postResponseStream.close();
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
}

24. DefaultRequestDirectorTest#shouldHandleMultipleInvocations()

View license
@Test
public void shouldHandleMultipleInvocations() throws Exception {
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    Robolectric.addPendingHttpResponse(201, "another happy response body");
    HttpResponse response1 = requestDirector.execute(null, new HttpGet("http://example.com"), null);
    HttpResponse response2 = requestDirector.execute(null, new HttpGet("www.example.com"), null);
    assertThat(response1.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(Strings.fromStream(response1.getEntity().getContent()), equalTo("a happy response body"));
    assertThat(response2.getStatusLine().getStatusCode(), equalTo(201));
    assertThat(Strings.fromStream(response2.getEntity().getContent()), equalTo("another happy response body"));
}

25. CreateSessionHandlerTest#assertNewTestSessionCreationAndGetCapabilties()

View license
@Test
public void assertNewTestSessionCreationAndGetCapabilties() throws Exception {
    HttpResponse sessionResponse = executeCreateSessionRequest();
    JSONObject json = parseJsonResponse(sessionResponse);
    String sessionId = json.getString("sessionId");
    // Get capabilities of session
    HttpResponse getCapaResp = executeRequest("http://" + host + ":" + port + "/wd/hub/session/" + sessionId, HttpMethod.GET);
    SelendroidAssert.assertResponseIsOk(getCapaResp);
    JSONObject capa = parseJsonResponse(getCapaResp);
    Assert.assertEquals(sessionId, capa.getString("sessionId"));
    Assert.assertEquals(0, capa.getInt("status"));
    Assert.assertEquals("selendroid", capa.getJSONObject("value").getString(Capabilities.NAME));
}

26. FindElementHandlerTest#assertThatFindElementResponseHasCorrectFormat()

View license
// @Test()
public void assertThatFindElementResponseHasCorrectFormat() throws Exception {
    HttpResponse response = executeCreateSessionRequest();
    SelendroidAssert.assertResponseIsRedirect(response);
    JSONObject session = parseJsonResponse(response);
    String sessionId = session.getString("sessionId");
    Assert.assertFalse(sessionId.isEmpty());
    JSONObject payload = new JSONObject();
    payload.put("using", "id");
    payload.put("value", "my_button_bar");
    String url = "http://" + host + ":" + port + "/wd/hub/session/" + sessionId + "/element";
    HttpResponse element = executeRequestWithPayload(url, HttpMethod.POST, payload.toString());
    SelendroidAssert.assertResponseIsOk(element);
}

27. HealthCheckResourceTest#checkHealth()

Project: karyon
Source File: HealthCheckResourceTest.java
View license
private void checkHealth(HealthCheckHandler healthCheckHandler, int respStatus) throws Exception {
    final AdminResourcesContainer adminResourcesContainer = buildAdminResourcesContainer(healthCheckHandler);
    adminResourcesContainer.init();
    final int adminPort = adminResourcesContainer.getServerPort();
    HttpClient client = new DefaultHttpClient();
    HttpGet healthGet = new HttpGet(String.format("http://localhost:%d/jr/v2/healthcheck", adminPort));
    HttpResponse response = client.execute(healthGet);
    assertEquals("admin resource health check resource failed.", respStatus, response.getStatusLine().getStatusCode());
    adminResourcesContainer.shutdown();
}

28. ReadDstu1Test#testReadJson()

Project: hapi-fhir
Source File: ReadDstu1Test.java
View license
@Test
public void testReadJson() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient/1?_format=json");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(200, status.getStatusLine().getStatusCode());
    IdentifierDt dt = ourCtx.newJsonParser().parseResource(Patient.class, responseContent).getIdentifierFirstRep();
    assertEquals("1", dt.getSystem().getValueAsString());
    assertEquals(null, dt.getValue().getValueAsString());
    Header cl = status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION_LC);
    assertNotNull(cl);
    assertEquals("http://localhost:" + ourPort + "/Patient/1/_history/1", cl.getValue());
    assertThat(responseContent, stringContainsInOrder("1", "\""));
    assertThat(responseContent, not(stringContainsInOrder("1", "\"", "1")));
}

29. HealthCheckResourceTest#checkHealth()

Project: karyon
Source File: HealthCheckResourceTest.java
View license
private void checkHealth(HealthCheckHandler healthCheckHandler, int respStatus) throws Exception {
    final AdminResourcesContainer adminResourcesContainer = buildAdminResourcesContainer(healthCheckHandler);
    adminResourcesContainer.init();
    final int adminPort = adminResourcesContainer.getServerPort();
    HttpClient client = new DefaultHttpClient();
    HttpGet healthGet = new HttpGet(String.format("http://localhost:%d/jr/healthcheck", adminPort));
    HttpResponse response = client.execute(healthGet);
    assertEquals("admin resource health check resource failed.", respStatus, response.getStatusLine().getStatusCode());
    adminResourcesContainer.shutdown();
}

30. WebAdminTest#testMaskedResources()

Project: karyon
Source File: WebAdminTest.java
View license
@Test
public void testMaskedResources() throws Exception {
    HttpClient client = new DefaultHttpClient();
    final String endPoint = String.format("http://localhost:%d/webadmin/archprops", adminServerPort);
    LOG.info("REST endpoint " + endPoint);
    HttpGet restGet = new HttpGet(endPoint);
    HttpResponse response = client.execute(restGet);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(MediaType.APPLICATION_JSON, response.getEntity().getContentType().getValue());
    String responseStr = EntityUtils.toString(response.getEntity());
    LOG.info("responseStr: " + responseStr);
    assertTrue(responseStr.contains("[\"AWS_SECRET_KEY\",\"" + MaskedResourceHelper.MASKED_PROPERTY_VALUE + "\"]"));
    assertTrue(responseStr.contains("[\"AWS_ACCESS_ID\",\"super-aws-access-id\"]"));
    // need to consume full response before make another rest call with
    // the default SingleClientConnManager used with DefaultHttpClient
    EntityUtils.consume(response.getEntity());
}

31. ServerRequest#invokeLogout()

Project: keycloak
Source File: ServerRequest.java
View license
public static void invokeLogout(KeycloakDeployment deployment, String refreshToken) throws IOException, HttpFailure {
    HttpClient client = deployment.getClient();
    URI uri = deployment.getLogoutUrl().clone().build();
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
    HttpPost post = new HttpPost(uri);
    ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
    UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
    post.setEntity(form);
    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    if (status != 204) {
        error(status, entity);
    }
    if (entity == null) {
        return;
    }
    InputStream is = entity.getContent();
    if (is != null)
        is.close();
}

32. ServerRequest#invokeClientManagementRequest()

Project: keycloak
Source File: ServerRequest.java
View license
public static void invokeClientManagementRequest(KeycloakDeployment deployment, String host, String endpointUrl) throws HttpFailure, IOException {
    if (endpointUrl == null) {
        throw new IOException("You need to configure URI for register/unregister node for application " + deployment.getResourceName());
    }
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair(AdapterConstants.CLIENT_CLUSTER_HOST, host));
    HttpPost post = new HttpPost(endpointUrl);
    ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
    UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
    post.setEntity(form);
    HttpResponse response = deployment.getClient().execute(post);
    int status = response.getStatusLine().getStatusCode();
    if (status != 204) {
        HttpEntity entity = response.getEntity();
        error(status, entity);
    }
}

33. CustomerCli#profile()

Project: keycloak
Source File: CustomerCli.java
View license
public static void profile() throws Exception {
    String accountUrl = keycloak.getDeployment().getAccountUrl();
    HttpGet get = new HttpGet(accountUrl);
    get.setHeader("Accept", "application/json");
    get.setHeader("Authorization", "Bearer " + keycloak.getTokenString(10, TimeUnit.SECONDS));
    HttpResponse response = keycloak.getDeployment().getClient().execute(get);
    if (response.getStatusLine().getStatusCode() == 200) {
        print(response.getEntity().getContent());
    } else {
        System.out.println(response.getStatusLine().toString());
    }
}

34. CustomerCli#customers()

Project: keycloak
Source File: CustomerCli.java
View license
public static void customers() throws Exception {
    String baseUrl = keycloak.getDeployment().getAuthServerBaseUrl();
    baseUrl = baseUrl.substring(0, baseUrl.indexOf('/', 8));
    String customersUrl = baseUrl + "/database/customers";
    HttpGet get = new HttpGet(customersUrl);
    get.setHeader("Accept", "application/json");
    get.setHeader("Authorization", "Bearer " + keycloak.getTokenString(10, TimeUnit.SECONDS));
    HttpResponse response = keycloak.getDeployment().getClient().execute(get);
    if (response.getStatusLine().getStatusCode() == 200) {
        print(response.getEntity().getContent());
    } else {
        System.out.println(response.getStatusLine().toString());
    }
}

35. ProfileTest#getProfile()

Project: keycloak
Source File: ProfileTest.java
View license
@Test
public void getProfile() throws Exception {
    oauth.doLogin("[email protected]", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    String token = oauth.doAccessTokenRequest(code, "password").getAccessToken();
    HttpResponse response = doGetProfile(token, null);
    assertEquals(200, response.getStatusLine().getStatusCode());
    JSONObject profile = new JSONObject(IOUtils.toString(response.getEntity().getContent()));
    assertEquals("[email protected]", profile.getString("username"));
    assertEquals("[email protected]", profile.getString("email"));
    assertEquals("First", profile.getString("firstName"));
    assertEquals("Last", profile.getString("lastName"));
    JSONObject attributes = profile.getJSONObject("attributes");
    JSONArray attrValue = attributes.getJSONArray("key1");
    assertEquals(1, attrValue.length());
    assertEquals("value1", attrValue.get(0));
    attrValue = attributes.getJSONArray("key2");
    assertEquals(1, attrValue.length());
    assertEquals("value2", attrValue.get(0));
}

36. ProfileTest#getProfileOAuthClient()

Project: keycloak
Source File: ProfileTest.java
View license
@Test
public void getProfileOAuthClient() throws Exception {
    oauth.clientId("third-party");
    oauth.doLoginGrant("[email protected]", "password");
    grantPage.accept();
    String token = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE), "password").getAccessToken();
    HttpResponse response = doGetProfile(token, null);
    assertEquals(200, response.getStatusLine().getStatusCode());
    JSONObject profile = new JSONObject(IOUtils.toString(response.getEntity().getContent()));
    assertEquals("[email protected]", profile.getString("username"));
    accountApplicationsPage.open();
    accountApplicationsPage.revokeGrant("third-party");
}

37. ClientAuthSignedJWTTest#testAssertionMissingIssuer()

View license
@Test
public void testAssertionMissingIssuer() throws Exception {
    String invalidJwt = getClientSignedJWT(getClient1PrivateKey(), null);
    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
    HttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
    assertError(response, null, "unauthorized_client", Errors.INVALID_CLIENT_CREDENTIALS);
}

38. ClientAuthSignedJWTTest#testAssertionUnknownClient()

View license
@Test
public void testAssertionUnknownClient() throws Exception {
    String invalidJwt = getClientSignedJWT(getClient1PrivateKey(), "unknown-client");
    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
    HttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
    assertError(response, "unknown-client", "unauthorized_client", Errors.INVALID_CLIENT_CREDENTIALS);
}

39. ClientAuthSignedJWTTest#testAssertionDisabledClient()

View license
@Test
public void testAssertionDisabledClient() throws Exception {
    ClientManager.realm(adminClient.realm("test")).clientId("client1").enabled(false);
    String invalidJwt = getClient1SignedJWT();
    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
    HttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
    assertError(response, "client1", "invalid_client", Errors.CLIENT_DISABLED);
    ClientManager.realm(adminClient.realm("test")).clientId("client1").enabled(false);
}

40. ClientAuthSignedJWTTest#testAssertionInvalidSignature()

View license
@Test
public void testAssertionInvalidSignature() throws Exception {
    // JWT for client1, but signed by privateKey of client2
    String invalidJwt = getClientSignedJWT(getClient2PrivateKey(), "client1");
    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
    HttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
    assertError(response, "client1", "unauthorized_client", Errors.INVALID_CLIENT_CREDENTIALS);
}

41. ClientAuthSignedJWTTest#testAssertionExpired()

View license
@Test
public void testAssertionExpired() throws Exception {
    String invalidJwt = getClient1SignedJWT();
    setTimeOffset(1000);
    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
    HttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
    setTimeOffset(0);
    assertError(response, "client1", "unauthorized_client", Errors.INVALID_CLIENT_CREDENTIALS);
}

42. ClientAuthSignedJWTTest#testAssertionInvalidNotBefore()

View license
@Test
public void testAssertionInvalidNotBefore() throws Exception {
    String invalidJwt = getClient1SignedJWT();
    setTimeOffset(-1000);
    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));
    HttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);
    setTimeOffset(0);
    assertError(response, "client1", "unauthorized_client", Errors.INVALID_CLIENT_CREDENTIALS);
}

43. CouchDBSchemaManager#checkForDBExistence()

Project: Kundera
Source File: CouchDBSchemaManager.java
View license
/**
     * Check for db existence.
     * 
     * @return true, if successful
     * @throws ClientProtocolException
     *             the client protocol exception
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws URISyntaxException
     *             the URI syntax exception
     */
private boolean checkForDBExistence() throws ClientProtocolException, IOException, URISyntaxException {
    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
    HttpGet get = new HttpGet(uri);
    HttpResponse getRes = null;
    try {
        // creating database.
        getRes = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));
        if (getRes.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return true;
        }
        return false;
    } finally {
        CouchDBUtils.closeContent(getRes);
    }
}

44. CouchDBSchemaManager#dropDatabase()

Project: Kundera
Source File: CouchDBSchemaManager.java
View license
/**
     * Drop database.
     * 
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws ClientProtocolException
     *             the client protocol exception
     * @throws URISyntaxException
     *             the URI syntax exception
     */
private void dropDatabase() throws IOException, ClientProtocolException, URISyntaxException {
    HttpResponse delRes = null;
    try {
        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
        HttpDelete delete = new HttpDelete(uri);
        delRes = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));
    } finally {
        CouchDBUtils.closeContent(delRes);
    }
}

45. CouchDBOperationUtils#createdatabase()

Project: Kundera
Source File: CouchDBOperationUtils.java
View license
public void createdatabase(String keyspace, String host, int port) throws URISyntaxException, IOException {
    initiateClient(host, port);
    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), CouchDBConstants.URL_SAPRATOR + keyspace.toLowerCase(), null, null);
    HttpPut put = new HttpPut(uri);
    HttpResponse putRes = null;
    try {
        // creating database.
        logger.info("Creating database " + keyspace);
        putRes = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
    } finally {
        CouchDBUtils.closeContent(putRes);
    }
}

46. CouchDBOperationUtils#dropDatabase()

Project: Kundera
Source File: CouchDBOperationUtils.java
View license
public void dropDatabase(String keyspace, String host, int port) throws URISyntaxException, ClientProtocolException, IOException {
    initiateClient(host, port);
    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), CouchDBConstants.URL_SAPRATOR + keyspace.toLowerCase(), null, null);
    HttpDelete delete = new HttpDelete(uri);
    HttpResponse delReq = null;
    try {
        // creating database.
        logger.info("Droping database " + keyspace);
        delReq = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));
    } finally {
        CouchDBUtils.closeContent(delReq);
    }
}

47. AsyncHttpRequest#makeRequest()

View license
private void makeRequest() throws IOException {
    if (isCancelled()) {
        return;
    }
    // Fixes #115
    if (request.getURI().getScheme() == null) {
        // subclass of IOException so processed in the caller
        throw new MalformedURLException("No valid URI scheme was provided");
    }
    HttpResponse response = client.execute(request, context);
    if (!isCancelled() && responseHandler != null) {
        responseHandler.sendResponseMessage(response);
    }
}

48. UploadTest#loadPathInvalidResponse()

Project: LiveSDK-for-Android
Source File: UploadTest.java
View license
@Override
protected void loadPathInvalidResponse(String requestPath) throws Exception {
    super.loadPathInvalidResponse(requestPath);
    // we have to load the uploadLocationResponse first
    // so store the invalidResponse and load it in again after the uploadlocation
    // has been added.
    HttpResponse invalidResponse = this.mockClient.getHttpResponse();
    this.mockClient.clearHttpResponseQueue();
    this.loadUploadLocationResponseBody();
    this.mockClient.addHttpResponse(invalidResponse);
}

49. ConfluenceClient#getSpaces()

Project: manifoldcf
Source File: ConfluenceClient.java
View license
private Spaces getSpaces() throws Exception {
    String url = String.format("%s://%s:%s%s%sgetSpaces", protocol, host, port, path, AUTHORITY_PATH);
    logger.debug("[Processing] Hitting url for getting Confluence spaces : {}", url);
    HttpPost httpPost = createPostRequest(url);
    httpPost.setEntity(new StringEntity("[]"));
    HttpResponse response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new ConfluenceException("Confluence error. " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
    Spaces spaces = spacesFromHttpEntity(entity);
    EntityUtils.consume(entity);
    return spaces;
}

50. ConfluenceClient#getSpacePermissionsForUser()

Project: manifoldcf
Source File: ConfluenceClient.java
View license
private List<String> getSpacePermissionsForUser(Space space, String username) throws Exception {
    String url = String.format("%s://%s:%s%s%sgetPermissionsForUser", protocol, host, port, path, AUTHORITY_PATH);
    logger.debug("[Processing] Hitting url {} for getting Confluence permissions for user {} in space {}", url, username, space.getKey());
    HttpPost httpPost = createPostRequest(url);
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(space.getKey());
    jsonArray.put(username);
    StringEntity stringEntity = new StringEntity(jsonArray.toString());
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new ConfluenceException("Confluence error. " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
    List<String> permissions = permissionsFromHttpEntity(entity);
    EntityUtils.consume(entity);
    return permissions;
}

51. UbuntuOneSynchronizer#executeRequest()

View license
protected HttpResponse executeRequest(HttpUriRequest request) throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpParams httpParameters = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
    HttpConnectionParams.setSoTimeout(httpParameters, 60000);
    HttpResponse response = null;
    int retries = 3;
    while (retries-- > 0) {
        this.signRequest(request);
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 400 || statusCode == 401) {
            invalidate();
        } else {
            return response;
        }
    }
    return response;
}

52. HttpMessageHandler#handleMessage()

Project: mr4c
Source File: HttpMessageHandler.java
View license
public void handleMessage(Message msg) throws IOException {
    HttpPost post = new HttpPost(m_uri);
    post.setEntity(new StringEntity(msg.getContent(), ContentType.create(msg.getContentType())));
    s_log.info("POSTing message to [{}]: [{}]", m_uri, msg);
    HttpResponse response = m_client.execute(post);
    StatusLine statusLine = response.getStatusLine();
    s_log.info("Status line: {}", statusLine);
    s_log.info("Content: {}", toString(response.getEntity()));
    if (statusLine.getStatusCode() >= 300) {
        throw new IOException(statusLine.toString());
    }
}

53. GetAndPostIntegrationTest#testPostRequestWithMultipartExtremEncodedParameters()

View license
@Test
public void testPostRequestWithMultipartExtremEncodedParameters() throws Exception {
    this.testServer.response = "testPostRequestWithMultipartEncodedParameters";
    HttpPost httppost = new HttpPost("http://localhost:8192/chin");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "sfsadfasdf", Charset.forName("UTF-8"));
    reqEntity.addPart("specialString", new StringBody("?????????????????", "text/plain", Charset.forName("UTF-8")));
    reqEntity.addPart("gender", new StringBody("????", Charset.forName("UTF-8")) {

        @Override
        public String getFilename() {
            return "????";
        }
    });
    httppost.setEntity(reqEntity);
    HttpResponse response = this.httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity, "UTF-8");
    assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;gender=????;specialString=?????????????????", responseBody);
}

54. GetAndPostIntegrationTest#testPostRequestWithEncodedParameters()

View license
@Test
public void testPostRequestWithEncodedParameters() throws Exception {
    this.testServer.response = "testPostRequestWithEncodedParameters";
    HttpPost httppost = new HttpPost("http://localhost:8192/encodingtest");
    HttpResponse response = this.httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    assertEquals("<html><head><title>Testé ça</title></head><body>Testé ça</body></html>", responseBody);
}

55. GZipIntegrationTest#contentShouldNotBeGzippedIfContentLengthIsAddedManually()

Project: nanohttpd
Source File: GZipIntegrationTest.java
View license
@Test
public void contentShouldNotBeGzippedIfContentLengthIsAddedManually() throws IOException {
    testServer.response = NanoHTTPD.newFixedLengthResponse("This is a test");
    testServer.response.addHeader("Content-Length", "" + ("This is a test".getBytes("UTF-8").length));
    HttpGet request = new HttpGet("http://localhost:8192/");
    request.addHeader("Accept-encoding", "gzip");
    HttpResponse response = httpclient.execute(request);
    Header contentEncoding = response.getFirstHeader("content-encoding");
    assertNull("Content-Encoding should not be set when manually setting content-length", contentEncoding);
    assertEquals("This is a test", EntityUtils.toString(response.getEntity()));
}

56. TestNanoFileUpLoad#executeUpload()

Project: nanohttpd
Source File: TestNanoFileUpLoad.java
View license
private void executeUpload(CloseableHttpClient httpclient, String textFileName, HttpPost post) throws IOException, ClientProtocolException {
    FileBody fileBody = new FileBody(new File(textFileName), ContentType.DEFAULT_BINARY);
    StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    builder.addPart("text1", stringBody1);
    HttpEntity entity = builder.build();
    //
    post.setEntity(entity);
    HttpResponse response = httpclient.execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

57. ApplicationControllerTest#makeSureSessionsGetSentToClient()

View license
@Test
public void makeSureSessionsGetSentToClient() {
    // Some empty headers for now...
    Map<String, String> headers = Maps.newHashMap();
    // redirect will send a location: redirect in the headers
    HttpResponse httpResponse = ninjaTestBrowser.makeRequestAndGetResponse(withBaseUrl("/session"), headers);
    // Test that cookies get transported to consumer:
    assertEquals(1, ninjaTestBrowser.getCookies().size());
    Cookie cookie = ninjaTestBrowser.getCookieWithName("NINJA_SESSION");
    assertTrue(cookie != null);
    assertTrue(cookie.getValue().contains("___TS"));
    assertTrue(cookie.getValue().contains("username"));
    assertTrue(cookie.getValue().contains("kevin"));
}

58. AssetsControllerTest#testThatSettingOfMimeTypeWorks()

Project: ninja
Source File: AssetsControllerTest.java
View license
@Test
public void testThatSettingOfMimeTypeWorks() {
    // Some empty headers for now...
    Map<String, String> headers = Maps.newHashMap();
    // /redirect will send a location: redirect in the headers
    HttpResponse httpResponse = ninjaTestBrowser.makeRequestAndGetResponse(getServerAddress() + "assets/files/test_for_mimetypes.dxf", headers);
    // this is a mimetype nobody knows of...
    // but it is listetd in the ninja mimetypes... therefore it will be found:
    // case insensitivity makes test realistic
    String contentType = httpResponse.getHeaders("Content-Type")[0].getValue();
    assertThat("application/dxf; charset=UTF-8".equalsIgnoreCase(contentType), is(true));
}

59. AssetsControllerTest#testThatAssetsWork()

Project: ninja
Source File: AssetsControllerTest.java
View license
@Test
public void testThatAssetsWork() {
    // Some empty headers for now...
    Map<String, String> headers = Maps.newHashMap();
    // /redirect will send a location: redirect in the headers
    HttpResponse httpResponse = ninjaTestBrowser.makeRequestAndGetResponse(getServerAddress() + "assets/js/google-code-prettify/prettify.css", headers);
    assertEquals(200, httpResponse.getStatusLine().getStatusCode());
}

60. AssetsControllerTest#testThatMetaInfIntegrationWorks()

Project: ninja
Source File: AssetsControllerTest.java
View license
@Test
public void testThatMetaInfIntegrationWorks() {
    // Some empty headers for now...
    Map<String, String> headers = Maps.newHashMap();
    // /redirect will send a location: redirect in the headers
    HttpResponse httpResponse = ninjaTestBrowser.makeRequestAndGetResponse(getServerAddress() + "assets/webjars/bootstrap/3.3.4/css/bootstrap.min.css", headers);
    assertEquals(200, httpResponse.getStatusLine().getStatusCode());
}

61. AssetsControllerTest#testThatStaticAssetsDoNotSetNinjaCookies()

Project: ninja
Source File: AssetsControllerTest.java
View license
@Test
public void testThatStaticAssetsDoNotSetNinjaCookies() {
    // Some empty headers for now...
    Map<String, String> headers = Maps.newHashMap();
    headers.put("Cookie", "NINJA_FLASH=\"success=This+is+a+flashed+success+-+with+placeholder%3A+PLACEHOLDER\";Path=/");
    // /redirect will send a location: redirect in the headers
    HttpResponse httpResponse = ninjaTestBrowser.makeRequestAndGetResponse(getServerAddress() + "assets/files/test_for_mimetypes.dxf", headers);
    // static assets should not set any session information        
    // ... and static assets should not set any flash information
    assertEquals(null, httpResponse.getFirstHeader("Set-Cookie"));
}

62. NinjaTestBrowser#makeRequestAndGetResponse()

Project: ninja
Source File: NinjaTestBrowser.java
View license
public HttpResponse makeRequestAndGetResponse(String url, Map<String, String> headers) {
    HttpResponse response = null;
    try {
        HttpGet getRequest = new HttpGet(url);
        // add all headers
        for (Entry<String, String> header : headers.entrySet()) {
            getRequest.addHeader(header.getKey(), header.getValue());
        }
        response = httpClient.execute(getRequest);
        getRequest.reset();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return response;
}

63. Client#doGet()

Project: odo
Source File: Client.java
View license
protected static String doGet(String fullUrl, int timeout) throws Exception {
    HttpGet get = new HttpGet(fullUrl);
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), timeout);
    HttpConnectionParams.setSoTimeout(client.getParams(), timeout);
    HttpResponse response = client.execute(get);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String accumulator = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        accumulator += line;
        accumulator += "\n";
    }
    return accumulator;
}

64. OkApacheClientTest#contentEncoding()

Project: okhttp
Source File: OkApacheClientTest.java
View license
@Test
public void contentEncoding() throws Exception {
    String text = "{\"Message\": { \"text\": \"Hello, World!\" } }";
    server.enqueue(new MockResponse().setBody(gzip(text)).setHeader("Content-Encoding", "gzip"));
    HttpGet request = new HttpGet(server.url("/").url().toURI());
    // Not transparent gzip.
    request.setHeader("Accept-encoding", "gzip");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    Header[] encodingHeaders = response.getHeaders("Content-Encoding");
    assertEquals(1, encodingHeaders.length);
    assertEquals("gzip", encodingHeaders[0].getValue());
    assertNotNull(entity.getContentEncoding());
    assertEquals("gzip", entity.getContentEncoding().getValue());
    assertEquals(text, gunzip(entity));
}

65. ServiceJsonTest#serviceDocumentDollarFormatJson()

Project: olingo-odata2
Source File: ServiceJsonTest.java
View license
@Test
public void serviceDocumentDollarFormatJson() throws Exception {
    final HttpResponse response = callUri("?$format=json");
    // checkMediaType(response, HttpContentType.APPLICATION_JSON);
    String body = getBody(response);
    Assert.assertTrue(jsonDataResponseContains(body, "Buildings"));
    Assert.assertTrue(jsonDataResponseContains(body, "Employees"));
    Assert.assertTrue(jsonDataResponseContains(body, "Managers"));
    Assert.assertTrue(jsonDataResponseContains(body, "Photos"));
    Assert.assertTrue(jsonDataResponseContains(body, "Rooms"));
    Assert.assertTrue(jsonDataResponseContains(body, "Teams"));
}

66. ServiceJsonTest#serviceDocumentAcceptHeaderJson()

Project: olingo-odata2
Source File: ServiceJsonTest.java
View license
@Test
public void serviceDocumentAcceptHeaderJson() throws Exception {
    final HttpResponse response = callUri("", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_JSON);
    String body = getBody(response);
    Assert.assertTrue(jsonDataResponseContains(body, "Buildings"));
    Assert.assertTrue(jsonDataResponseContains(body, "Employees"));
    Assert.assertTrue(jsonDataResponseContains(body, "Managers"));
    Assert.assertTrue(jsonDataResponseContains(body, "Photos"));
    Assert.assertTrue(jsonDataResponseContains(body, "Rooms"));
    Assert.assertTrue(jsonDataResponseContains(body, "Teams"));
}

67. ServiceJsonTest#serviceDocumentAcceptHeaderInvalidCharset()

Project: olingo-odata2
Source File: ServiceJsonTest.java
View license
@Test
public void serviceDocumentAcceptHeaderInvalidCharset() throws Exception {
    final HttpResponse response = callUri("", HttpHeaders.ACCEPT, HttpContentType.APPLICATION_XML + "; charset=iso-latin-1", HttpStatusCodes.NOT_ACCEPTABLE);
    final String body = getBody(response);
    Map<String, String> prefixMap = new HashMap<String, String>();
    prefixMap.put("a", Edm.NAMESPACE_M_2007_08);
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
    assertXpathExists("/a:error", body);
    assertXpathExists("/a:error/a:code", body);
    assertXpathExists("/a:error/a:message", body);
}

68. ServiceXmlTest#serviceDocument()

Project: olingo-odata2
Source File: ServiceXmlTest.java
View license
@Test
public void serviceDocument() throws Exception {
    final HttpResponse response = callUri("/");
    checkMediaType(response, HttpContentType.APPLICATION_ATOM_SVC_UTF8);
    final String body = getBody(response);
    assertXpathEvaluatesTo("Employees", "/app:service/app:workspace/app:collection[@href=\"Employees\"]", body);
    assertXpathEvaluatesTo("Teams", "/app:service/app:workspace/app:collection[@href=\"Teams\"]", body);
    assertXpathEvaluatesTo("Rooms", "/app:service/app:workspace/app:collection[@href=\"Rooms\"]", body);
    assertXpathEvaluatesTo("Managers", "/app:service/app:workspace/app:collection[@href=\"Managers\"]", body);
    assertXpathEvaluatesTo("Buildings", "/app:service/app:workspace/app:collection[@href=\"Buildings\"]", body);
    assertXpathEvaluatesTo("Photos", "/app:service/app:workspace/app:collection[@href=\"Photos\"]", body);
    notFound("invalid.svc");
}

69. BasicBatchTest#testBatch()

Project: olingo-odata2
Source File: BasicBatchTest.java
View license
@Test
public void testBatch() throws Exception {
    final HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "$batch"));
    post.setHeader("Content-Type", "multipart/mixed;boundary=batch_98c1-8b13-36bb");
    HttpEntity entity = new StringEntity(REQUEST_PAYLOAD);
    post.setEntity(entity);
    HttpResponse response = getHttpClient().execute(post);
    assertNotNull(response);
    assertEquals(202, response.getStatusLine().getStatusCode());
    assertEquals("HTTP/1.1", response.getProtocolVersion().toString());
    assertTrue(response.containsHeader("Content-Length"));
    assertTrue(response.containsHeader("Content-Type"));
    assertTrue(response.containsHeader("DataServiceVersion"));
    assertTrue(response.getEntity().getContentType().getValue().matches(REG_EX));
    assertNotNull(response.getEntity().getContent());
    String body = StringHelper.inputStreamToString(response.getEntity().getContent(), true);
    assertTrue(body.contains("Content-Id: mimeHeaderContentId1"));
    assertTrue(body.contains("Content-Id: requestHeaderContentId1"));
    assertTrue(body.contains("Content-Id: mimeHeaderContentId2"));
    assertTrue(body.contains("Content-Id: requestHeaderContentId2"));
}

70. BasicBatchTest#testBatchUriEncoded()

Project: olingo-odata2
Source File: BasicBatchTest.java
View license
@Test
public void testBatchUriEncoded() throws Exception {
    final HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "%24batch"));
    post.setHeader("Content-Type", "multipart/mixed;boundary=batch_98c1-8b13-36bb");
    HttpEntity entity = new StringEntity(REQUEST_PAYLOAD);
    post.setEntity(entity);
    HttpResponse response = getHttpClient().execute(post);
    assertNotNull(response);
    assertEquals(202, response.getStatusLine().getStatusCode());
    assertEquals("HTTP/1.1", response.getProtocolVersion().toString());
    assertTrue(response.containsHeader("Content-Length"));
    assertTrue(response.containsHeader("Content-Type"));
    assertTrue(response.containsHeader("DataServiceVersion"));
    assertTrue(response.getEntity().getContentType().getValue().matches(REG_EX));
    assertNotNull(response.getEntity().getContent());
    String body = StringHelper.inputStreamToString(response.getEntity().getContent(), true);
    assertTrue(body.contains("Content-Id: mimeHeaderContentId1"));
    assertTrue(body.contains("Content-Id: requestHeaderContentId1"));
    assertTrue(body.contains("Content-Id: mimeHeaderContentId2"));
    assertTrue(body.contains("Content-Id: requestHeaderContentId2"));
}

71. BasicBatchTest#testBatchInvalidContentTypeForPut()

Project: olingo-odata2
Source File: BasicBatchTest.java
View license
@Test
public void testBatchInvalidContentTypeForPut() throws Exception {
    final HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "$batch"));
    post.setHeader("Content-Type", "multipart/mixed;boundary=batch_98c1-8b13-36bb");
    String replacedEntity = REQUEST_PAYLOAD.replace("Content-Type: application/json;odata=verbose" + CRLF, "");
    HttpEntity entity = new StringEntity(replacedEntity);
    post.setEntity(entity);
    HttpResponse response = getHttpClient().execute(post);
    assertNotNull(response);
    assertEquals(202, response.getStatusLine().getStatusCode());
    assertEquals("HTTP/1.1", response.getProtocolVersion().toString());
    assertTrue(response.containsHeader("Content-Length"));
    assertTrue(response.containsHeader("Content-Type"));
    assertTrue(response.containsHeader("DataServiceVersion"));
    assertTrue(response.getEntity().getContentType().getValue().matches(REG_EX));
    assertNotNull(response.getEntity().getContent());
    String body = StringHelper.inputStreamToString(response.getEntity().getContent(), true);
    assertTrue(body.contains("Content-Id: mimeHeaderContentId1"));
    assertTrue(body.contains("Content-Id: requestHeaderContentId1"));
    assertTrue(body.contains("HTTP/1.1 415 Unsupported Media Type"));
}

72. BasicHttpTest#get()

Project: olingo-odata2
Source File: BasicHttpTest.java
View license
@Test
public void get() throws Exception {
    HttpResponse response = executeGetRequest("$metadata");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    assertEquals("metadata", StringHelper.inputStreamToString(response.getEntity().getContent()));
    response = executeGetRequest("//////$metadata");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    StringHelper.inputStreamToString(response.getEntity().getContent());
    response = executeGetRequest("/./$metadata");
    assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), response.getStatusLine().getStatusCode());
    StringHelper.inputStreamToString(response.getEntity().getContent());
    response = executeGetRequest("$metadata/./");
    assertEquals(HttpStatusCodes.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode());
}

73. BasicHttpTest#head()

Project: olingo-odata2
Source File: BasicHttpTest.java
View license
@Test
public void head() throws Exception {
    HttpResponse response = executeHeadRequest("/");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    assertNull(response.getEntity());
    response = executeHeadRequest("$metadata");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    assertNull(response.getEntity());
    response = executeHeadRequest("//////$metadata");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    assertNull(response.getEntity());
    response = executeHeadRequest("/./$metadata");
    assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), response.getStatusLine().getStatusCode());
    assertNull(response.getEntity());
    response = executeHeadRequest("$metadata/./");
    assertEquals(HttpStatusCodes.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode());
}

74. BasicHttpTest#putWithContent()

Project: olingo-odata2
Source File: BasicHttpTest.java
View license
@Test
public void putWithContent() throws Exception {
    final HttpPut put = new HttpPut(URI.create(getEndpoint().toString()));
    final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<entry xmlns=\"" + Edm.NAMESPACE_ATOM_2005 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\"" + " xmlns:d=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xml:base=\"https://server.at.some.domain.com/path.to.some.service/ReferenceScenario.svc/\">" + "</entry>";
    final HttpEntity entity = new StringEntity(xml);
    put.setEntity(entity);
    final HttpResponse response = getHttpClient().execute(put);
    assertEquals(HttpStatusCodes.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatusLine().getStatusCode());
    final String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertTrue(payload.contains("error"));
}

75. BasicHttpTest#postMethodNotAllowedWithContent()

Project: olingo-odata2
Source File: BasicHttpTest.java
View license
@Test
public void postMethodNotAllowedWithContent() throws Exception {
    final HttpPost post = new HttpPost(URI.create(getEndpoint().toString()));
    final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<entry xmlns=\"" + Edm.NAMESPACE_ATOM_2005 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\"" + " xmlns:d=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xml:base=\"https://server.at.some.domain.com/path.to.some.service/ReferenceScenario.svc/\">" + "</entry>";
    final HttpEntity entity = new StringEntity(xml);
    post.setEntity(entity);
    final HttpResponse response = getHttpClient().execute(post);
    assertEquals(HttpStatusCodes.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatusLine().getStatusCode());
    final String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertTrue(payload.contains("error"));
}

76. ContextTest#checkContextExists()

Project: olingo-odata2
Source File: ContextTest.java
View license
@Test
public void checkContextExists() throws ClientProtocolException, IOException, ODataException {
    assertNull(getService().getProcessor().getContext());
    final HttpResponse response = executeGetRequest("$metadata");
    final ODataContext context = getService().getProcessor().getContext();
    assertNotNull(context);
    final ODataService service = context.getService();
    assertNotNull(service);
    assertEquals(Status.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    assertEquals("$metadata", context.getPathInfo().getODataSegments().get(0).getPath());
}

77. DebugDisabledTest#checkNoDebugCallbackMustResultInNoDebugResponse()

View license
@Test
public void checkNoDebugCallbackMustResultInNoDebugResponse() throws Exception {
    startCustomServer(FitStaticServiceFactory.class);
    HttpResponse response = executeGetRequest("/?odata-debug=json");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><servicedocument/>", payload);
    response = executeGetRequest("/?odata-debug=html");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><servicedocument/>", payload);
    response = executeGetRequest("/?odata-debug=download");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><servicedocument/>", payload);
    stopCustomServer();
}

78. DebugDisabledTest#checkDebugCallbackFalseMustResultInNoDebugResponse()

View license
@Test
public void checkDebugCallbackFalseMustResultInNoDebugResponse() throws Exception {
    startCustomServer(DebugCallbackFactoryFlase.class);
    HttpResponse response = executeGetRequest("/?odata-debug=json");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><servicedocument/>", payload);
    response = executeGetRequest("/?odata-debug=html");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><servicedocument/>", payload);
    response = executeGetRequest("/?odata-debug=download");
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><servicedocument/>", payload);
    stopCustomServer();
}

79. ExceptionsTest#exceptionBasicTest()

Project: olingo-odata2
Source File: ExceptionsTest.java
View license
@Test
public void exceptionBasicTest() throws Exception {
    final HttpResponse response = executeGetRequest("NoContainer.NoEntitySet()");
    assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), response.getStatusLine().getStatusCode());
    final String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
    Map<String, String> prefixMap = new HashMap<String, String>();
    prefixMap.put("a", Edm.NAMESPACE_M_2007_08);
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
    assertXpathExists("a:error", payload);
    assertXpathExists("/a:error/a:code", payload);
    assertXpathExists("/a:error/a:message[@xml:lang=\"en\"]", payload);
}

80. HttpExceptionResponseTest#test404HttpNotFound()

View license
@Test
public void test404HttpNotFound() throws Exception {
    when(processor.readEntity(any(GetEntityUriInfo.class), any(String.class))).thenThrow(new ODataNotFoundException(ODataNotFoundException.ENTITY));
    final HttpResponse response = executeGetRequest("Managers('199')");
    assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), response.getStatusLine().getStatusCode());
    final String content = StringHelper.inputStreamToString(response.getEntity().getContent());
    Map<String, String> prefixMap = new HashMap<String, String>();
    prefixMap.put("a", Edm.NAMESPACE_M_2007_08);
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
    assertXpathExists("/a:error/a:code", content);
    assertXpathValuesEqual("\"" + MessageService.getMessage(Locale.ENGLISH, ODataNotFoundException.ENTITY).getText() + "\"", "/a:error/a:message", content);
}

81. LanguageNegotiationTest#testErrorInItalianLanguage()

View license
@Test
public void testErrorInItalianLanguage() throws ClientProtocolException, IOException, XpathException, SAXException {
    final HttpGet get = new HttpGet(URI.create(getEndpoint().toString() + "$metadata"));
    get.setHeader(HttpHeaders.ACCEPT_LANGUAGE, "it");
    HttpResponse response = getHttpClient().execute(get);
    String content = StringHelper.httpEntityToString(response.getEntity());
    assertXpathExists("/m:error/m:message", content);
    assertXpathExists("/m:error/m:message[@xml:lang=\"it\"]", content);
    assertXpathEvaluatesTo("eccezione comune", "/m:error/m:message/text()", content);
}

82. LanguageNegotiationTest#testErrorNoLanguage()

View license
@Test
public void testErrorNoLanguage() throws ClientProtocolException, IOException, XpathException, SAXException {
    final HttpGet get = new HttpGet(URI.create(getEndpoint().toString() + "$metadata"));
    HttpResponse response = getHttpClient().execute(get);
    String content = StringHelper.httpEntityToString(response.getEntity());
    assertXpathExists("/m:error/m:message", content);
    assertXpathExists("/m:error/m:message[@xml:lang=\"en\"]", content);
    assertXpathEvaluatesTo("Common exception", "/m:error/m:message/text()", content);
}

83. ServiceResolutionTest#testSplit0()

View license
@Test
public void testSplit0() throws IOException, ODataException {
    server.setPathSplit(0);
    startServer();
    final HttpGet get = new HttpGet(URI.create(server.getEndpoint().toString() + "/$metadata"));
    final HttpResponse response = httpClient.execute(get);
    assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
    final ODataContext ctx = service.getProcessor().getContext();
    assertNotNull(ctx);
    assertTrue(ctx.getPathInfo().getPrecedingSegments().isEmpty());
    assertEquals("$metadata", ctx.getPathInfo().getODataSegments().get(0).getPath());
}

84. DynamicSearchTest#testSearchOneStringParamWithAnd()

Project: hapi-fhir
Source File: DynamicSearchTest.java
View license
@Test
public void testSearchOneStringParamWithAnd() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?param1=param1value¶m1=param1value2");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());
    assertEquals(1, ourLastSearchParams.size());
    StringAndListParam andList = (StringAndListParam) ourLastSearchParams.get("param1");
    assertEquals(2, andList.getValuesAsQueryTokens().size());
    StringOrListParam orList = andList.getValuesAsQueryTokens().get(0);
    assertEquals(1, orList.getValuesAsQueryTokens().size());
    StringParam param1 = orList.getValuesAsQueryTokens().get(0);
    assertEquals("param1value", param1.getValue());
    orList = andList.getValuesAsQueryTokens().get(1);
    assertEquals(1, orList.getValuesAsQueryTokens().size());
    StringParam param1b = orList.getValuesAsQueryTokens().get(0);
    assertEquals("param1value2", param1b.getValue());
}

85. CreateTest#testCreate()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreate() throws Exception {
    Patient patient = new Patient();
    patient.addIdentifier().setValue("001");
    patient.addIdentifier().setValue("002");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
    httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(201, status.getStatusLine().getStatusCode());
    assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue());
    assertNull(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE));
    assertThat(ourLastResourceBody, stringContainsInOrder("<Patient ", "<identifier>", "<value value=\"001"));
    assertEquals(EncodingEnum.XML, ourLastEncoding);
}

86. CreateTest#testCreateById()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateById() throws Exception {
    Patient patient = new Patient();
    patient.addIdentifier().setValue("001");
    patient.addIdentifier().setValue("002");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/1234");
    httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(201, status.getStatusLine().getStatusCode());
    assertEquals("http://localhost:" + ourPort + "/Patient/1234/_history/002", status.getFirstHeader("location").getValue());
}

87. CreateTest#testCreateCustomType()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateCustomType() throws Exception {
    Observation obs = new Observation();
    obs.getIdentifier().setValue("001");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Observation");
    httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(obs), ContentType.create(Constants.CT_FHIR_JSON, "UTF-8")));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(201, status.getStatusLine().getStatusCode());
    assertEquals("http://localhost:" + ourPort + "/Observation/001/_history/002", status.getFirstHeader("location").getValue());
}

88. CreateTest#testCreateJson()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateJson() throws Exception {
    Patient patient = new Patient();
    patient.addIdentifier().setValue("001");
    patient.addIdentifier().setValue("002");
    patient.addName().addFamily("line1\nline2");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
    httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_JSON, "UTF-8")));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(201, status.getStatusLine().getStatusCode());
    assertEquals("http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue());
    ourLog.info(ourLastResourceBody);
    assertEquals("{\"resourceType\":\"Patient\",\"identifier\":[{\"value\":\"001\"},{\"value\":\"002\"}],\"name\":[{\"family\":[\"line1\\nline2\"]}]}", ourLastResourceBody);
}

89. CreateTest#testCreateWithNoParsed()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateWithNoParsed() throws Exception {
    Organization org = new Organization();
    org.addIdentifier().setValue("001");
    org.addIdentifier().setValue("002");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Organization");
    httpPost.setEntity(new StringEntity(ourCtx.newJsonParser().encodeResourceToString(org), ContentType.create(Constants.CT_FHIR_JSON, "UTF-8")));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(201, status.getStatusLine().getStatusCode());
    assertEquals("http://localhost:" + ourPort + "/Organization/001", status.getFirstHeader("location").getValue());
    assertNull(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE));
    assertThat(ourLastResourceBody, stringContainsInOrder("\"resourceType\":\"Organization\"", "\"identifier\"", "\"value\":\"001"));
    assertEquals(EncodingEnum.JSON, ourLastEncoding);
}

90. CreateTest#testCreateWithUnprocessableEntity()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateWithUnprocessableEntity() throws Exception {
    DiagnosticReport report = new DiagnosticReport();
    report.getIdentifier().setValue("001");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/DiagnosticReport");
    httpPost.setEntity(new StringEntity(ourCtx.newXmlParser().encodeResourceToString(report), ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(422, status.getStatusLine().getStatusCode());
    OperationOutcome outcome = ourCtx.newXmlParser().parseResource(OperationOutcome.class, new StringReader(responseContent));
    assertEquals("FOOBAR", outcome.getIssueFirstRep().getDetails().getValue());
}

91. CreateTest#testCreateWithWrongContentTypeJson()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateWithWrongContentTypeJson() throws Exception {
    Patient patient = new Patient();
    patient.addIdentifier().setValue("001");
    patient.addIdentifier().setValue("002");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
    String inputString = ourCtx.newXmlParser().encodeResourceToString(patient);
    ContentType inputCt = ContentType.create(Constants.CT_FHIR_JSON, "UTF-8");
    httpPost.setEntity(new StringEntity(inputString, inputCt));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(400, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("Unexpected char"));
}

92. CreateTest#testCreateWithWrongContentTypeXml()

Project: hapi-fhir
Source File: CreateTest.java
View license
@Test
public void testCreateWithWrongContentTypeXml() throws Exception {
    Patient patient = new Patient();
    patient.addIdentifier().setValue("001");
    patient.addIdentifier().setValue("002");
    HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient");
    String inputString = ourCtx.newJsonParser().encodeResourceToString(patient);
    ContentType inputCt = ContentType.create(Constants.CT_FHIR_XML, "UTF-8");
    httpPost.setEntity(new StringEntity(inputString, inputCt));
    HttpResponse status = ourClient.execute(httpPost);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info("Response was:\n{}", responseContent);
    assertEquals(400, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("Unexpected character"));
}

93. CustomTypeTest#testFindProfileItself()

Project: hapi-fhir
Source File: CustomTypeTest.java
View license
@Test
public void testFindProfileItself() throws Exception {
    ourServlet.setAddProfileTag(AddProfileTagEnum.ONLY_FOR_CUSTOM);
    ourReturnExtended = true;
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Profile/prof2?_pretty=true");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    ourLog.info(responseContent);
    Profile bundle = ourCtx.newXmlParser().parseResource(Profile.class, responseContent);
}

94. CustomTypeTest#testSearchReturnsNoProfileForExtendedType()

Project: hapi-fhir
Source File: CustomTypeTest.java
View license
@Test
public void testSearchReturnsNoProfileForExtendedType() throws Exception {
    ourServlet.setAddProfileTag(AddProfileTagEnum.NEVER);
    ourReturnExtended = true;
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());
    BundleEntry entry = bundle.getEntries().get(0);
    List<Tag> profileTags = entry.getCategories().getTagsWithScheme(Tag.HL7_ORG_PROFILE_TAG);
    assertEquals(0, profileTags.size());
}

95. CustomTypeTest#testSearchReturnsNoProfileForNormalType()

Project: hapi-fhir
Source File: CustomTypeTest.java
View license
@Test
public void testSearchReturnsNoProfileForNormalType() throws Exception {
    ourServlet.setAddProfileTag(AddProfileTagEnum.ONLY_FOR_CUSTOM);
    ourReturnExtended = false;
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());
    BundleEntry entry = bundle.getEntries().get(0);
    List<Tag> profileTags = entry.getCategories().getTagsWithScheme(Tag.HL7_ORG_PROFILE_TAG);
    assertEquals(0, profileTags.size());
}

96. CustomTypeTest#testSearchReturnsProfile()

Project: hapi-fhir
Source File: CustomTypeTest.java
View license
@Test
public void testSearchReturnsProfile() throws Exception {
    ourServlet.setAddProfileTag(AddProfileTagEnum.ONLY_FOR_CUSTOM);
    ourReturnExtended = true;
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());
    BundleEntry entry = bundle.getEntries().get(0);
    List<Tag> profileTags = entry.getCategories().getTagsWithScheme(Tag.HL7_ORG_PROFILE_TAG);
    assertEquals(1, profileTags.size());
    assertEquals("http://foo/profiles/Profile", profileTags.get(0).getTerm());
    Patient p = (Patient) bundle.getEntries().get(0).getResource();
    assertEquals("idaaa", p.getNameFirstRep().getFamilyAsSingleString());
}

97. CustomTypeTest#testSearchReturnsProfileForNormalType()

Project: hapi-fhir
Source File: CustomTypeTest.java
View license
@Test
public void testSearchReturnsProfileForNormalType() throws Exception {
    ourServlet.setAddProfileTag(AddProfileTagEnum.ALWAYS);
    ourReturnExtended = false;
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_id=aaa");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());
    BundleEntry entry = bundle.getEntries().get(0);
    List<Tag> profileTags = entry.getCategories().getTagsWithScheme(Tag.HL7_ORG_PROFILE_TAG);
    assertEquals(1, profileTags.size());
    assertEquals("http://hl7.org/fhir/profiles/Patient", profileTags.get(0).getTerm());
    Patient p = (Patient) bundle.getEntries().get(0).getResource();
    assertEquals("idaaa", p.getNameFirstRep().getFamilyAsSingleString());
}

98. DynamicSearchTest#testSearchOneStringParam()

Project: hapi-fhir
Source File: DynamicSearchTest.java
View license
@Test
public void testSearchOneStringParam() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?param1=param1value");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.getEntries().size());
    assertEquals(1, ourLastSearchParams.size());
    StringAndListParam andList = (StringAndListParam) ourLastSearchParams.get("param1");
    assertEquals(1, andList.getValuesAsQueryTokens().size());
    StringOrListParam orList = andList.getValuesAsQueryTokens().get(0);
    assertEquals(1, orList.getValuesAsQueryTokens().size());
    StringParam param1 = orList.getValuesAsQueryTokens().get(0);
    assertEquals("param1value", param1.getValue());
}

99. IncludeTest#testOneInclude()

Project: hapi-fhir
Source File: IncludeTest.java
View license
@Test
public void testOneInclude() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.size());
    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals(1, p.getName().size());
    assertEquals("Hello", p.getId().getIdPart());
    assertEquals("foo", p.getName().get(0).getFamilyFirstRep().getValue());
}

100. IncludeTest#testTwoInclude()

Project: hapi-fhir
Source File: IncludeTest.java
View license
@Test
public void testTwoInclude() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=bar");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.size());
    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals(2, p.getName().size());
    assertEquals("Hello", p.getId().getIdPart());
    Set<String> values = new HashSet<String>();
    values.add(p.getName().get(0).getFamilyFirstRep().getValue());
    values.add(p.getName().get(1).getFamilyFirstRep().getValue());
    assertThat(values, containsInAnyOrder("foo", "bar"));
}