Example usage for org.apache.http.protocol BasicHttpContext setAttribute

List of usage examples for org.apache.http.protocol BasicHttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext setAttribute.

Prototype

public void setAttribute(String str, Object obj) 

Source Link

Usage

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Sets necessary HTTP authentication for this partner, depending on if it is an asny MDN that will be sent or an AS2 message.
 *If the partner is not configured to use HTTP authentication in any kind nothing will happen in here
 *//*  w  w  w .  j ava2s.  c  om*/
private void setHTTPAuthentication(DefaultHttpClient client, Partner receiver, boolean isMDN) {
    HTTPAuthentication authentication = null;
    if (isMDN) {
        authentication = receiver.getAuthenticationAsyncMDN();
    } else {
        authentication = receiver.getAuthentication();
    }
    if (authentication.isEnabled()) {
        Credentials userPassCredentials = new UsernamePasswordCredentials(authentication.getUser(),
                authentication.getPassword());
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, userPassCredentials);
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }/*from  w ww .j  av a 2 s  . c  om*/
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST//  w ww  .ja  v  a2s.  c o m
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */
private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getPostURL());
    String resultsFormat = this.getContentType(resultType);
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    // add params
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("format", resultsFormat));
    params.add(new BasicNameValuePair("default-graph-uri", this.dataset));

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // finish new stuff

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    JSONObject resp;
    try {
        resp = (JSONObject) JSONValue.parse(responseTxt);
    } catch (Exception e) {
        entity.getContent().close();
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            entity.getContent().close();
            throw new Exception(responseTxt);
        }
        entity.getContent().close();
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);
        entity.getContent().close();

        return procResp;
    }
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST/*from  ww w  . j  a v a  2s  . co  m*/
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */

public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getUploadURL());
    String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.addTextBody("graph-uri", this.dataset);
    builder.addBinaryBody("res-file", owl);
    HttpEntity entity = builder.build();
    httppost.setEntity(entity);

    /*  THIS IS THE MULTIPART FORMAT WE NEED TO SEND.
            
    Content-Type: multipart/form-data; boundary=---------------------------32932166721282
    Content-Length: 234
            
    -----------------------------32932166721282
    Content-Disposition: form-data; name="graph-uri"
            
    http://www.kdl.ge.com/changeme
    -----------------------------32932166721282
    Content-Disposition: form-data; name="res-file"; filename="employee.owl"
    Content-Type: application/octet-stream
            
    <rdf:RDF
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:owl="http://www.w3.org/2002/07/owl#"
        xmlns="http://kdl.ge.com/pd/employee#"
        xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      .
      .
      .
    </rdf:RDF>
            
    -----------------------------32932166721282--
            
     */

    executeTestQuery();

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity resp_entity = response_http.getEntity();
    // get response with HTML tags removed
    String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " ");

    SimpleResultSet ret = new SimpleResultSet();

    if (responseTxt.trim().isEmpty()) {
        // success or bad login :-(
        ret.setSuccess(true);
    } else {
        ret.setSuccess(false);
        ret.addRationaleMessage(responseTxt);
    }
    resp_entity.getContent().close();
    return ret.toJson();
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using GET (use should be rare - in cases where POST is not supported)
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception/*ww w. j  a  v  a 2s.  c o  m*/
 */
@SuppressWarnings("unused")
private JSONObject executeQueryAuthGet(String queryAndUrl, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //ResponseHandler<String> responseHandler = new BasicResponseHandler();

    System.err.println("the server name was " + this.server);
    System.err.println("the port id was " + this.port);
    System.err.println("the user name was " + "SPARQL/" + this.userName);
    System.err.println("the password was " + this.password);

    System.err.println(queryAndUrl);

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet(queryAndUrl);
    String resultsFormat = this.getContentType(resultType);
    httpget.addHeader("Accept", resultsFormat);

    System.out.println("executing request" + httpget.getRequestLine());

    //        String responseTxt = httpclient.execute(httpget, responseHandler);
    HttpResponse response_http = httpclient.execute(targetHost, httpget, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    if (responseTxt.length() < 100) {
        System.err.println("SparqlEndpointInterface received: " + responseTxt);
    } else {
        System.err.println("SparqlEndpointInterface received: " + responseTxt.substring(0, 99) + "... ("
                + responseTxt.length() + " chars)");
    }

    JSONObject resp;
    try {
        resp = (JSONObject) new JSONParser().parse(responseTxt);
    } catch (Exception e) {
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            throw new Exception(responseTxt);
        }
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);

        return procResp;
    }
}

From source file:org.trancecode.xproc.step.HttpRequestStepProcessor.java

private HttpClient prepareHttpClient(final XProcHttpRequest xProcRequest, final BasicHttpContext localContext) {
    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);
    final DefaultHttpClient httpClient = new DefaultHttpClient(connManager);
    final ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (xProcRequest.getCredentials() != null) {
        final List<String> authPref = Lists.newArrayList(AuthPolicy.BASIC, AuthPolicy.DIGEST);
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref);
        httpClient.setCredentialsProvider(xProcRequest.getCredentials());
        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(xProcRequest.getHttpHost(), basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }//from   ww  w  . j a v  a  2 s. co  m
    return httpClient;
}