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

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

Introduction

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

Prototype

public void addHeader(String str, String str2) 

Source Link

Usage

From source file:org.apache.solr.client.solrj.impl.HttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, final ResponseParser processor)
        throws SolrServerException, IOException {
    HttpRequestBase method = null;
    InputStream is = null;/*from   www .  j  av  a2  s  .  com*/
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }

    int tries = maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = baseUrl + path;
                    boolean hasNullStreamName = false;
                    if (streams != null) {
                        for (ContentStream cs : streams) {
                            if (cs.getName() == null) {
                                hasNullStreamName = true;
                                break;
                            }
                        }
                    }
                    boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1))
                            && !hasNullStreamName;

                    // only send this list of params as query string params
                    ModifiableSolrParams queryParams = new ModifiableSolrParams();
                    for (String param : this.queryParams) {
                        String[] value = wparams.getParams(param);
                        if (value != null) {
                            for (String v : value) {
                                queryParams.add(param, v);
                            }
                            wparams.remove(param);
                        }
                    }

                    LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
                    if (streams == null || isMultipart) {
                        HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false));
                        post.setHeader("Content-Charset", "UTF-8");
                        if (!isMultipart) {
                            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
                        Iterator<String> iter = wparams.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = wparams.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (isMultipart) {
                                        parts.add(new FormBodyPart(p,
                                                new StringBody(v, Charset.forName("UTF-8"))));
                                    } else {
                                        postParams.add(new BasicNameValuePair(p, v));
                                    }
                                }
                            }
                        }

                        if (isMultipart && streams != null) {
                            for (ContentStream content : streams) {
                                String contentType = content.getContentType();
                                if (contentType == null) {
                                    contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
                                }
                                String name = content.getName();
                                if (name == null) {
                                    name = "";
                                }
                                parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(),
                                        contentType, content.getName())));
                            }
                        }

                        if (parts.size() > 0) {
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                            for (FormBodyPart p : parts) {
                                entity.addPart(p);
                            }
                            post.setEntity(entity);
                        } else {
                            //not using multipart
                            post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(wparams, false);
                        HttpPost post = new HttpPost(url + pstr);

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }

                            });
                        } else {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }
                            });
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if (tries < 1) {
                    throw r;
                }
            }
        }
    } catch (IOException ex) {
        throw new SolrServerException("error reading streams", ex);
    }

    // XXX client already has this set, is this needed?
    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    method.addHeader("User-Agent", AGENT);

    InputStream respBody = null;
    boolean shouldClose = true;
    boolean success = false;
    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        respBody = response.getEntity().getContent();
        Header ctHeader = response.getLastHeader("content-type");
        String contentType;
        if (ctHeader != null) {
            contentType = ctHeader.getValue();
        } else {
            contentType = "";
        }

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            if (processor == null) {
                throw new RemoteSolrException(httpStatus,
                        "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:"
                                + response.getStatusLine().getReasonPhrase(),
                        null);
            }
        }
        if (processor == null) {

            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<Object>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            success = true;
            return rsp;
        }

        String procCt = processor.getContentType();
        if (procCt != null) {
            String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
            String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
            if (!procMimeType.equals(mimeType)) {
                // unexpected mime type
                String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
                Header encodingHeader = response.getEntity().getContentEncoding();
                String encoding;
                if (encodingHeader != null) {
                    encoding = encodingHeader.getValue();
                } else {
                    encoding = "UTF-8"; // try UTF-8
                }
                try {
                    msg = msg + " " + IOUtils.toString(respBody, encoding);
                } catch (IOException e) {
                    throw new RemoteSolrException(httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null);
                throw e;
            }
        }

        //      if(true) {
        //        ByteArrayOutputStream copy = new ByteArrayOutputStream();
        //        IOUtils.copy(respBody, copy);
        //        String val = new String(copy.toByteArray());
        //        System.out.println(">RESPONSE>"+val+"<"+val.length());
        //        respBody = new ByteArrayInputStream(copy.toByteArray());
        //      }

        NamedList<Object> rsp = null;
        String charset = EntityUtils.getContentCharSet(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, charset);
        } catch (Exception e) {
            throw new RemoteSolrException(httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            String reason = null;
            try {
                NamedList err = (NamedList) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    // TODO? get the trace?
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase());
                msg.append("\n\n");
                msg.append("request: " + method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            throw new RemoteSolrException(httpStatus, reason, null);
        }
        success = true;
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (respBody != null && shouldClose) {
            try {
                respBody.close();
            } catch (Throwable t) {
            } // ignore
            if (!success) {
                method.abort();
            }
        }
    }
}

From source file:org.apache.streams.components.http.provider.SimpleHttpProvider.java

public HttpRequestBase prepareHttpRequest(URI uri) {
    HttpRequestBase request;
    if (configuration.getRequestMethod().equals(HttpProviderConfiguration.RequestMethod.GET)) {
        request = new HttpGet(uri);
    } else if (configuration.getRequestMethod().equals(HttpProviderConfiguration.RequestMethod.POST)) {
        request = new HttpPost(uri);
    } else {/*w w  w  .j  a v  a2s  .c o  m*/
        // this shouldn't happen because of the default
        request = new HttpGet(uri);
    }

    request.addHeader("content-type", this.configuration.getContentType());

    return request;

}

From source file:org.artifactory.repo.HttpRepo.java

/**
 * Adds default headers and extra headers to the HttpRequest method
 * The extra headers are unique headers that should be added to the remote server request according to special
 * requirement example : user adds extra headers through the User Plugin (BeforeRemoteDownloadAction)
 * @param method Method to execute/* w w  w.  j  a v a  2 s  .co  m*/
 * @param extraHeaders Extra headers to add to the remote server request
 */
@SuppressWarnings({ "deprecation" })
private void addDefaultHeadersAndQueryParams(HttpRequestBase method, Map<String, String> extraHeaders) {
    //Explicitly force keep alive
    method.setHeader(HttpHeaders.CONNECTION, "Keep-Alive");

    //Add the current requester host id
    Set<String> originatedHeaders = RepoRequests.getOriginatedHeaders();
    for (String originatedHeader : originatedHeaders) {
        method.addHeader(ARTIFACTORY_ORIGINATED, originatedHeader);
    }
    String hostId = ContextHelper.get().beanForType(AddonsManager.class).addonByType(HaCommonAddon.class)
            .getHostId();
    // Add the extra headers to the remote request
    if (extraHeaders != null) {
        for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
            boolean isReservedKey = ARTIFACTORY_ORIGINATED.equals(entry.getKey())
                    || ORIGIN_ARTIFACTORY.equals(entry.getKey()) || ACCEPT_ENCODING.equals(entry.getKey());
            if (!isReservedKey) {
                method.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    // Add the default artifactory headers, those headers will always override the existing headers if they already exist
    method.addHeader(ARTIFACTORY_ORIGINATED, hostId);

    //For backwards compatibility
    method.setHeader(ORIGIN_ARTIFACTORY, hostId);

    //Set gzip encoding
    if (handleGzipResponse) {
        method.addHeader(ACCEPT_ENCODING, "gzip");
    }

    // Set custom query params
    String queryParams = getDescriptor().getQueryParams();
    if (StringUtils.isNotBlank(queryParams)) {
        String url = method.getURI().toString();
        if (url.contains("?")) {
            url += "&";
        } else {
            url += "?";
        }
        url += HttpUtils.encodeQuery(queryParams);
        method.setURI(URI.create(url));
    }
}

From source file:org.artifactory.rest.common.service.ResearchService.java

/**
 * add originated header to request/*from   ww  w.j  a  v a2 s  .c o  m*/
 *
 * @param request - http servlet request
 */
private static void addOriginatedHeader(HttpRequestBase request) {
    String hostId = ContextHelper.get().beanForType(AddonsManager.class).addonByType(HaCommonAddon.class)
            .getHostId();
    request.addHeader(ARTIFACTORY_ORIGINATED, hostId);
}

From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java

protected static void setRequestCookie(HttpRequestBase httpRequest, Header[] headers) {
    StringBuilder sb = new StringBuilder(128);
    if (ArrayUtils.isNotEmpty(headers)) {
        for (Header header : headers) {
            if (StringUtils.equals(header.getName(), "Set-Cookie")) {
                String value = header.getValue();
                if (StringUtils.isNotBlank(value)) {
                    // Because of the need to remove the effective range: path=/
                    String[] values = StringUtils.split(value, ";");
                    for (String string : values) {
                        String[] v = string.split("=");
                        if (v.length >= 2)
                            sb.append(v[0]).append("=").append(v[1]).append(";");
                    }//from  ww w.j av a 2 s  .c  o  m
                }
            }
        }
    }
    httpRequest.addHeader("Cookie", sb.toString());
}

From source file:org.dasein.cloud.aws.storage.S3Method.java

S3Response invoke(@Nullable String bucket, @Nullable String object, @Nullable String temporaryEndpoint)
        throws S3Exception, CloudException, InternalException {
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug("----------------------------------------------------------------------------------");
    }/*  ww  w. j a  v  a  2  s . c  om*/
    HttpClient client = null;
    boolean leaveOpen = false;
    try {
        StringBuilder url = new StringBuilder();
        HttpRequestBase method;
        int status;

        // Sanitise the parameters as they may have spaces and who knows what else
        if (bucket != null) {
            bucket = AWSCloud.encode(bucket, false);
        }
        if (object != null && !"?location".equalsIgnoreCase(object) && !"?acl".equalsIgnoreCase(object)
                && !"?tagging".equalsIgnoreCase(object)) {
            object = AWSCloud.encode(object, false);
        }
        if (temporaryEndpoint != null) {
            temporaryEndpoint = AWSCloud.encode(temporaryEndpoint, false);
        }
        if (provider.getEC2Provider().isAWS()) {
            url.append("https://");
            String regionId = provider.getContext().getRegionId();

            if (temporaryEndpoint == null) {
                boolean validDomainName = isValidDomainName(bucket);

                if (bucket != null && validDomainName) {
                    url.append(bucket);
                    if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) {
                        url.append(".s3-");
                        url.append(regionId);
                        url.append(".amazonaws.com/");
                    } else {
                        url.append(".s3.amazonaws.com/");
                    }
                } else {
                    if (regionId != null && !regionId.isEmpty() && !"us-east-1".equals(regionId)) {
                        url.append("s3-");
                        url.append(regionId);
                        url.append(".amazonaws.com/");
                    } else {
                        url.append("s3.amazonaws.com/");
                    }
                }
                if (bucket != null && !validDomainName) {
                    url.append(bucket);
                    url.append("/");
                }
            } else {
                url.append(temporaryEndpoint);
                url.append("/");
            }
        } else if (provider.getEC2Provider().isStorage()
                && "google".equalsIgnoreCase(provider.getProviderName())) {
            url.append("https://");
            if (temporaryEndpoint == null) {
                if (bucket != null) {
                    url.append(bucket);
                    url.append(".");
                }
                url.append("commondatastorage.googleapis.com/");
            } else {
                url.append(temporaryEndpoint);
                url.append("/");
            }
        } else {
            int idx = 0;

            if (!provider.getContext().getEndpoint().startsWith("http")) {
                url.append("https://");
            } else {
                idx = provider.getContext().getEndpoint().indexOf("https://");
                if (idx == -1) {
                    idx = "http://".length();
                    url.append("http://");
                } else {
                    idx = "https://".length();
                    url.append("https://");
                }
            }
            String service = "";
            if (provider.getEC2Provider().isEucalyptus()) {
                service = "Walrus/";
            }

            if (temporaryEndpoint == null) {
                url.append(provider.getContext().getEndpoint().substring(idx));
                if (!provider.getContext().getEndpoint().endsWith("/")) {
                    url.append("/").append(service);
                } else {
                    url.append(service);
                }
            } else {
                url.append(temporaryEndpoint);
                url.append("/");
                url.append(service);
            }
            if (bucket != null) {
                url.append(bucket);
                url.append("/");
            }
        }
        if (object != null) {
            url.append(object);
        } else if (parameters != null) {
            boolean first = true;

            if (object != null && object.indexOf('?') != -1) {
                first = false;
            }
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();

                if (first) {
                    url.append("?");
                    first = false;
                } else {
                    url.append("&");
                }
                if (val != null) {
                    url.append(AWSCloud.encode(key, false));
                    url.append("=");
                    url.append(AWSCloud.encode(val, false));
                } else {
                    url.append(AWSCloud.encode(key, false));
                }
            }
        }

        if (provider.getEC2Provider().isStorage() && provider.getProviderName().equalsIgnoreCase("Google")) {
            headers.put(AWSCloud.P_GOOG_DATE, getDate());
        } else {
            headers.put(AWSCloud.P_AWS_DATE, provider.getV4HeaderDate(null));
        }
        if (contentType == null && body != null) {
            contentType = "application/xml";
            headers.put("Content-Type", contentType);
        } else if (contentType != null) {
            headers.put("Content-Type", contentType);
        }

        method = action.getMethod(url.toString());
        String host = method.getURI().getHost();
        headers.put("host", host);

        if (action.equals(S3Action.PUT_BUCKET_TAG))
            try {
                headers.put("Content-MD5", toBase64(computeMD5Hash(body)));
            } catch (NoSuchAlgorithmException e) {
                logger.error(e);
            } catch (IOException e) {
                logger.error(e);
            }

        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                method.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (body != null) {
            ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(body, APPLICATION_XML));
        } else if (uploadFile != null) {
            ((HttpEntityEnclosingRequestBase) method).setEntity(new FileEntity(uploadFile, contentType));
        }
        try {
            String hash = null;
            if (method instanceof HttpEntityEnclosingRequestBase) {
                try {
                    hash = provider.getRequestBodyHash(
                            EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity()));
                } catch (IOException e) {
                    throw new InternalException(e);
                }
            } else {
                hash = provider.getRequestBodyHash("");
            }

            String signature;
            if (provider.getEC2Provider().isAWS()) {
                // Sign v4 for AWS
                signature = provider.getV4Authorization(new String(provider.getAccessKey()[0]),
                        new String(provider.getAccessKey()[1]), method.getMethod(), url.toString(), SERVICE_ID,
                        headers, hash);
                if (hash != null) {
                    method.addHeader(AWSCloud.P_AWS_CONTENT_SHA256, hash);
                }
            } else {
                // Eucalyptus et al use v2
                signature = provider.signS3(new String(provider.getAccessKey()[0], "utf-8"),
                        provider.getAccessKey()[1], method.getMethod(), null, contentType, headers, bucket,
                        object);
            }
            method.addHeader(AWSCloud.P_CFAUTH, signature);
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }

        if (wire.isDebugEnabled()) {
            wire.debug("[" + url.toString() + "]");
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                try {
                    wire.debug(EntityUtils.toString(((HttpEntityEnclosingRequestBase) method).getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            } else if (uploadFile != null) {
                wire.debug("-- file upload --");
                wire.debug("");
            }
        }

        attempts++;
        client = provider.getClient(body == null && uploadFile == null);

        S3Response response = new S3Response();
        HttpResponse httpResponse;

        try {
            APITrace.trace(provider, action.toString());
            httpResponse = client.execute(method);
            if (wire.isDebugEnabled()) {
                wire.debug(httpResponse.getStatusLine().toString());
                for (Header header : httpResponse.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
            status = httpResponse.getStatusLine().getStatusCode();
        } catch (IOException e) {
            logger.error(url + ": " + e.getMessage());
            throw new InternalException(e);
        }
        response.headers = httpResponse.getAllHeaders();

        HttpEntity entity = httpResponse.getEntity();
        InputStream input = null;

        if (entity != null) {
            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
        }
        try {
            if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED
                    || status == HttpStatus.SC_ACCEPTED) {
                Header clen = httpResponse.getFirstHeader("Content-Length");
                long len = -1L;

                if (clen != null) {
                    len = Long.parseLong(clen.getValue());
                }
                if (len != 0L) {
                    try {
                        Header ct = httpResponse.getFirstHeader("Content-Type");

                        if ((ct != null && (ct.getValue().startsWith("application/xml")
                                || ct.getValue().startsWith("text/xml")))
                                || (action.equals(S3Action.GET_BUCKET_TAG) && input != null)) {
                            try {
                                response.document = parseResponse(input);
                                return response;
                            } finally {
                                input.close();
                            }
                        } else if (ct != null && ct.getValue().startsWith("application/octet-stream")
                                && len < 1) {
                            return null;
                        } else {
                            response.contentLength = len;
                            if (ct != null) {
                                response.contentType = ct.getValue();
                            }
                            response.input = input;
                            response.method = method;
                            leaveOpen = true;
                            return response;
                        }
                    } catch (IOException e) {
                        logger.error(e);
                        throw new CloudException(e);
                    }
                } else {
                    return response;
                }
            } else if (status == HttpStatus.SC_NO_CONTENT) {
                return response;
            }
            if (status == HttpStatus.SC_FORBIDDEN) {
                throw new S3Exception(status, "", "AccessForbidden",
                        "Access was denied : " + (url != null ? url.toString() : ""));
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new S3Exception(status, null, null, "Object not found.");
            } else {
                if (status == HttpStatus.SC_SERVICE_UNAVAILABLE
                        || status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    if (attempts >= 5) {
                        String msg;

                        if (status == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                            msg = "Cloud service is currently unavailable.";
                        } else {
                            msg = "The cloud service encountered a server error while processing your request.";
                        }
                        logger.error(msg);
                        throw new CloudException(msg);
                    } else {
                        leaveOpen = true;
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException ignore) {
                            }
                        }
                        try {
                            Thread.sleep(5000L);
                        } catch (InterruptedException ignore) {
                        }
                        return invoke(bucket, object);
                    }
                }
                try {
                    Document doc;

                    try {
                        logger.warn("Received error code: " + status);
                        doc = parseResponse(input);
                    } finally {
                        if (input != null) {
                            input.close();
                        }
                    }
                    if (doc != null) {
                        String endpoint = null, code = null, message = null, requestId = null;
                        NodeList blocks = doc.getElementsByTagName("Error");

                        if (blocks.getLength() > 0) {
                            Node error = blocks.item(0);
                            NodeList attrs;

                            attrs = error.getChildNodes();
                            for (int i = 0; i < attrs.getLength(); i++) {
                                Node attr = attrs.item(i);

                                if (attr.getNodeName().equals("Code") && attr.hasChildNodes()) {
                                    code = attr.getFirstChild().getNodeValue().trim();
                                } else if (attr.getNodeName().equals("Message") && attr.hasChildNodes()) {
                                    message = attr.getFirstChild().getNodeValue().trim();
                                } else if (attr.getNodeName().equals("RequestId") && attr.hasChildNodes()) {
                                    requestId = attr.getFirstChild().getNodeValue().trim();
                                } else if (attr.getNodeName().equals("Endpoint") && attr.hasChildNodes()) {
                                    endpoint = attr.getFirstChild().getNodeValue().trim();
                                }
                            }

                        }
                        if (endpoint != null && code.equals("TemporaryRedirect")) {
                            if (temporaryEndpoint != null) {
                                throw new CloudException("Too deep redirect to " + endpoint);
                            } else {
                                return invoke(bucket, object, endpoint);
                            }
                        } else {
                            if (message == null) {
                                throw new CloudException("Unable to identify error condition: " + status + "/"
                                        + requestId + "/" + code);
                            }
                            throw new S3Exception(status, requestId, code, message);
                        }
                    } else {
                        throw new CloudException("Unable to parse error.");
                    }
                } catch (IOException e) {
                    if (status == HttpStatus.SC_FORBIDDEN) {
                        throw new S3Exception(status, "", "AccessForbidden",
                                "Access was denied without explanation.");
                    }
                    throw new CloudException(e);
                } catch (RuntimeException e) {
                    throw new CloudException(e);
                } catch (Error e) {
                    throw new CloudException(e);
                }
            }
        } finally {
            if (!leaveOpen) {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
    } finally {
        if (!leaveOpen && client != null) {
            client.getConnectionManager().shutdown();
        }
        if (wire.isDebugEnabled()) {
            wire.debug("----------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:org.olat.restapi.RestConnection.java

private void decorateHttpMessage(HttpRequestBase msg, String accept, String langage, boolean cookie) {
    if (cookie) {
        RequestConfig config = RequestConfig.copy(RequestConfig.DEFAULT)
                .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        msg.setConfig(config);/*ww  w. j  a  v a  2s. c  o  m*/
    }
    if (StringHelper.containsNonWhitespace(accept)) {
        msg.addHeader("Accept", accept);
    }
    if (StringHelper.containsNonWhitespace(langage)) {
        msg.addHeader("Accept-Language", langage);
    }
}

From source file:org.onehippo.forge.sforcecomps.client.rest.SalesForceRestClient.java

private void addHeaders(HttpRequestBase httpRequest) {
    if (authInfo != null && authInfo.getAccessToken() != null) {
        httpRequest.addHeader("Authorization", "OAuth " + authInfo.getAccessToken());
    }//from  www  . j a  v a 2 s .  co m

    httpRequest.addHeader("Content-Type", "application/json");
}

From source file:org.openecomp.sdc.be.dao.rest.HttpRestClient.java

private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {

    if (headers != null) {
        for (Entry<Object, Object> entry : headers.entrySet()) {
            httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
        }//from www  .  j ava 2  s. co m
    }

}

From source file:org.opennms.protocols.http.HttpUrlConnection.java

@Override
public InputStream getInputStream() throws IOException {
    try {//from   ww w  .ja v  a 2  s.c o  m
        if (m_clientWrapper == null) {
            connect();
        }

        // Build URL
        int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
        URIBuilder ub = new URIBuilder();
        ub.setPort(port);
        ub.setScheme(m_url.getProtocol());
        ub.setHost(m_url.getHost());
        ub.setPath(m_url.getPath());
        if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(),
                    Charset.forName("UTF-8"));
            if (!params.isEmpty()) {
                ub.addParameters(params);
            }
        }

        // Build Request
        HttpRequestBase request = null;
        if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
            final Content cnt = m_request.getContent();
            HttpPost post = new HttpPost(ub.build());
            ContentType contentType = ContentType.create(cnt.getType());
            LOG.info("Processing POST request for {}", contentType);
            if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
                post.setEntity(fields.getEntity());
            } else {
                StringEntity entity = new StringEntity(cnt.getData(), contentType);
                post.setEntity(entity);
            }
            request = post;
        } else {
            request = new HttpGet(ub.build());
        }

        if (m_request != null) {
            // Add Custom Headers
            for (final Header header : m_request.getHeaders()) {
                request.addHeader(header.getName(), header.getValue());
            }
        }

        // Get Response
        CloseableHttpResponse response = m_clientWrapper.execute(request);
        return response.getEntity().getContent();
    } catch (Exception e) {
        throw new IOException(
                "Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(),
                e);
    }
}