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

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

Introduction

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

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Return SHA256 payload hash value already set on HTTP request, or if none
 * is yet set calculate this value if possible.
 *
 * @param httpMethod//from   ww w  .  j  a  va 2  s  .com
 * the request's HTTP method just prior to sending
 * @return hex-encoded SHA256 hash of payload data.
 */
public static String awsV4GetOrCalculatePayloadHash(HttpUriRequest httpMethod) {
    // Lookup and return request payload SHA256 hash if present
    String requestPayloadHexSHA256Hash = null;
    Header sha256Header = httpMethod.getFirstHeader("x-amz-content-sha256");
    if (sha256Header != null) {
        return sha256Header.getValue();
    }

    // If request payload SHA256 isn't available, check for a payload
    if (httpMethod instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) httpMethod).getEntity();
        // We will automatically generate the SHA256 hash for a limited
        // set of payload entities, and bail out early for the
        // unsupported ones.
        if (entity instanceof StringEntity || entity instanceof ByteArrayEntity
                || entity instanceof RepeatableRequestEntity) {
            try {
                // Hack to get to underlying input stream if this has been
                // wrapped by JetS3t's ProgressMonitoredInputStream, since
                // the caller didn't intend to monitor the progress of this
                // last-ditch effort to calculate a SHA256 hash.
                InputStream requestIS = entity.getContent();
                while (requestIS instanceof ProgressMonitoredInputStream) {
                    requestIS = ((ProgressMonitoredInputStream) requestIS).getWrappedInputStream();
                }

                requestPayloadHexSHA256Hash = ServiceUtils.toHex(ServiceUtils.hashSHA256(requestIS, true // resetInsteadOfClose - reset don't close
                ));

                requestIS.reset();
            } catch (IOException e) {
                throw new RuntimeException("Failed to automatically set required header"
                        + " \"x-amz-content-sha256\" for request with" + " entity " + entity, e);
            }
        }
        // For unsupported payload entities bail out with a (hopefully)
        // useful error message.
        // We don't want to do too much automatically because it could
        // kill performance, without the reason being clear to users.
        else if (entity != null) {
            throw new RuntimeException("Header \"x-amz-content-sha256\" set to the hex-encoded"
                    + " SHA256 hash of the request payload is required for"
                    + " AWS Version 4 request signing, please set this on: " + httpMethod);
        }
    }

    if (requestPayloadHexSHA256Hash == null) {
        // If no payload, we set the SHA256 hash of an empty string.
        requestPayloadHexSHA256Hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
    }
    return requestPayloadHexSHA256Hash;
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Extract the request timestamp from the given HTTP request, from either
 * the "x-amz-date" metadata header or the Date header, and convert it
 * into an AWS-flavoured ISO8601 string format suitable for us in
 * request authorization for AWS version 4 signatures.
 *
 * @param httpMethod/*from   w w  w  . j  av a2s  .c o m*/
 * request containing at least one of the "x-amz-date" or Date headers with
 * a timestamp value in one of the supported formats: RFC 822, ISO 8601,
 * AWS-flavoured ISO 8601.
 * @return timestamp formatted as AWS-flavoured ISO8601: "YYYYMMDDTHHmmssZ"
 */
public static String awsV4ParseAndFormatDate(HttpUriRequest httpMethod) {
    // Retrieve request's date header, from locations in order of
    // preference: explicit metadata date, request Date header
    Header dateHeader = httpMethod.getFirstHeader("x-amz-date");
    if (dateHeader == null) {
        dateHeader = httpMethod.getFirstHeader("Date");
    }
    if (dateHeader == null) {
        throw new RuntimeException("Request must have a date timestamp applied before it can be"
                + " signed with AWS Version 4, but no date value found in"
                + " \"x-amz-date\" or \"Date\" headers");
    }

    // Parse provided Date object or string into ISO8601 format timestamp
    String dateValue = dateHeader.getValue();
    if (dateValue.endsWith("Z")) {
        // ISO8601-like date, does it need to be converted to AWS flavour?
        try {
            parseAwsFlavouredISO8601Date(dateValue);
            // Parse succeeded, no more work necessary
            return dateValue;
        } catch (ParseException e) {
            // Parse failed, try parsing normal ISO8601 format
            try {
                Date date = ServiceUtils.parseIso8601Date(dateValue);
                return formatAwsFlavouredISO8601Date(date);
            } catch (ParseException e2) {
                throw new RuntimeException("Invalid date value in request: " + dateValue, e2);
            }
        }
    } else {
        try {
            Date date = ServiceUtils.parseRfc822Date(dateValue);
            return formatAwsFlavouredISO8601Date(date);
        } catch (ParseException e) {
            throw new RuntimeException("Invalid date value in request: " + dateValue, e);
        }
    }
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Calculate AWS Version 4 signature for a HTTP request and apply the
 * appropriate "Authorization" header value to authorize it.
 *
 * @param httpMethod/*www. ja v a  2 s.  c o m*/
 * the request's HTTP method just prior to sending
 * @param requestSignatureVersion
 * request signature version string, e.g. "AWS4-HMAC-SHA256"
 * @param providerCredentials
 * account holder's access and secret key credentials
 * @param requestPayloadHexSha256Hash
 * hex-encoded SHA256 hash of request's payload.
 * @param region
 * region to which the request will be sent
 * {@link "http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"}
 */
public static void awsV4SignRequestAuthorizationHeader(String requestSignatureVersion,
        HttpUriRequest httpMethod, ProviderCredentials providerCredentials, String requestPayloadHexSha256Hash,
        String region) {
    // Ensure the required Host header is set prior to signing.
    if (httpMethod.getFirstHeader("Host") == null) {
        httpMethod.setHeader("Host", httpMethod.getURI().getHost());
    }

    // Generate AWS-flavoured ISO8601 timestamp string
    String timestampISO8601 = SignatureUtils.awsV4ParseAndFormatDate(httpMethod);

    // Apply AWS-flavoured ISO8601 timestamp string to "x-aws-date"
    // metadata, otherwise if only the Date header is present and it is
    // RFC 822 formatted S3 expects that date to be part of the string
    // to sign, not the AWS-flavoured ISO8601 timestamp as claimed by the
    // documentation.
    // TODO This shouldn't be necessary, confirm it really is...
    if (httpMethod.getFirstHeader("x-amz-date") == null) {
        httpMethod.setHeader("x-amz-date", timestampISO8601);
    }

    // Canonical request string
    String canonicalRequestString = SignatureUtils.awsV4BuildCanonicalRequestString(httpMethod,
            requestPayloadHexSha256Hash);

    // String to sign
    String stringToSign = SignatureUtils.awsV4BuildStringToSign(requestSignatureVersion, canonicalRequestString,
            timestampISO8601, region);

    // Signing key
    byte[] signingKey = SignatureUtils.awsV4BuildSigningKey(providerCredentials.getSecretKey(),
            timestampISO8601, region);

    // Request signature
    String signature = ServiceUtils
            .toHex(ServiceUtils.hmacSHA256(signingKey, ServiceUtils.stringToBytes(stringToSign)));

    // Authorization header value
    String authorizationHeaderValue = SignatureUtils.awsV4BuildAuthorizationHeaderValue(
            providerCredentials.getAccessKey(), signature, requestSignatureVersion, canonicalRequestString,
            timestampISO8601, region);

    httpMethod.setHeader("Authorization", authorizationHeaderValue);
}

From source file:org.springframework.cloud.sleuth.instrument.zuul.ApacheHttpClientRibbonRequestCustomizerTests.java

private void thenThereIsAHeaderWithNameAndValue(HttpUriRequest request, String name, String value) {
    Header header = request.getFirstHeader(name);
    then(header.getName()).isEqualTo(name);
    then(header.getValue()).isEqualTo(value);
}

From source file:org.springframework.cloud.sleuth.instrument.zuul.ApacheHttpClientRibbonRequestCustomizerTests.java

@Test
public void should_set_not_sampled_on_the_context_when_there_is_no_span() throws Exception {
    RequestBuilder requestBuilder = RequestBuilder.create("GET");

    this.customizer.inject(null, this.customizer.toSpanTextMap(requestBuilder));

    HttpUriRequest request = requestBuilder.build();
    Header header = request.getFirstHeader(Span.SAMPLED_NAME);
    then(header.getName()).isEqualTo(Span.SAMPLED_NAME);
    then(header.getValue()).isEqualTo(Span.SPAN_NOT_SAMPLED);
}

From source file:com.comcast.cim.rest.client.xhtml.TestXhtmlHttpClient.java

@Test
public void testSetsAcceptHeaderForXhtml() throws Exception {
    XhtmlApplicationState state = new XhtmlApplicationState(null, null, null);
    HttpGet get = new HttpGet("http://foo.example.com/");
    URL context = new URL("http://foo.example.com/");
    XhtmlResponseHandler rh = new XhtmlResponseHandler(context);

    Capture<HttpUriRequest> cap = new Capture<HttpUriRequest>();
    EasyMock.expect(mockFactory.get(context)).andReturn(rh);
    EasyMock.expect(mockHttpClient.execute(EasyMock.capture(cap), EasyMock.same(rh))).andReturn(state);

    replayMocks();//from w  ww  . jav a2  s .  c o  m
    impl.execute(get);
    verifyMocks();

    HttpUriRequest captured = cap.getValue();
    Assert.assertEquals("application/xhtml+xml,*/*;q=0.9", captured.getFirstHeader("Accept").getValue());
}

From source file:com.comcast.cim.rest.client.xhtml.TestXhtmlHttpClient.java

@Test
public void testOverwritesAcceptHeaderForXhtml() throws Exception {
    XhtmlApplicationState state = new XhtmlApplicationState(null, null, null);
    HttpGet get = new HttpGet("http://foo.example.com/");
    get.setHeader("Accept", "*/*");
    URL context = new URL("http://foo.example.com/");
    XhtmlResponseHandler rh = new XhtmlResponseHandler(null);

    Capture<HttpUriRequest> cap = new Capture<HttpUriRequest>();
    EasyMock.expect(mockFactory.get(context)).andReturn(rh);
    EasyMock.expect(mockHttpClient.execute(EasyMock.capture(cap), EasyMock.same(rh))).andReturn(state);

    replayMocks();//  ww  w  .  java  2 s  . com
    impl.execute(get);
    verifyMocks();

    HttpUriRequest captured = cap.getValue();
    Assert.assertEquals("application/xhtml+xml,*/*;q=0.9", captured.getFirstHeader("Accept").getValue());
}

From source file:com.betfair.cougar.baseline.security.BaselineClientIdentityTokenResolver.java

@Override
public List<IdentityToken> resolve(HttpUriRequest input, X509Certificate[] certificateChain) {
    List<IdentityToken> credentials = new ArrayList<IdentityToken>();

    for (SimpleIdentityTokenName securityToken : SimpleIdentityTokenName.values()) {

        Header authHeaderValue = input.getFirstHeader(TOKEN_PREFIX + securityToken.name());
        if (authHeaderValue != null) {
            credentials.add(new IdentityToken(securityToken.name(), authHeaderValue.getValue()));
        }/*from w w w  . j a  va  2  s.c  om*/
    }

    return credentials;
}

From source file:org.ecloudmanager.tmrk.cloudapi.CloudapiRequestAuhtorization.java

private String signature(HttpUriRequest request, String apiPrivateKey) {
    StringBuilder sb = new StringBuilder();
    String verb = request.getMethod().toUpperCase();
    String date = request.getFirstHeader(HttpHeaderNames.DATE).getValue();
    Header contentTypeHeader = request.getFirstHeader(HttpHeaderNames.CONTENT_TYPE);
    String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
    Header contentLengthHeader = request.getFirstHeader(HttpHeaderNames.CONTENT_LENGTH);
    String contentLength = contentLengthHeader != null ? contentLengthHeader.getValue() : null;

    sb.append(verb).append("\n");
    sb.append(contentLength != null ? contentLength.trim() : "").append("\n");
    sb.append(contentType != null ? contentType.trim() : "").append("\n");
    sb.append(date).append("\n");
    HeaderIterator hit = request.headerIterator();
    Headers<Object> headers = new Headers<>();
    while (hit.hasNext()) {
        Header hdr = hit.nextHeader();/* w w  w.ja v  a2  s . co m*/
        headers.add(hdr.getName(), hdr.getValue());
    }
    sb.append(canonicalizedHeaders(headers));
    sb.append(canonicalizedResource(new ResteasyUriInfo(request.getURI())));

    String sigstr = sb.toString();
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(getBytes(apiPrivateKey), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return Base64.encodeBytes(sha256_HMAC.doFinal(getBytes(sigstr)));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.fcrepo.integration.AbstractResourceIT.java

protected Dataset getDataset(final HttpClient client, final HttpUriRequest method) throws IOException {

    if (method.getFirstHeader(ACCEPT) == null) {
        method.addHeader(ACCEPT, "application/n-triples");
    } else {//from w  w w  .  j a v a2  s  . c o m
        logger.debug("Retrieving RDF in mimeType: {}", method.getFirstHeader(ACCEPT));
    }

    final HttpResponse response = client.execute(method);
    assertEquals(OK.getStatusCode(), response.getStatusLine().getStatusCode());
    final Dataset result = parseTriples(response.getEntity());
    logger.trace("Retrieved RDF: {}", result);
    return result;

}