Example usage for org.apache.http.message BasicHttpResponse setHeader

List of usage examples for org.apache.http.message BasicHttpResponse setHeader

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpResponse setHeader.

Prototype

public void setHeader(String str, String str2) 

Source Link

Usage

From source file:org.envirocar.app.test.dao.TrackDecoderTest.java

public void testTotalTrackCount() throws TrackRetrievalException {
    BasicHttpResponse response = new BasicHttpResponse(createStatusLine());
    response.setHeader("Link",
            "<https://envirocar.org/api/stable/users/matthes/tracks?limit=1&page=7>;rel=last;type=application/json, <https://envirocar.org/api/stable/users/matthes/tracks?limit=1&page=2>;rel=next;type=application/json");
    Integer count = new TrackDecoder().resolveTrackCount(response);

    Assert.assertTrue(count.intValue() == 7);

    response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 204, ""));
    response.setHeader("Link", "<https://envirocar.org/api/stable/users/matthes/tracks?page=6>;rel=last");
    count = new TrackDecoder().resolveTrackCount(response);

    Assert.assertTrue(count.intValue() == 6);

}

From source file:com.parse.ParseApacheHttpClientTest.java

@Test
public void testGetParseResponse() throws IOException {
    int statusCode = 200;
    String reasonPhrase = "test reason";
    ProtocolVersion protocol = new ProtocolVersion("HTTP", 1, 1);
    BasicStatusLine line = new BasicStatusLine(protocol, statusCode, reasonPhrase);
    BasicHttpResponse apacheResponse = new BasicHttpResponse(line);
    String content = "content";
    StringEntity entity = new StringEntity(content);
    apacheResponse.setEntity(entity);//from w w  w  .  j a v  a  2  s . c  om
    apacheResponse.setHeader("Content-Length", String.valueOf(entity.getContentLength()));

    ParseApacheHttpClient parseClient = new ParseApacheHttpClient(10000, null);
    ParseHttpResponse parseResponse = parseClient.getResponse(apacheResponse);

    // Verify status code
    assertEquals(statusCode, parseResponse.getStatusCode());
    // Verify reason phrase
    assertEquals(reasonPhrase, parseResponse.getReasonPhrase());
    // Verify content length
    assertEquals(7, parseResponse.getTotalSize());
    // Verify content
    // Can not read apacheResponse entity to compare since it has been read during
    // creating parseResponse
    assertArrayEquals(content.getBytes(), ParseIOUtils.toByteArray(parseResponse.getContent()));
}

From source file:com.comcast.drivethru.client.ClientExecuteTest.java

@Test
public void testExecuteSuccess() throws Exception {
    String body = "this is a response from the internet";
    HttpEntity entity = new ByteArrayEntity(body.getBytes());

    BasicHttpResponse resp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    resp.setHeader("a", "apple");
    resp.setHeader("b", "bobcat");
    resp.setHeader("Content-Type", "text/plain");
    resp.setEntity(entity);/*w  ww  . j av  a  2 s  . c o m*/

    RestRequest request = new RestRequest(new URL().setPath("/").addQuery("q", "stuff"), POST);
    request.setContentType("application/json");
    request.setBody("{ \"name\" : \"Clark\" }");
    request.addHeader("x-transaction-id", "0011223344556677");

    Capture<HttpPost> capture = EasyMock.newCapture();
    Capture<HttpPost> capture2 = EasyMock.newCapture();

    HttpClient delegate = createMock(HttpClient.class);
    expect(delegate.execute(capture(capture))).andReturn(resp);

    SecurityProvider securityProvider = createMock(SecurityProvider.class);
    securityProvider.sign(capture(capture2));
    expectLastCall();

    replay(delegate, securityProvider);

    String base = "http://www.google.com";
    DefaultRestClient client = new DefaultRestClient(base, delegate);
    client.addDefaultHeader("Fintan", "The Salmon of Knowledge");
    client.setSecurityProvider(securityProvider);

    RestResponse response = client.execute(request);
    client.close();

    assertEquals(response.getBodyString(), body);
    assertEquals(response.getStatusCode(), 200);
    assertEquals(response.getStatusMessage(), "OK");
    assertEquals(response.getContentType(), "text/plain");
    assertEquals(response.getHeaderValue("a"), "apple");
    assertEquals(response.getHeaderValue("b"), "bobcat");

    /* Verify the constructed request object */
    assertTrue(capture.hasCaptured());
    HttpPost req = capture.getValue();
    assertEquals(req.getLastHeader("Content-Type").getValue(), "application/json");
    assertEquals(req.getLastHeader("x-transaction-id").getValue(), "0011223344556677");
    assertEquals(req.getLastHeader("Fintan").getValue(), "The Salmon of Knowledge");
    assertEquals(req.getURI().toString(), "http://www.google.com/?q=stuff");

    /* Verify the "aborted" status of the request */
    assertEquals(req.isAborted(), true);

    /* Read and verify the contents of the request */
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(req.getEntity().getContent(), baos);
    assertEquals(baos.toString(), "{ \"name\" : \"Clark\" }");

    /* Verify Security was called with same element */
    assertTrue(capture2.hasCaptured());
    assertSame(capture2.getValue(), req);

    verify(delegate, securityProvider);
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void test302Redirect() throws Exception {
    HttpGet get = new HttpGet("http://example.com/302");
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    BasicHttpResponse redirect = new BasicHttpResponse(_302);
    redirect.setHeader("Location", "http://example.com/200");
    responses.add(redirect);//from  w  ww . j a  v a 2  s  . com
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }
    });
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void test302RedirectTarget() throws Exception {
    HttpContext localContext = new BasicHttpContext();
    HttpGet get = new HttpGet("http://example.com/302");
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    BasicHttpResponse redirect = new BasicHttpResponse(_302);
    redirect.setHeader("Location", "http://example.com/200");
    responses.add(redirect);//  ww w  . j  a  v a 2s  . c  o m
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            return null;
        }
    }, localContext);
    HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null);
    assertEquals("http://example.com/200", root.resolve(req.getURI()).toASCIIString());
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testAuthentication() throws Exception {
    HttpGet get = new HttpGet("http://example.com/protected");
    HttpContext localContext = new BasicHttpContext();
    List<String> authpref = Collections.singletonList(AuthPolicy.BASIC);
    AuthScope scope = new AuthScope("example.com", -1);
    UsernamePasswordCredentials cred = new UsernamePasswordCredentials("Aladdin", "open sesame");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(scope, cred);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    get.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    get.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    BasicHttpResponse unauth = new BasicHttpResponse(_401);
    unauth.setHeader("WWW-Authenticate", "Basic realm=\"insert realm\"");
    responses.add(unauth);//from   w  ww .j a va 2  s.  c  o  m
    responses.add(new BasicHttpResponse(_200));
    client.execute(get, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
            assertContains("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", asString(response.getEntity()));
            return null;
        }
    }, localContext);
}

From source file:org.elasticsearch.client.RequestLoggerTests.java

public void testTraceResponse() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int statusCode = randomIntBetween(200, 599);
    String reasonPhrase = "REASON";
    BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase);
    String expected = "# " + statusLine.toString();
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    int numHeaders = randomIntBetween(0, 3);
    for (int i = 0; i < numHeaders; i++) {
        httpResponse.setHeader("header" + i, "value");
        expected += "\n# header" + i + ": value";
    }/*  w w  w.  j a  v  a  2  s .co  m*/
    expected += "\n#";
    boolean hasBody = getRandom().nextBoolean();
    String responseBody = "{\n  \"field\": \"value\"\n}";
    if (hasBody) {
        expected += "\n# {";
        expected += "\n#   \"field\": \"value\"";
        expected += "\n# }";
        HttpEntity entity;
        switch (randomIntBetween(0, 2)) {
        case 0:
            entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
            break;
        case 1:
            //test a non repeatable entity
            entity = new InputStreamEntity(
                    new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)),
                    ContentType.APPLICATION_JSON);
            break;
        case 2:
            // Evil entity without a charset
            entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null));
            break;
        default:
            throw new UnsupportedOperationException();
        }
        httpResponse.setEntity(entity);
    }
    String traceResponse = RequestLogger.buildTraceResponse(httpResponse);
    assertThat(traceResponse, equalTo(expected));
    if (hasBody) {
        //check that the body is still readable as most entities are not repeatable
        String body = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        assertThat(body, equalTo(responseBody));
    }
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void test302CachedRedirectTarget() throws Exception {
    do {/*from w  w w  .  j av  a 2 s. c  om*/
        HttpGet get = new HttpGet("http://example.com/302");
        get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        BasicHttpResponse redirect = new BasicHttpResponse(_302);
        redirect.setHeader("Location", "http://example.com/200");
        redirect.setHeader("Cache-Control", "public,max-age=3600");
        responses.add(redirect);
        BasicHttpResponse doc = new BasicHttpResponse(_200);
        doc.setHeader("Cache-Control", "public,max-age=3600");
        responses.add(doc);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
                return null;
            }
        });
    } while (false);
    do {
        HttpContext localContext = new BasicHttpContext();
        HttpGet get = new HttpGet("http://example.com/302");
        get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        BasicHttpResponse redirect = new BasicHttpResponse(_302);
        redirect.setHeader("Location", "http://example.com/200");
        redirect.setHeader("Cache-Control", "public,max-age=3600");
        responses.add(redirect);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_302.getStatusCode(), response.getStatusLine().getStatusCode());
                return null;
            }
        }, localContext);
        HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        URI root = new URI(host.getSchemeName(), null, host.getHostName(), -1, "/", null, null);
        assertEquals("http://example.com/302", root.resolve(req.getURI()).toASCIIString());
    } while (false);
}

From source file:org.callimachusproject.auth.DigestPasswordAccessor.java

public HttpResponse getPersistentLogin(String iri) throws OpenRDFException, IOException {
    DetachedRealm realm = realms.getRealm(iri);
    if (realm == null)
        return null;
    String secret = realm.getOriginSecret();
    String nonce = nextNonce();/*  www.j  a  v  a 2 s .c o  m*/
    BasicHttpResponse resp = new BasicHttpResponse(_200);
    resp.addHeader("Set-Cookie",
            digestNonce + nonce + ";Max-Age=" + THREE_MONTHS + ";Path=/;HttpOnly" + digestNonceSecure);
    resp.addHeader("Cache-Control", "private");
    resp.setHeader("Content-Type", "text/plain;charset=UTF-8");
    String hash = md5(nonce + ":" + secret);
    resp.setEntity(new StringEntity(hash, Charset.forName("UTF-8")));
    return resp;
}

From source file:org.callimachusproject.auth.DetachedRealm.java

public HttpResponse unauthorized(String method, Object resource, Map<String, String[]> req, HttpEntity body)
        throws Exception {
    HttpResponse unauth = unauthorizedHeaders(method, resource, req, body);
    if (unauthorized == null)
        return unauth;
    try {/*from   w  ww.  j  av  a2  s .c o  m*/
        BasicHttpResponse resp;
        if (unauth == null) {
            resp = new BasicHttpResponse(_401);
        } else {
            resp = new BasicHttpResponse(unauth.getStatusLine());
            for (Header hd : unauth.getAllHeaders()) {
                if (hd.getName().equalsIgnoreCase("Transfer-Encoding"))
                    continue;
                if (hd.getName().toLowerCase().startsWith("content-"))
                    continue;
                resp.addHeader(hd);
            }
        }
        resp.setHeader("Cache-Control", "no-store");
        if (inUnauthorized.get() == null) {
            inUnauthorized.set(true);
            HttpEntity entity = client.getEntity(unauthorized, "text/html;charset=UTF-8");
            resp.setEntity(entity);
        } else {
            String via = Arrays.asList(req.get("via")).toString();
            resp.setEntity(new StringEntity(via + " is unauthorized"));
        }
        return resp;
    } finally {
        inUnauthorized.remove();
        if (unauth != null) {
            EntityUtils.consume(unauth.getEntity());
        }
    }
}