Example usage for org.apache.http.client.methods HttpRequestBase getHeaders

List of usage examples for org.apache.http.client.methods HttpRequestBase getHeaders

Introduction

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

Prototype

public Header[] getHeaders(String str) 

Source Link

Usage

From source file:com.github.lpezet.antiope.dao.DefaultHttpRequestFactory.java

/** Configures the headers in the specified Apache HTTP request. */
private void configureHeaders(HttpRequestBase pHttpRequest, Request<?> pRequest, ExecutionContext pContext,
        APIConfiguration pConfiguration) {
    /*/*from  www .j  a  v a  2  s .  c  o  m*/
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the QueryString signer.
     */
    URI endpoint = pRequest.getEndpoint();
    String hostHeader = endpoint.getHost();
    if (HttpUtils.isUsingNonDefaultPort(endpoint)) {
        hostHeader += COLON + endpoint.getPort();
    }
    pHttpRequest.addHeader(HOST, hostHeader);

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : pRequest.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase(CONTENT_LENGTH) || entry.getKey().equalsIgnoreCase(HOST))
            continue;

        pHttpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    /* Set content type and encoding */
    if (pHttpRequest.getHeaders(CONTENT_TYPE) == null || pHttpRequest.getHeaders(CONTENT_TYPE).length == 0) {
        pHttpRequest.addHeader(CONTENT_TYPE,
                "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase());
    }

    // Override the user agent string specified in the client params if the
    // context requires it
    if (pContext != null && pContext.getContextUserAgent() != null) {
        pHttpRequest.addHeader(USER_AGENT,
                createUserAgentString(pConfiguration, pContext.getContextUserAgent()));
    }
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) {
    if (depth >= MAX_REDIRECT) {
        throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached");
    }/*from   www.j a  v a  2  s . c o  m*/

    RequestCallback callback = req.getRequestCallback();

    HttpRequestBase method = req.getMethod();
    String verificationText = req.getVerificationText();
    String url = method.getURI().toString();

    // save the browser and version if it's not yet been set
    if (har != null && har.getLog().getBrowser() == null) {
        Header[] uaHeaders = method.getHeaders("User-Agent");
        if (uaHeaders != null && uaHeaders.length > 0) {
            String userAgent = uaHeaders[0].getValue();
            try {
                // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0'
                ReadableUserAgent uai = PARSER.parse(userAgent);
                String browser = uai.getName();
                String version = uai.getVersionNumber().toVersionString();
                har.getLog().setBrowser(new HarNameVersion(browser, version));
            } catch (Exception e) {
                LOG.warn("Failed to parse user agent string", e);
            }
        }
    }

    // process any rewrite requests
    boolean rewrote = false;
    String newUrl = url;
    for (RewriteRule rule : rewriteRules) {
        Matcher matcher = rule.match.matcher(newUrl);
        newUrl = matcher.replaceAll(rule.replace);
        rewrote = true;
    }

    if (rewrote) {
        try {
            method.setURI(new URI(newUrl));
            url = newUrl;
        } catch (URISyntaxException e) {
            LOG.warn("Could not rewrite url to %s", newUrl);
        }
    }

    // handle whitelist and blacklist entries
    int mockResponseCode = -1;
    synchronized (this) {
        // guard against concurrent modification of whitelistEntry
        if (whitelistEntry != null) {
            boolean found = false;
            for (Pattern pattern : whitelistEntry.patterns) {
                if (pattern.matcher(url).matches()) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                mockResponseCode = whitelistEntry.responseCode;
            }
        }
    }

    if (blacklistEntries != null) {
        for (BlacklistEntry blacklistEntry : blacklistEntries) {
            if (blacklistEntry.pattern.matcher(url).matches()) {
                mockResponseCode = blacklistEntry.responseCode;
                break;
            }
        }
    }

    if (!additionalHeaders.isEmpty()) {
        // Set the additional headers
        for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            method.removeHeaders(key);
            method.addHeader(key, value);
        }
    }

    String charSet = "UTF-8";
    String responseBody = null;

    InputStream is = null;
    int statusCode = -998;
    long bytes = 0;
    boolean gzipping = false;
    boolean contentMatched = true;
    OutputStream os = req.getOutputStream();
    if (os == null) {
        os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB
    }
    if (verificationText != null) {
        contentMatched = false;
    }

    // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down)
    // we still have the attempt associated, even if we never got a response
    HarEntry entry = new HarEntry(harPageRef);

    // clear out any connection-related information so that it's not stale from previous use of this thread.
    RequestInfo.clear(url, entry);

    entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol()));
    entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol()));
    if (this.har != null && harPageRef != null) {
        har.getLog().addEntry(entry);
    }

    String query = method.getURI().getRawQuery();
    if (query != null) {
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(query, params, "UTF-8");
        for (String k : params.keySet()) {
            for (Object v : params.getValues(k)) {
                entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v));
            }
        }
    }

    String errorMessage = null;
    HttpResponse response = null;

    BasicHttpContext ctx = new BasicHttpContext();

    ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime());
    synchronized (activeRequests) {
        activeRequests.add(activeRequest);
    }

    // for dealing with automatic authentication
    if (authType == AuthType.NTLM) {
        // todo: not supported yet
        //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine()));
    } else if (authType == AuthType.BASIC) {
        ctx.setAttribute("preemptive-auth", new BasicScheme());
    }

    StatusLine statusLine = null;
    try {
        // set the User-Agent if it's not already set
        if (method.getHeaders("User-Agent").length == 0) {
            method.addHeader("User-Agent", "BrowserMob VU/1.0");
        }

        // was the request mocked out?
        if (mockResponseCode != -1) {
            statusCode = mockResponseCode;

            // TODO: HACKY!!
            callback.handleHeaders(new Header[] { new Header() {
                @Override
                public String getName() {
                    return "Content-Type";
                }

                @Override
                public String getValue() {
                    return "text/plain";
                }

                @Override
                public HeaderElement[] getElements() throws ParseException {
                    return new HeaderElement[0];
                }
            } });
            // Make sure we set the status line here too.
            // Use the version number from the request
            ProtocolVersion version = null;
            int reqDotVersion = req.getProxyRequest().getDotVersion();
            if (reqDotVersion == -1) {
                version = new HttpVersion(0, 9);
            } else if (reqDotVersion == 0) {
                version = new HttpVersion(1, 0);
            } else if (reqDotVersion == 1) {
                version = new HttpVersion(1, 1);
            }
            // and if not any of these, trust that a Null version will
            // cause an appropriate error
            callback.handleStatusLine(
                    new BasicStatusLine(version, statusCode, "Status set by browsermob-proxy"));
            // No mechanism to look up the response text by status code,
            // so include a notification that this is a synthetic error code.
        } else {
            response = httpClient.execute(method, ctx);
            statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            if (callback != null) {
                callback.handleStatusLine(statusLine);
                callback.handleHeaders(response.getAllHeaders());
            }

            if (response.getEntity() != null) {
                is = response.getEntity().getContent();
            }

            // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204)
            if (is != null) {
                Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");
                if (contentEncodingHeader != null
                        && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
                    gzipping = true;
                }

                // deal with GZIP content!
                if (decompress && gzipping) {
                    is = new GZIPInputStream(is);
                }

                if (captureContent) {
                    // todo - something here?
                    os = new ClonedOutputStream(os);
                }

                bytes = copyWithStats(is, os);
            }
        }
    } catch (Exception e) {
        errorMessage = e.toString();

        if (callback != null) {
            callback.reportError(e);
        }

        // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored)
        if (!shutdown) {
            LOG.info(String.format("%s when requesting %s", errorMessage, url));
        }
    } finally {
        // the request is done, get it out of here
        synchronized (activeRequests) {
            activeRequests.remove(activeRequest);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // this is OK to ignore
            }
        }
    }

    // record the response as ended
    RequestInfo.get().finish();

    // set the start time and other timings
    entry.setStartedDateTime(RequestInfo.get().getStart());
    entry.setTimings(RequestInfo.get().getTimings());
    entry.setServerIPAddress(RequestInfo.get().getResolvedAddress());
    entry.setTime(RequestInfo.get().getTotalTime());

    // todo: where you store this in HAR?
    // obj.setErrorMessage(errorMessage);
    entry.getResponse().setBodySize(bytes);
    entry.getResponse().getContent().setSize(bytes);
    entry.getResponse().setStatus(statusCode);
    if (statusLine != null) {
        entry.getResponse().setStatusText(statusLine.getReasonPhrase());
    }

    boolean urlEncoded = false;
    if (captureHeaders || captureContent) {
        for (Header header : method.getAllHeaders()) {
            if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) {
                urlEncoded = true;
            }

            entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
        }

        if (response != null) {
            for (Header header : response.getAllHeaders()) {
                entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
            }
        }
    }

    if (captureContent) {
        // can we understand the POST data at all?
        if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) {
            HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method;
            HttpEntity entity = enclosingReq.getEntity();

            HarPostData data = new HarPostData();
            data.setMimeType(req.getMethod().getFirstHeader("Content-Type").getValue());
            entry.getRequest().setPostData(data);

            if (urlEncoded || URLEncodedUtils.isEncoded(entity)) {
                try {
                    final String content = new String(req.getCopy().toByteArray(), "UTF-8");
                    if (content != null && content.length() > 0) {
                        List<NameValuePair> result = new ArrayList<NameValuePair>();
                        URLEncodedUtils.parse(result, new Scanner(content), null);

                        ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>();
                        data.setParams(params);

                        for (NameValuePair pair : result) {
                            params.add(new HarPostDataParam(pair.getName(), pair.getValue()));
                        }
                    }
                } catch (Exception e) {
                    LOG.info("Unexpected problem when parsing input copy", e);
                }
            } else {
                // not URL encoded, so let's grab the body of the POST and capture that
                data.setText(new String(req.getCopy().toByteArray()));
            }
        }
    }

    //capture request cookies
    javax.servlet.http.Cookie[] cookies = req.getProxyRequest().getCookies();
    for (javax.servlet.http.Cookie cookie : cookies) {
        HarCookie hc = new HarCookie();
        hc.setName(cookie.getName());
        hc.setValue(cookie.getValue());
        entry.getRequest().getCookies().add(hc);
    }

    String contentType = null;

    if (response != null) {
        try {
            Header contentTypeHdr = response.getFirstHeader("Content-Type");
            if (contentTypeHdr != null) {
                contentType = contentTypeHdr.getValue();
                entry.getResponse().getContent().setMimeType(contentType);

                if (captureContent && os != null && os instanceof ClonedOutputStream) {
                    ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput();

                    if (gzipping) {
                        // ok, we need to decompress it before we can put it in the har file
                        try {
                            InputStream temp = new GZIPInputStream(
                                    new ByteArrayInputStream(copy.toByteArray()));
                            copy = new ByteArrayOutputStream();
                            IOUtils.copy(temp, copy);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if (hasTextualContent(contentType)) {
                        setTextOfEntry(entry, copy, contentType);
                    } else if (captureBinaryContent) {
                        setBinaryContentOfEntry(entry, copy);
                    }
                }

                NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset");

                if (nvp != null) {
                    charSet = nvp.getValue();
                }
            }

            if (os instanceof ByteArrayOutputStream) {
                responseBody = ((ByteArrayOutputStream) os).toString(charSet);

                if (verificationText != null) {
                    contentMatched = responseBody.contains(verificationText);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    if (contentType != null) {
        entry.getResponse().getContent().setMimeType(contentType);
    }

    // checking to see if the client is being redirected
    boolean isRedirect = false;

    String location = null;
    if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) {
        isRedirect = true;

        // pulling the header for the redirect
        Header locationHeader = response.getLastHeader("location");
        if (locationHeader != null) {
            location = locationHeader.getValue();
        } else if (this.followRedirects) {
            throw new RuntimeException("Invalid redirect - missing location header");
        }
    }

    //
    // Response validation - they only work if we're not following redirects
    //

    int expectedStatusCode = req.getExpectedStatusCode();

    // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem
    if (mockResponseCode == -1 && expectedStatusCode > -1) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }
        if (expectedStatusCode != statusCode) {
            if (isRedirect) {
                throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw "
                        + statusCode + " redirecting to: " + location);
            } else {
                throw new RuntimeException(
                        "Expected status code of " + expectedStatusCode + " but saw " + statusCode);
            }
        }
    }

    // Location header check:
    if (isRedirect && (req.getExpectedLocation() != null)) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }

        if (location.compareTo(req.getExpectedLocation()) != 0) {
            throw new RuntimeException(
                    "Expected a redirect to  " + req.getExpectedLocation() + " but saw " + location);
        }
    }

    // end of validation logic

    // basic tail recursion for redirect handling
    if (isRedirect && this.followRedirects) {
        // updating location:
        try {
            URI redirectUri = new URI(location);
            URI newUri = method.getURI().resolve(redirectUri);
            method.setURI(newUri);

            return execute(req, ++depth);
        } catch (URISyntaxException e) {
            LOG.warn("Could not parse URL", e);
        }
    }

    return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage,
            responseBody, contentType, charSet);
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }// w w  w  . j  av  a  2s  .c  o  m
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:org.georchestra.security.HeadersManagementStrategy.java

/**
 * Copies the request headers from the original request to the proxy request.  It may modify the
 * headers slightly/*  ww w  . ja v a  2  s. co m*/
 */
@SuppressWarnings("unchecked")
public synchronized void configureRequestHeaders(HttpServletRequest originalRequest,
        HttpRequestBase proxyRequest) {
    Enumeration<String> headerNames = originalRequest.getHeaderNames();
    String headerName = null;

    StringBuilder headersLog = new StringBuilder("Request Headers:\n");
    headersLog.append("==========================================================\n");
    if (referer != null) {
        addHeaderToRequestAndLog(proxyRequest, headersLog, REFERER_HEADER_NAME, this.referer);
    }
    while (headerNames.hasMoreElements()) {
        headerName = headerNames.nextElement();
        if (headerName.compareToIgnoreCase(CONTENT_LENGTH) == 0) {
            continue;
        }
        if (headerName.equalsIgnoreCase(COOKIE_ID)) {
            continue;
        }
        if (filter(originalRequest, headerName, proxyRequest)) {
            continue;
        }
        if (noAcceptEncoding && headerName.equalsIgnoreCase(ACCEPT_ENCODING)) {
            continue;
        }
        if (headerName.equalsIgnoreCase(HOST)) {
            continue;
        }
        // Don't forward 'sec-*' headers, those headers must be managed by security-proxy
        if (headerName.toLowerCase().startsWith(PROTECTED_HEADER_PREFIX)) {
            continue;
        }
        if (referer != null && headerName.equalsIgnoreCase(REFERER_HEADER_NAME)) {
            continue;
        }
        String value = originalRequest.getHeader(headerName);
        addHeaderToRequestAndLog(proxyRequest, headersLog, headerName, value);
    }
    // see https://github.com/georchestra/georchestra/issues/509:
    addHeaderToRequestAndLog(proxyRequest, headersLog, SEC_PROXY, "true");

    handleRequestCookies(originalRequest, proxyRequest, headersLog);
    HttpSession session = originalRequest.getSession();

    for (HeaderProvider provider : headerProviders) {
        for (Header header : provider.getCustomRequestHeaders(session, originalRequest)) {
            if ((header.getName().equalsIgnoreCase(SEC_USERNAME)
                    || header.getName().equalsIgnoreCase(SEC_ROLES))
                    && proxyRequest.getHeaders(header.getName()) != null
                    && proxyRequest.getHeaders(header.getName()).length > 0) {
                Header[] originalHeaders = proxyRequest.getHeaders(header.getName());
                for (Header originalHeader : originalHeaders) {
                    headersLog.append("\t" + originalHeader.getName());
                    headersLog.append("=");
                    headersLog.append(originalHeader.getValue());
                    headersLog.append("\n");
                }
            } else {
                proxyRequest.addHeader(header);
                headersLog.append("\t" + header.getName());
                headersLog.append("=");
                headersLog.append(header.getValue());
                headersLog.append("\n");
            }
        }
    }

    headersLog.append("==========================================================");

    logger.trace(headersLog.toString());
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();/* ww w  . jav  a  2s  .  c o  m*/

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:ru.histone.resourceloaders.DefaultResourceLoader.java

private StreamResource loadHttpResource(URI location, Node[] args) {
    URI newLocation = URI.create(location.toString().replace("#fragment", ""));
    final Map<Object, Node> requestMap = args != null && args.length != 0
            && args[0] instanceof ObjectHistoneNode ? ((ObjectHistoneNode) args[0]).getElements()
                    : new HashMap<Object, Node>();
    Node methodNode = requestMap.get("method");
    final String method = methodNode != null && methodNode.isString()
            && methodNode.getAsString().getValue().length() != 0
                    ? requestMap.get("method").getAsString().getValue()
                    : "GET";
    final Map<String, String> headers = new HashMap<String, String>();
    if (requestMap.containsKey("headers")) {
        for (Map.Entry<Object, Node> en : requestMap.get("headers").getAsObject().getElements().entrySet()) {
            String value = null;//from w  w w. ja v a  2 s .co  m
            if (en.getValue().isUndefined())
                value = "undefined";
            else
                value = en.getValue().getAsString().getValue();
            headers.put(en.getKey().toString(), value);
        }
    }

    final Map<String, String> filteredHeaders = filterRequestHeaders(headers);
    final Node data = requestMap.containsKey("data") ? (Node) requestMap.get("data") : null;

    // Prepare request
    HttpRequestBase request = new HttpGet(newLocation);
    if ("POST".equalsIgnoreCase(method)) {
        request = new HttpPost(newLocation);
    } else if ("PUT".equalsIgnoreCase(method)) {
        request = new HttpPut(newLocation);
    } else if ("DELETE".equalsIgnoreCase(method)) {
        request = new HttpDelete(newLocation);
    } else if ("TRACE".equalsIgnoreCase(method)) {
        request = new HttpTrace(newLocation);
    } else if ("OPTIONS".equalsIgnoreCase(method)) {
        request = new HttpOptions(newLocation);
    } else if ("PATCH".equalsIgnoreCase(method)) {
        request = new HttpPatch(newLocation);
    } else if ("HEAD".equalsIgnoreCase(method)) {
        request = new HttpHead(newLocation);
    } else if (method != null && !"GET".equalsIgnoreCase(method)) {
        return new StreamResource(null, location.toString(), ContentType.TEXT);
    }

    for (Map.Entry<String, String> en : filteredHeaders.entrySet()) {
        request.setHeader(en.getKey(), en.getValue());
    }
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && data != null) {
        String stringData = null;
        String contentType = filteredHeaders.get("content-type") == null ? ""
                : filteredHeaders.get("content-type");
        if (data.isObject()) {
            stringData = ToQueryString.toQueryString(data.getAsObject(), null, "&");
            contentType = "application/x-www-form-urlencoded";
        } else {
            stringData = data.getAsString().getValue();
        }
        if (stringData != null) {
            StringEntity se;
            try {
                se = new StringEntity(stringData);
            } catch (UnsupportedEncodingException e) {
                throw new ResourceLoadException(String.format("Can't encode data '%s'", stringData));
            }
            ((HttpEntityEnclosingRequestBase) request).setEntity(se);
        }
        request.setHeader("Content-Type", contentType);
    }
    if (request.getHeaders("content-Type").length == 0) {
        request.setHeader("Content-Type", "");
    }

    // Execute request
    HttpClient client = new DefaultHttpClient(httpClientConnectionManager);
    ((AbstractHttpClient) client).setRedirectStrategy(new RedirectStrategy());
    InputStream input = null;
    try {
        HttpResponse response = client.execute(request);
        input = response.getEntity() == null ? null : response.getEntity().getContent();
    } catch (IOException e) {
        throw new ResourceLoadException(String.format("Can't load resource '%s'", location.toString()));
    } finally {
    }
    return new StreamResource(input, location.toString(), ContentType.TEXT);
}