Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getParams.

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public Document invoke() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + OpSource.class.getName() + ".invoke()");
    }//from  w  w  w  .ja  v a 2s .co  m
    try {
        URL url = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e1) {
            throw new CloudException(e1);
        }
        final String host = url.getHost();
        final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
        final String urlStr = url.toString();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        /**  HTTP Authentication */
        String uid = new String(provider.getContext().getAccessPublic());
        String pwd = new String(provider.getContext().getAccessPrivate());

        /** Type of authentication */
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.BASIC);

        httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null),
                new UsernamePasswordCredentials(uid, pwd));

        if (wire.isDebugEnabled()) {
            wire.debug("--------------------------------------------------------------> " + urlStr);
            wire.debug("");
        }

        AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr);
        method.setParams(new BasicHttpParams().setParameter(urlStr, url));
        /**  Set headers */
        method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key));

        /** POST/PUT method specific logic */
        if (method instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method;
            String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key);

            if (requestBody != null) {
                if (wire.isDebugEnabled()) {
                    wire.debug(requestBody);
                }

                AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes());
                entity.setContentType(parameters.get(OpSource.Content_Type_Key));
                entityEnclosingMethod.setEntity(entity);
            } else {
                throw new CloudException("The request body is null for a post request");
            }
        }

        /** Now parse the xml */
        try {

            HttpResponse httpResponse;
            int status;
            if (wire.isDebugEnabled()) {
                for (org.apache.http.Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
            }
            /**  Now execute the request */
            APITrace.trace(provider, method.toString() + " " + urlStr);
            httpResponse = httpclient.execute((HttpUriRequest) method);
            status = httpResponse.getStatusLine().getStatusCode();
            if (wire.isDebugEnabled()) {
                wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            org.apache.http.Header[] headers = httpResponse.getAllHeaders();

            HttpEntity entity = httpResponse.getEntity();
            if (wire.isDebugEnabled()) {
                wire.debug("HTTP xml status code ---------" + status);
                for (org.apache.http.Header h : headers) {
                    if (h.getValue() != null) {
                        wire.debug(h.getName() + ": " + h.getValue().trim());
                    } else {
                        wire.debug(h.getName() + ":");
                    }
                }
                /** Can not enable this line, otherwise the entity would be empty*/
                // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity));
                wire.debug("-----------------");
            }
            if (entity == null) {
                parseError(status, "Empty entity");
            }

            String responseBody = EntityUtils.toString(entity);

            if (status == HttpStatus.SC_OK) {
                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
                    if (input != null) {
                        Document doc = null;
                        try {
                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
                            if (wire.isDebugEnabled()) {
                                try {
                                    TransformerFactory transfac = TransformerFactory.newInstance();
                                    Transformer trans = transfac.newTransformer();
                                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                    StringWriter sw = new StringWriter();
                                    StreamResult result = new StreamResult(sw);
                                    DOMSource source = new DOMSource(doc);
                                    trans.transform(source, result);
                                    String xmlString = sw.toString();
                                    wire.debug(xmlString);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            logger.debug(ex.toString(), ex);
                        }
                        return doc;
                    }
                } catch (IOException e) {
                    logger.error(
                            "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                /*
                catch( SAXException e ) {
                throw new CloudException(e);
                }                    
                catch( ParserConfigurationException e ) {
                throw new InternalException(e);
                }
                */
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new CloudException("An internal error occured: The endpoint was not found");
            } else {
                if (responseBody != null) {
                    parseError(status, responseBody);
                    Document parsedError = null;
                    if (!responseBody.contains("<HR")) {
                        parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
                        if (wire.isDebugEnabled()) {
                            try {
                                TransformerFactory transfac = TransformerFactory.newInstance();
                                Transformer trans = transfac.newTransformer();
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                StringWriter sw = new StringWriter();
                                StreamResult result = new StreamResult(sw);
                                DOMSource source = new DOMSource(parsedError);
                                trans.transform(source, result);
                                String xmlString = sw.toString();
                                wire.debug(xmlString);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else
                        logger.debug("Error message was unparsable");
                    return parsedError;
                }
            }
        } catch (ParseException e) {
            throw new CloudException(e);
        } catch (SAXException e) {
            throw new CloudException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CloudException(e);
        } catch (ParserConfigurationException e) {
            throw new CloudException(e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + OpSource.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------------> " + endpoint);
        }
    }
    return null;
}

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        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);
    }//  w w w. j a  va  2s. c om
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

From source file:com.netbase.insightapi.clientlib.InsightAPIQuery.java

/**
 * Make a diligent attempt to run the query on the server, retrying in the
 * case of timeouts. Passes through any non-retriable exceptions, but does
 * not check that the operation was "successful".
 * //from  w  w w  . ja va  2s.  co m
 * This entry point should not be used directly by application programs.
 * Queries should be run with either UserChannel.run() or
 * UserChannel.start().
 * 
 * @param userChannel
 * @throws Exception
 */
protected void runQuery(UserChannel userChannel) throws Exception {
    DefaultHttpClient httpclient = null;
    try {

        statusCode = -1;
        statusString = null;

        String url = getUrl();

        if (debug)
            userChannel.logInfo(serial + " requesting: " + URLDecoder.decode(url, URL_ARG_ENCODING_CHARSET));

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url);

        httpclient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
        httpclient.getParams().setParameter("http.socket.timeout", new Integer(timeout));
        httpclient.getParams().setParameter("http.protocol.content-charset", URL_ARG_ENCODING_CHARSET);
        httpclient.getParams().setParameter("http.tcp.nodelay", Boolean.TRUE);
        httpclient.getParams().setParameter("http.connection.timeout", new Integer(timeout));

        // set the proxy properties, if any
        if (proxyServer != null) {
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyServer, proxyPort, proxyScheme));
        }
        // set retry handler
        httpclient.setHttpRequestRetryHandler(new RetryHandler(url, userChannel));

        // run the request
        long startTime = System.currentTimeMillis();
        HttpResponse response = httpclient.execute(httpget);

        // get result statistics
        elapsedMs = (System.currentTimeMillis() - startTime);
        statusCode = response.getStatusLine().getStatusCode();
        statusString = response.getStatusLine().getReasonPhrase();

        // gather the internet headers
        for (Header header : response.getAllHeaders()) {
            // force the headers to lower case. As they come from the
            // server, they are CamelCase, e.g.
            // X-RealTimeConcurrentRateLimit-Max
            headers.put(header.getName().toLowerCase(), header.getValue());
        }

        // retrieve the content
        String charset = "UTF-8";
        if (response.getEntity() != null && response.getEntity().getContentEncoding() != null) {
            charset = response.getEntity().getContentEncoding().getValue();
        }
        if (response.getEntity() != null) {
            responseContent = EntityUtils.toString(response.getEntity(), charset);

            if (debug)
                userChannel.logInfo(serial + " result: " + responseContent.length()
                        + " characters, status code: " + statusCode + ", statusString: " + statusString);
        }
    }

    finally {
        if (httpclient != null) {
            // close connection
            httpclient.getConnectionManager().shutdown();
        }
    }

}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientUtil.java

private static void configureAuthentication(final DefaultHttpClient httpClient, final String ctxPrefix,
        final RemoteStorageContext ctx, final RemoteAuthenticationSettings ras, final Logger logger,
        final String authScope) {
    if (ras != null) {
        List<String> authorisationPreference = new ArrayList<String>(2);
        authorisationPreference.add(AuthPolicy.DIGEST);
        authorisationPreference.add(AuthPolicy.BASIC);

        Credentials credentials = null;//www  .  j  a v  a  2  s. c  o  m

        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras;

            // TODO - implement this
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthPolicy.NTLM);

            logger(logger).info("... {}authentication setup for NTLM domain '{}'", authScope,
                    nras.getNtlmDomain());

            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());

            ctx.putContextObject(ctxPrefix + CTX_KEY_NTLM_IS_IN_USE, Boolean.TRUE);
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

            // Using Username/Pwd auth, will not add NTLM
            logger(logger).info("... {}authentication setup for remote storage with username '{}'", authScope,
                    uras.getUsername());

            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
        }

        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference);
    }
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

private void configureHttpClient(final DefaultHttpClient httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);/*from  w  w w  .ja  v a 2 s.  c om*/

    configureAuthentication(httpclient, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        httpclient.getAuthSchemes().register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.getAuthSchemes().register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        configureAuthentication(httpclient, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(httpclient, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.getParams().setBooleanParameter(HANDLE_AUTHENTICATION, true);
}

From source file:org.apache.manifoldcf.authorities.authorities.generic.GenericAuthority.java

protected DefaultHttpClient getClient() throws ManifoldCFException {
    synchronized (this) {
        if (client != null) {
            return client;
        }//from  w ww .  j a  v a 2  s  . c  om
        DefaultHttpClient cl = new DefaultHttpClient();
        if (genericLogin != null && !genericLogin.isEmpty()) {
            try {
                URL url = new URL(genericEntryPoint);
                Credentials credentials = new UsernamePasswordCredentials(genericLogin, genericPassword);
                cl.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(),
                        url.getPort() > 0 ? url.getPort() : 80, AuthScope.ANY_REALM), credentials);
                cl.addRequestInterceptor(new PreemptiveAuth(credentials), 0);
            } catch (MalformedURLException ex) {
                client = null;
                sessionExpirationTime = -1L;
                throw new ManifoldCFException("getClient exception: " + ex.getMessage(), ex);
            }
        }
        HttpConnectionParams.setConnectionTimeout(cl.getParams(), connectionTimeoutMillis);
        HttpConnectionParams.setSoTimeout(cl.getParams(), socketTimeoutMillis);
        sessionExpirationTime = System.currentTimeMillis() + 300000L;
        client = cl;
        return cl;
    }
}