Example usage for org.apache.http.client.methods CloseableHttpResponse containsHeader

List of usage examples for org.apache.http.client.methods CloseableHttpResponse containsHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse containsHeader.

Prototype

boolean containsHeader(String str);

Source Link

Usage

From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java

private static String getErrorMessage(HttpUriRequest request, CloseableHttpResponse response) {
    String controllerHost = null;
    String controllerVersion = null;
    if (response.containsHeader(CommonConstants.Controller.HOST_HTTP_HEADER)) {
        controllerHost = response.getFirstHeader(CommonConstants.Controller.HOST_HTTP_HEADER).getValue();
        controllerVersion = response.getFirstHeader(CommonConstants.Controller.VERSION_HTTP_HEADER).getValue();
    }/*from w  ww.  j  av  a2 s .  c  o m*/
    StatusLine statusLine = response.getStatusLine();
    String reason;
    try {
        reason = new JSONObject(EntityUtils.toString(response.getEntity())).getString("error");
    } catch (Exception e) {
        reason = "Failed to get reason";
    }
    String errorMessage = String.format(
            "Got error status code: %d (%s) with reason: \"%s\" while sending request: %s",
            statusLine.getStatusCode(), statusLine.getReasonPhrase(), reason, request.getURI());
    if (controllerHost != null) {
        errorMessage = String.format("%s to controller: %s, version: %s", errorMessage, controllerHost,
                controllerVersion);
    }
    return errorMessage;
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java

private static String assert200Ok(CloseableHttpResponse res, String expectedContentType, String expectedContent)
        throws Exception {

    assertStatusLine(res, "HTTP/1.1 200 OK");

    // Ensure that the 'Last-Modified' header exists and is well-formed.
    final String lastModified;
    assertThat(res.containsHeader(HttpHeaders.LAST_MODIFIED), is(true));
    lastModified = res.getFirstHeader(HttpHeaders.LAST_MODIFIED).getValue();
    HttpHeaderDateFormat.get().parse(lastModified);

    // Ensure the content and its type are correct.
    assertThat(EntityUtils.toString(res.getEntity()), is(expectedContent));

    if (expectedContentType != null) {
        assertThat(res.containsHeader(HttpHeaders.CONTENT_TYPE), is(true));
        assertThat(res.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(), startsWith(expectedContentType));
    } else {//  www. j a va2 s.  co m
        assertThat(res.containsHeader(HttpHeaders.CONTENT_TYPE), is(false));
    }

    return lastModified;
}

From source file:io.crate.rest.AdminUIHttpIntegrationTest.java

private CloseableHttpResponse executeAndDefaultAssertions(HttpUriRequest request) throws IOException {
    CloseableHttpResponse resp = httpClient.execute(request);
    assertThat(resp.containsHeader("Connection"), is(false));
    return resp;/*from w  ww. j  av a 2  s.  c  o m*/
}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

protected CloseableHttpResponse executeAndDefaultAssertions(HttpUriRequest request) throws IOException {
    CloseableHttpResponse resp = httpClient.execute(request);
    assertThat(resp.containsHeader("Connection"), is(false));
    return resp;/*from w w  w.j av a 2 s  .c om*/
}

From source file:com.cloud.network.nicira.NiciraRestClient.java

private String responseToErrorMessage(final CloseableHttpResponse response) {
    String errorMessage = response.getStatusLine().toString();
    if (response.containsHeader(CONTENT_TYPE)
            && TEXT_HTML_CONTENT_TYPE.equals(response.getFirstHeader(CONTENT_TYPE).getValue())) {
        try {/*w ww  .  jav a2  s . c  o  m*/
            final HttpEntity entity = response.getEntity();
            final String respobnseBody = EntityUtils.toString(entity);
            errorMessage = respobnseBody.subSequence(0, maxResponseErrorMesageLength).toString();
        } catch (final IOException e) {
            s_logger.debug("Could not read repsonse body. Response: " + response, e);
        }
    }

    return errorMessage;
}

From source file:com.spectralogic.ds3client.networking.NetworkClientImpl.java

@Override
public WebResponse getResponse(final Ds3Request request) throws IOException {
    try (final RequestExecutor requestExecutor = new RequestExecutor(this.client, host, request)) {
        int redirectCount = 0;
        do {/*from   ww w .j a va  2 s. c  o m*/
            final CloseableHttpResponse response = requestExecutor.execute();
            String requestId = "Unknown";
            if (response.containsHeader(REQUEST_ID_HEADER)) {
                requestId = response.getFirstHeader(REQUEST_ID_HEADER).getValue();
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirectCount++;
                LOG.info("Performing retry - attempt: {} for request #{}", redirectCount, requestId);
                response.close();
            } else {
                LOG.info("Server responded with {} for request #{}", response.getStatusLine().getStatusCode(),
                        requestId);
                return new WebResponseImpl(response);
            }
        } while (redirectCount < this.connectionDetails.getRetries());

        throw new TooManyRedirectsException(redirectCount);
    }
}

From source file:io.joynr.messaging.bounceproxy.controller.RemoteBounceProxyFacade.java

private URI sendCreateChannelHttpRequest(ControlledBounceProxyInformation bpInfo, String ccid,
        String trackingId) throws IOException, JoynrProtocolException {

    // TODO jsessionid handling
    final String url = bpInfo.getLocationForBpc().toString() + "channels/?ccid=" + ccid;

    logger.debug("Using bounce proxy channel service URL: {}", url);

    HttpPost postCreateChannel = new HttpPost(url.trim());
    postCreateChannel.addHeader(ChannelServiceConstants.X_ATMOSPHERE_TRACKING_ID, trackingId);

    CloseableHttpResponse response = null;
    try {/* w w  w . j av  a 2s .  com*/
        response = httpclient.execute(postCreateChannel);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == HttpURLConnection.HTTP_CREATED) {
            // the channel was created successfully

            // check if bounce proxy ID header was sent correctly
            if (response.containsHeader("bp")) {
                String bounceProxyId = response.getFirstHeader("bp").getValue();
                if (bounceProxyId == null || !bounceProxyId.equals(bpInfo.getId())) {
                    throw new JoynrProtocolException("Bounce proxy ID '" + bounceProxyId
                            + "' returned by bounce proxy '" + bpInfo.getId() + "' does not match.");
                }
            } else {
                throw new JoynrProtocolException(
                        "No bounce proxy ID returned by bounce proxy '" + bpInfo.getId() + "'");
            }

            // get URI of newly created channel
            if (!response.containsHeader("Location")) {
                throw new JoynrProtocolException(
                        "No channel location returned by bounce proxy '" + bpInfo.getId() + "'");
            }

            String locationValue = response.getFirstHeader("Location").getValue();

            if (locationValue == null || locationValue.isEmpty()) {
                throw new JoynrProtocolException(
                        "Bounce proxy '" + bpInfo.getId() + "' didn't return a channel location.");
            }
            try {
                URI channelLocation = new URI(locationValue);

                logger.info("Successfully created channel '{}' on bounce proxy '{}'", ccid, bpInfo.getId());
                return channelLocation;
            } catch (Exception e) {
                throw new JoynrProtocolException("Cannot parse channel location '" + locationValue
                        + "' returned by bounce proxy '" + bpInfo.getId() + "'", e);
            }
        }

        // the bounce proxy is not excepted to reject this call as it was
        // chosen based on performance measurements sent by it
        logger.error("Failed to create channel on bounce proxy '{}'. Response: {}", bpInfo.getId(), response);
        throw new JoynrProtocolException(
                "Bounce Proxy " + bpInfo.getId() + " rejected channel creation (Response: " + response + ")");

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address)
        throws IOException {
    CloseableHttpResponse response = null;
    try {//from w  w  w. j ava2  s  .  co m
        HttpClientContext context = HttpClientContext.create();
        HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s",
                address.getHostName(), address.getPort(), uri));
        response = client.execute(httpHead, context);

        List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations == null) {
            // client might not follow redirects automatically
            if (response.containsHeader("location")) {
                List<String> redirects = new ArrayList<>(1);
                for (Header location : response.getHeaders("location")) {
                    redirects.add(location.getValue());
                }
                return redirects;
            }
            return Collections.emptyList();
        }

        List<String> redirects = new ArrayList<>(1);
        for (URI redirectLocation : redirectLocations) {
            redirects.add(redirectLocation.toString());
        }
        return redirects;
    } finally {
        if (response != null) {
            IOUtils.closeWhileHandlingException(response);
        }
    }
}

From source file:org.esigate.DriverTest.java

public void testHeadersPreservedWhenError500() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Dummy", "dummy");
    HttpEntity httpEntity = new StringEntity("Error", "UTF-8");
    response.setEntity(httpEntity);/*from  w w w. jav  a2  s  .  co  m*/
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    int statusCode = driverResponse.getStatusLine().getStatusCode();
    assertEquals("Status code", HttpStatus.SC_INTERNAL_SERVER_ERROR, statusCode);
    assertTrue("Header 'Dummy'", driverResponse.containsHeader("Dummy"));
}