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

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

Introduction

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

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

private static void assertMementoDatetimeHeaderPresent(final CloseableHttpResponse response) {
    assertNotNull("No memento datetime header set in response",
            response.getFirstHeader(MEMENTO_DATETIME_HEADER));
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

private static void assertMementoDatetimeHeaderMatches(final CloseableHttpResponse response,
        final String expected) {
    assertMementoDatetimeHeaderPresent(response);
    assertEquals("Response memento datetime did not match expected value", expected,
            response.getFirstHeader(MEMENTO_DATETIME_HEADER).getValue());
}

From source file:org.keycloak.testsuite.util.saml.ModifySamlResponseStepBuilder.java

protected HttpUriRequest handleRedirectBinding(CloseableHttpResponse currentResponse)
        throws Exception, IOException, URISyntaxException {
    NameValuePair samlParam = null;

    assertThat(currentResponse, statusCodeIsHC(Status.FOUND));
    String location = currentResponse.getFirstHeader("Location").getValue();
    URI locationUri = URI.create(location);

    List<NameValuePair> params = URLEncodedUtils.parse(locationUri, "UTF-8");
    for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
        NameValuePair param = it.next();
        if ("SAMLResponse".equals(param.getName()) || "SAMLRequest".equals(param.getName())) {
            assertThat("Only one SAMLRequest/SAMLResponse check", samlParam, nullValue());
            samlParam = param;/*  w w w.  j  a v  a  2s.  co  m*/
            it.remove();
        }
    }

    assertThat(samlParam, notNullValue());

    String base64EncodedSamlDoc = samlParam.getValue();
    InputStream decoded = RedirectBindingUtil.base64DeflateDecode(base64EncodedSamlDoc);
    String samlDoc = IOUtils.toString(decoded, GeneralConstants.SAML_CHARSET);
    IOUtils.closeQuietly(decoded);

    String transformed = getTransformer().transform(samlDoc);
    if (transformed == null) {
        return null;
    }

    final String attrName = this.targetAttribute != null ? this.targetAttribute : samlParam.getName();

    return createRequest(locationUri, attrName, transformed, params);
}

From source file:org.restcomm.connect.http.client.Downloader.java

public HttpResponseDescriptor fetch(final HttpRequestDescriptor descriptor)
        throws IllegalArgumentException, IOException, URISyntaxException, XMLStreamException {
    int code = -1;
    HttpRequest request = null;/*  w w w  .j  a  v  a2s .  c  om*/
    CloseableHttpResponse response = null;
    HttpRequestDescriptor temp = descriptor;
    HttpResponseDescriptor responseDescriptor = null;
    HttpResponseDescriptor rawResponseDescriptor = null;
    try {
        do {
            request = request(temp);
            //FIXME:should we externalize RVD encoding default?
            request.setHeader("http.protocol.content-charset", "UTF-8");
            if (descriptor.getTimeout() > 0) {
                HttpContext httpContext = new BasicHttpContext();
                httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG,
                        RequestConfig.custom().setConnectTimeout(descriptor.getTimeout())
                                .setSocketTimeout(descriptor.getTimeout())
                                .setConnectionRequestTimeout(descriptor.getTimeout()).build());
                response = client.execute((HttpUriRequest) request, httpContext);
            } else {
                response = client.execute((HttpUriRequest) request);
            }
            code = response.getStatusLine().getStatusCode();
            if (isRedirect(code)) {
                final Header header = response.getFirstHeader(HttpHeaders.LOCATION);
                if (header != null) {
                    final String location = header.getValue();
                    final URI uri = URI.create(location);
                    temp = new HttpRequestDescriptor(uri, temp.getMethod(), temp.getParameters());
                    continue;
                } else {
                    break;
                }
            }
            //                HttpResponseDescriptor httpResponseDescriptor = response(request, response);
            rawResponseDescriptor = response(request, response);
            responseDescriptor = validateXML(rawResponseDescriptor);
        } while (isRedirect(code));
        if (isHttpError(code)) {
            // TODO - usually this part of code is not reached. Error codes are part of error responses that do not pass validateXML above and an exception is thrown. We need to re-thing this
            String requestUrl = request.getRequestLine().getUri();
            String errorReason = response.getStatusLine().getReasonPhrase();
            String httpErrorMessage = String.format(
                    "Problem while fetching http resource: %s \n Http status code: %d \n Http status message: %s",
                    requestUrl, code, errorReason);
            logger.warning(httpErrorMessage);
        }
    } catch (Exception e) {
        logger.warning("Problem while trying to download RCML from {}, exception: {}", request.getRequestLine(),
                e);
        String statusInfo = "n/a";
        String responseInfo = "n/a";
        if (response != null) {
            // Build additional information to log. Include http status, url and a small fragment of the response.
            statusInfo = response.getStatusLine().toString();
            if (rawResponseDescriptor != null) {
                int truncatedSize = (int) Math.min(rawResponseDescriptor.getContentLength(),
                        LOGGED_RESPONSE_MAX_SIZE);
                if (rawResponseDescriptor.getContentAsString() != null) {
                    responseInfo = String.format("%s %s",
                            rawResponseDescriptor.getContentAsString().substring(0, truncatedSize),
                            (rawResponseDescriptor.getContentLength() < LOGGED_RESPONSE_MAX_SIZE ? "" : "..."));
                }
            }
        }
        logger.warning(
                String.format("Problem while trying to download RCML. URL: %s, Status: %s, Response: %s ",
                        request.getRequestLine(), statusInfo, responseInfo));
        throw e; // re-throw
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return responseDescriptor;
}

From source file:synapticloop.b2.request.BaseB2Request.java

/**
 * Execute an HTTP HEAD request and return the response for further parsing
 *
 * @return the response object//from   ww  w  .j a  v  a  2 s . c om
 *
 * @throws B2ApiException if something went wrong with the call
 * @throws IOException if there was an error communicating with the API service
 */
protected CloseableHttpResponse executeHead() throws B2ApiException, IOException {
    URI uri = this.buildUri();

    LOGGER.debug("HEAD request to URL '{}'", uri.toString());

    HttpHead httpHead = new HttpHead(uri);

    CloseableHttpResponse httpResponse = this.execute(httpHead);

    switch (httpResponse.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
        return httpResponse;
    }

    final B2ApiException failure = new B2ApiException(EntityUtils.toString(httpResponse.getEntity()),
            new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase()));
    if (httpResponse.containsHeader(HttpHeaders.RETRY_AFTER)) {
        throw failure
                .withRetry(Integer.valueOf(httpResponse.getFirstHeader(HttpHeaders.RETRY_AFTER).getValue()));
    }
    throw failure;
}

From source file:synapticloop.b2.request.BaseB2Request.java

/**
 * Execute a GET request, returning the data stream from the response.
 *
 * @return The response from the GET request
 *
 * @throws B2ApiException if there was an error with the request
 * @throws IOException if there was an error communicating with the API service
 *//*from   w w w .j a v  a  2s . co m*/
protected CloseableHttpResponse executeGet() throws B2ApiException, IOException {
    URI uri = this.buildUri();

    HttpGet httpGet = new HttpGet(uri);

    CloseableHttpResponse httpResponse = this.execute(httpGet);

    // you will either get an OK or a partial content
    switch (httpResponse.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_PARTIAL_CONTENT:
        return httpResponse;
    }

    final B2ApiException failure = new B2ApiException(EntityUtils.toString(httpResponse.getEntity()),
            new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase()));
    if (httpResponse.containsHeader(HttpHeaders.RETRY_AFTER)) {
        throw failure
                .withRetry(Integer.valueOf(httpResponse.getFirstHeader(HttpHeaders.RETRY_AFTER).getValue()));
    }
    throw failure;
}

From source file:synapticloop.b2.request.BaseB2Request.java

/**
 * Execute a POST request returning the response data as a String
 *
 * @return the response data as a string
 *
 * @throws B2ApiException if there was an error with the call, most notably
 *     a non OK status code (i.e. not 200)
 * @throws IOException if there was an error communicating with the API service
 *//*w  ww  . j a  va  2 s.  c om*/
protected CloseableHttpResponse executePost() throws B2ApiException, IOException {
    URI uri = this.buildUri();

    String postData = convertPostData();
    HttpPost httpPost = new HttpPost(uri);

    httpPost.setEntity(new StringEntity(postData, APPLICATION_JSON));
    CloseableHttpResponse httpResponse = this.execute(httpPost);

    switch (httpResponse.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
        return httpResponse;
    }

    final B2ApiException failure = new B2ApiException(EntityUtils.toString(httpResponse.getEntity()),
            new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase()));
    if (httpResponse.containsHeader(HttpHeaders.RETRY_AFTER)) {
        throw failure
                .withRetry(Integer.valueOf(httpResponse.getFirstHeader(HttpHeaders.RETRY_AFTER).getValue()));
    }
    throw failure;
}

From source file:synapticloop.b2.response.B2DownloadFileResponse.java

/**
 * Instantiate a bucket response with the JSON response as a string from 
 * the API call.  This response is then parsed into the relevant fields.
 * /*from   w w  w.  j a  v a  2 s .  c  om*/
 * @param response The HTTP response object
 * 
 * @throws B2ApiException if there was an error parsing the response
 * @throws IOException if there was an error communicating with the API service
 */
public B2DownloadFileResponse(CloseableHttpResponse response) throws B2ApiException, IOException {
    if (null != response.getEntity()) {
        stream = new HttpMethodReleaseInputStream(response);
    } else {
        // HEAD responses do not have an entity
        stream = new NullInputStream(0L);
        EntityUtils.consume(response.getEntity());
    }

    contentLength = Long.parseLong(response.getFirstHeader(HttpHeaders.CONTENT_LENGTH).getValue());
    contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    contentSha1 = response.getFirstHeader(B2ResponseHeaders.HEADER_X_BZ_CONTENT_SHA1).getValue();
    fileId = response.getFirstHeader(B2ResponseHeaders.HEADER_X_BZ_FILE_ID).getValue();
    fileName = response.getFirstHeader(B2ResponseHeaders.HEADER_X_BZ_FILE_NAME).getValue();
    uploadTimestamp = response.getFirstHeader(B2ResponseHeaders.HEADER_X_BZ_UPLOAD_TIMESTAMP).getValue();

    for (Header header : response.getAllHeaders()) {
        String headerName = header.getName();
        String headerValue = header.getValue();

        String headerNameLowerCase = headerName.toLowerCase(Locale.ENGLISH);

        if (headerNameLowerCase
                .startsWith(B2ResponseHeaders.HEADER_X_BZ_INFO_PREFIX.toLowerCase(Locale.ENGLISH))) {
            fileInfo.put(headerName.substring(B2ResponseHeaders.HEADER_X_BZ_INFO_PREFIX.length()), headerValue);
        } else {
            if (!ignoredHeaders.contains(headerNameLowerCase)) {
                LOGGER.warn("Found a header named '{}' with value '{}', that was not mapped", headerName,
                        headerValue);
            }
        }
    }
}