Example usage for org.apache.http.auth AuthScope ANY_PORT

List of usage examples for org.apache.http.auth AuthScope ANY_PORT

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY_PORT.

Prototype

int ANY_PORT

To view the source code for org.apache.http.auth AuthScope ANY_PORT.

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java

@Override
public Set<String> scanForests() {
    LOG.debug("Scanning forests");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//from w w  w  .  j av  a2 s  .  c  o  m
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword()));

        String adminUrl = getEntity().getAdminConnectUrl();
        String uri = adminUrl + "/forest_list.xqy";
        HttpGet httpget = new HttpGet(uri);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String result = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);

        Set<String> forests = new HashSet<String>();
        String[] split = result.split("\n");
        Collections.addAll(forests, split);
        return forests;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:my.madet.function.HttpParser.java

public String FetchUrL(String url) {
    StringBuffer result = new StringBuffer();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from w  w w.  j  a va  2 s .c  o m
        // register ntlm auth scheme
        httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope("info.uniten.edu.my", AuthScope.ANY_PORT),
                new NTCredentials(unitenid, unitenpassw, "", ""));

        HttpGet request = new HttpGet(url);
        HttpResponse httpResponse = httpclient.execute(request);

        BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

        String line = "";
        while ((line = br.readLine()) != null) {
            result.append(line);
        }

        br.close();

    } catch (UnknownHostException e) { // no internet connection catch
        e.printStackTrace();
        Log.e("FetchUrL", "No internet ");
        return "No_Internet";
    } catch (Exception e) {
        Log.e("FetchUrL", "Error in http connection:" + e.toString());
        return null;
    }

    String resultString = result.toString();
    String regex = "(?i)<h1>Unauthorized Access</h1>";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(resultString);
    if (matcher.matches())
        return "Unauthorized";

    Log.i("FetchUrL content: ", result.toString());
    return resultString;

}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param solraccount eventual user name used to authenticate on the target Solr
 * @param solraccount eventual password used to authenticate on the target Solr
 * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted
* @param maxBytesPerReponse//from w ww  .j  av  a  2  s.  c o  m
*            maximum acceptable decompressed size in bytes for a response from
*            the remote Solr server. Negative value or Long.MAX_VALUE means no
*            limit.
 * @return a new apache HttpClient instance usable as a custom http client by SolrJ
 */
private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u,
        final String solraccount, final String solrpw, final String host,
        final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) {

    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */

    org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient(
            CONNECTION_MANAGER) {
        @Override
        protected HttpContext createHttpContext() {
            HttpContext context = super.createHttpContext();
            AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
            authCache.put(targetHost, basicAuth);
            context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
            if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) {
                context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY);
            }
            this.setHttpRequestRetryHandler(
                    new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry
            return context;
        }
    };
    org.apache.http.params.HttpParams params = result.getParams();
    /* Set the maximum time to establish a connection to the remote server */
    org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout);
    /* Set the maximum time between data packets reception one a connection has been established */
    org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout);
    /* Set the maximum time to get a connection from the shared connections pool */
    HttpClientParams.setConnectionManagerTimeout(params, timeout);
    result.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING))
                request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP);
            if (!request.containsHeader(HTTP.CONN_DIRECTIVE))
                request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT
        }

    });
    result.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    if (solraccount != null && !solraccount.isEmpty()) {
        org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(solraccount, solrpw));
        result.setCredentialsProvider(credsProvider);
    }

    if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
        /*
         * Add in last position the eventual interceptor limiting the response size, so
         * that this is the decompressed amount of bytes that is considered
         */
        result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                result.getResponseInterceptorCount());
    }

    return result;
}

From source file:io.cloudsoft.marklogic.nodes.MarkLogicNodeSshDriver.java

@Override
public String getForestStatus(String forestName) {
    LOG.trace("Getting status for forest {}", forestName);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//from   www .  j  av  a 2 s.  c o m
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEntity().getUser(), getEntity().getPassword()));

        String adminUrl = getEntity().getAdminConnectUrl();
        String uri = adminUrl + format("/forest_detailed_status.xqy?forest=%s", forestName);
        HttpGet httpget = new HttpGet(uri);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String status = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);
        return status;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.mnxfst.testing.activities.http.AbstractHTTPRequestActivity.java

/**
 * @see com.mnxfst.testing.activities.TSPlanActivity#initialize(com.mnxfst.testing.plan.config.TSPlanConfigOption)
 */// ww w  .j  av  a2 s .c  o m
public void initialize(TSPlanConfigOption cfg) throws TSPlanActivityExecutionException {

    if (cfg == null)
        throw new TSPlanActivityExecutionException("Failed to initialize activity '" + this.getClass().getName()
                + "' due to missing configuration options");

    /////////////////////////////////////////////////////////////////////////////////////////
    // fetch scheme, host, port and path

    this.scheme = (String) cfg.getOption(CFG_OPT_SCHEME);
    if (this.scheme == null || this.scheme.isEmpty())
        throw new TSPlanActivityExecutionException(
                "Required config option '" + CFG_OPT_SCHEME + "' missing for activity '" + getName() + "'");

    this.host = (String) cfg.getOption(CFG_OPT_HOST);
    if (this.host == null || this.host.isEmpty())
        throw new TSPlanActivityExecutionException(
                "Requied config option '" + CFG_OPT_HOST + "' missing for activity '" + getName() + "'");

    String portStr = (String) cfg.getOption(CFG_OPT_PORT);
    if (portStr != null && !portStr.isEmpty()) {
        try {
            this.port = Integer.parseInt(portStr.trim());
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '" + CFG_OPT_PORT
                            + "' for activity '" + getName() + "'");
        }
    }

    // fetch username and password
    this.basicAuthUsername = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_USERNAME);
    this.basicAuthPassword = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PASSWORD);
    this.basicAuthHostScope = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_HOST_SCOPE);

    String authPortScopeStr = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PORT_SCOPE);
    if (authPortScopeStr != null && !authPortScopeStr.trim().isEmpty()) {
        try {
            this.basicAuthPortScope = Integer.parseInt(authPortScopeStr.trim());
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '"
                            + CFG_OPT_BASIC_AUTH_PORT_SCOPE + "' for activity '" + getName() + "'");
        }
    }

    if (this.port <= 0)
        this.port = 80;

    this.path = (String) cfg.getOption(CFG_OPT_PATH);
    if (this.path == null || this.path.isEmpty())
        this.path = "/";

    String maxConnStr = (String) cfg.getOption(CFG_OPT_MAX_CONNECTIONS);
    if (maxConnStr != null && !maxConnStr.isEmpty()) {
        try {
            this.maxConnections = Integer.parseInt(maxConnStr);
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '" + CFG_OPT_MAX_CONNECTIONS
                            + "' for activity '" + getName() + "'");
        }
    }

    // initialize http host and context
    this.httpHost = new HttpHost(this.host, this.port);

    // URI builder
    try {

        // query parameters
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        for (String key : cfg.getOptions().keySet()) {
            if (key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) {
                String value = (String) cfg.getOption(key);
                String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length());
                qParams.add(new BasicNameValuePair(requestParameterName, value));

                if (logger.isDebugEnabled())
                    logger.debug("activity[name=" + getName() + ", id=" + getId() + ", requestParameter="
                            + requestParameterName + ", value=" + value + "]");
            }
        }

        this.destinationURI = URIUtils.createURI(this.scheme, this.host, this.port, this.path,
                URLEncodedUtils.format(qParams, this.contentChartset), null);

        // TODO handle post values

    } catch (URISyntaxException e) {
        throw new TSPlanActivityExecutionException("Failed to initialize uri for [scheme=" + this.scheme
                + ", host=" + this.host + ", port=" + this.port + ", path=" + this.path + "]");
    }

    httpRequestContext.setAttribute(ExecutionContext.HTTP_CONNECTION, clientConnection);
    httpRequestContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", maxConnections=" + maxConnections
                + ", scheme=" + scheme + ", host=" + host + ", port=" + port + ", path=" + path + "]");

    /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////////////
    // protocol settings

    this.userAgent = (String) cfg.getOption(CFG_OPT_USER_AGENT);
    if (this.userAgent == null || this.userAgent.isEmpty())
        this.userAgent = "ptest-server";

    String protocolVersion = (String) cfg.getOption(CFG_OPT_HTTP_PROTOCOL_VERSION);
    if (protocolVersion != null && !protocolVersion.isEmpty()) {
        if (protocolVersion.equalsIgnoreCase("0.9"))
            this.httpVersion = HttpVersion.HTTP_0_9;
        else if (protocolVersion.equalsIgnoreCase("1.0"))
            this.httpVersion = HttpVersion.HTTP_1_0;
        else if (protocolVersion.equalsIgnoreCase("1.1"))
            this.httpVersion = HttpVersion.HTTP_1_1;
        else
            throw new TSPlanActivityExecutionException("Failed to parse http protocol version '"
                    + protocolVersion + "'. Valid value: 0.9, 1.0 and 1.1");
    }

    this.contentChartset = (String) cfg.getOption(CFG_OPT_CONTENT_CHARSET);
    if (this.contentChartset == null || this.contentChartset.isEmpty())
        this.contentChartset = "UTF-8";

    String expectContStr = (String) cfg.getOption(CFG_OPT_EXPECT_CONTINUE);
    if (expectContStr != null && !expectContStr.isEmpty()) {
        this.expectContinue = Boolean.parseBoolean(expectContStr.trim());
    }

    HttpProtocolParams.setUserAgent(httpParameters, userAgent);
    HttpProtocolParams.setVersion(httpParameters, httpVersion);
    HttpProtocolParams.setContentCharset(httpParameters, contentChartset);
    HttpProtocolParams.setUseExpectContinue(httpParameters, expectContinue);

    String httpProcStr = (String) cfg.getOption(CFG_OPT_HTTP_REQUEST_PROCESSORS);
    if (httpProcStr != null && !httpProcStr.isEmpty()) {
        List<HttpRequestInterceptor> interceptors = new ArrayList<HttpRequestInterceptor>();
        String[] procClasses = httpProcStr.split(",");
        if (procClasses != null && procClasses.length > 0) {
            for (int i = 0; i < procClasses.length; i++) {
                try {
                    Class<?> clazz = Class.forName(procClasses[i]);
                    interceptors.add((HttpRequestInterceptor) clazz.newInstance());

                    if (logger.isDebugEnabled())
                        logger.debug("activity[name=" + getName() + ", id=" + getId()
                                + ", httpRequestInterceptor=" + procClasses[i] + "]");
                } catch (Exception e) {
                    throw new TSPlanActivityExecutionException("Failed to instantiate http interceptor '"
                            + procClasses[i] + "' for activity '" + getName() + "'. Error: " + e.getMessage());
                }
            }
        }

        this.httpRequestResponseProcessor = new ImmutableHttpProcessor(
                (HttpRequestInterceptor[]) interceptors.toArray(EMPTY_HTTP_REQUEST_INTERCEPTOR_ARRAY));
        this.hasRequestResponseProcessors = true;
    }

    this.method = (String) cfg.getOption(CFG_OPT_METHOD);
    if (method == null || method.isEmpty())
        this.method = "GET";
    if (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post"))
        throw new TSPlanActivityExecutionException(
                "Invalid method '" + method + "' found for activity '" + getName() + "'");

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", method=" + method + ", user-agent="
                + userAgent + ", httpVersion=" + httpVersion + ", contentCharset=" + contentChartset
                + ", expectContinue=" + expectContinue + "]");

    /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////////////
    // fetch proxy settings

    this.proxyUrl = (String) cfg.getOption(CFG_OPT_PROXY_URL);

    String proxyPortStr = (String) cfg.getOption(CFG_OPT_PROXY_PORT);
    if (proxyPortStr != null && !proxyPortStr.isEmpty()) {
        try {
            this.proxyPort = Integer.parseInt(proxyPortStr.trim());
        } catch (NumberFormatException e) {
            throw new TSPlanActivityExecutionException(
                    "Failed to parse expected numerical value for config option '" + CFG_OPT_PROXY_PORT
                            + "' for activity '" + getName() + "'");
        }
    }

    this.proxyUser = (String) cfg.getOption(CFG_OPT_PROXY_USER);
    this.proxyPassword = (String) cfg.getOption(CFG_OPT_PROXY_PASSWORD);

    if (proxyUrl != null && !proxyUrl.isEmpty()) {

        if (proxyPort > 0)
            this.proxyHost = new HttpHost(proxyUrl, proxyPort);
        else
            this.proxyHost = new HttpHost(proxyUrl);
    }

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", proxyUrl=" + proxyUrl
                + ", proxyPort=" + proxyPort + ", proxyUser=" + proxyUser + "]");

    /////////////////////////////////////////////////////////////////////////////////////////

    //      /////////////////////////////////////////////////////////////////////////////////////////
    //      // fetch request parameters
    //
    //      // unfortunately we must step through the whole set of keys ... 
    //      for(String key : cfg.getOptions().keySet()) {
    //         if(key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) {
    //            String value = (String)cfg.getOption(key);
    //            String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length());            
    //            httpParameters.setParameter(requestParameterName, value);            
    //            if(logger.isDebugEnabled())
    //               logger.debug("activity[name="+getName()+", id="+getId()+", requestParameter="+requestParameterName+", value="+value+"]");
    //         }
    //      }
    //
    //      /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////////////
    // configure scheme registry and initialize http client

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId() + ", registeredSchemes={http, https}]");

    ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager(
            schemeRegistry);
    threadSafeClientConnectionManager.setMaxTotal(maxConnections);
    threadSafeClientConnectionManager.setDefaultMaxPerRoute(maxConnections);
    this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager);

    if (this.basicAuthUsername != null && !this.basicAuthUsername.trim().isEmpty()
            && this.basicAuthPassword != null && !this.basicAuthPassword.trim().isEmpty()) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.basicAuthUsername,
                this.basicAuthPassword);
        AuthScope authScope = null;
        if (basicAuthHostScope != null && !basicAuthHostScope.isEmpty() && basicAuthPortScope > 0) {
            authScope = new AuthScope(basicAuthHostScope, basicAuthPortScope);
        } else {
            authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        }

        this.httpClient.getCredentialsProvider().setCredentials(authScope, creds);

        if (logger.isDebugEnabled())
            logger.debug("activity[name=" + getName() + ", id=" + getId() + ", credentials=("
                    + creds.getUserName() + ", " + creds.getPassword() + "), authScope=(" + authScope.getHost()
                    + ":" + authScope.getPort() + ")]");
    }

    if (logger.isDebugEnabled())
        logger.debug("activity[name=" + getName() + ", id=" + getId()
                + ", threadSafeClientConnectionManager=initialized]");

}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean patch2DjangoJSONArray(Context context, JSONArray jsonArray, String uploadurl,
        String username, String password) {

    String response = "";

    try {/*from w ww. j  a va2 s.  co  m*/

        JSONObject obj = new JSONObject();
        obj.put("objects", jsonArray);
        JSONArray emptyarray = new JSONArray();
        obj.put("deleted_objects", emptyarray);

        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        // Create a new HttpClient and Post Header
        HttpPatch httppatch = new HttpPatch(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppatch.setHeader("Content-type", "application/json");

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.setCredentialsProvider(credProvider);
        // ByteArrayEntity bae = new ByteArrayEntity(obj.toString()
        // .getBytes("UTF8"));

        StringEntity se = new StringEntity(obj.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        // bae.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
        // "application/json"));
        httppatch.setEntity(se);

        // Execute HTTP Post Request

        HttpResponse httpResponse = httpclient.execute(httppatch);

        response = httpResponse.getStatusLine().toString();

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (response.contains("ACCEPTED")) {
        return true;
    } else {
        return false;
    }

}

From source file:nl.nn.adapterframework.http.HttpSenderBase.java

public void configure() throws ConfigurationException {
    super.configure();

    if (!getMethodType().equals("POST")) {
        if (!isParamsInUrl()) {
            throw new ConfigurationException(
                    getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
        }//from ww w.  ja v  a  2 s  .c  om
        if (StringUtils.isNotEmpty(getInputMessageParam())) {
            throw new ConfigurationException(
                    getLogPrefix() + "inputMessageParam can only be set for methodType POST");
        }
    }

    /**
     * TODO find out if this really breaks proxy authentication or not.
     */
    //      httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(getTimeout());
    requestConfig.setConnectionRequestTimeout(getTimeout());
    requestConfig.setSocketTimeout(getTimeout());

    if (paramList != null) {
        paramList.configure();
        if (StringUtils.isNotEmpty(getUrlParam())) {
            urlParameter = paramList.findParameter(getUrlParam());
            addParameterToSkip(urlParameter);
        }
    }
    if (getMaxConnections() <= 0) {
        throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections()
                + "], which is not enough for adequate operation");
    }
    try {
        if (urlParameter == null) {
            if (StringUtils.isEmpty(getUrl())) {
                throw new ConfigurationException(
                        getLogPrefix() + "url must be specified, either as attribute, or as parameter");
            }
            staticUri = getURI(getUrl());
        }

        URL certificateUrl = null;
        URL truststoreUrl = null;

        if (!StringUtils.isEmpty(getCertificate())) {
            certificateUrl = ClassUtils.getResourceURL(getClassLoader(), getCertificate());
            if (certificateUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
            }
            log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
        }
        if (!StringUtils.isEmpty(getTruststore())) {
            truststoreUrl = ClassUtils.getResourceURL(getClassLoader(), getTruststore());
            if (truststoreUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
            }
            log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
        }

        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        if (!isVerifyHostname())
            hostnameVerifier = new NoopHostnameVerifier();

        // Add javax.net.ssl.SSLSocketFactory.getDefault() SSLSocketFactory if non has been set.
        // See: http://httpcomponents.10934.n7.nabble.com/Upgrading-commons-httpclient-3-x-to-HttpClient4-x-td19333.html
        // 
        // The first time this method is called, the security property "ssl.SocketFactory.provider" is examined. 
        // If it is non-null, a class by that name is loaded and instantiated. If that is successful and the 
        // object is an instance of SSLSocketFactory, it is made the default SSL socket factory.
        // Otherwise, this method returns SSLContext.getDefault().getSocketFactory(). If that call fails, an inoperative factory is returned.
        javax.net.ssl.SSLSocketFactory socketfactory = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory
                .getDefault();
        sslSocketFactory = new SSLConnectionSocketFactory(socketfactory, hostnameVerifier);

        if (certificateUrl != null || truststoreUrl != null || isAllowSelfSignedCertificates()) {
            try {
                CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null,
                        getCertificatePassword());
                CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null,
                        getTruststorePassword());

                SSLContext sslContext = AuthSSLConnectionSocket.createSSLContext(certificateUrl,
                        certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl,
                        truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(),
                        isAllowSelfSignedCertificates(), isVerifyHostname(),
                        isIgnoreCertificateExpiredException(), getProtocol());

                sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
                log.debug(getLogPrefix() + "created custom SSLConnectionSocketFactory");

            } catch (Throwable t) {
                throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory",
                        t);
            }
        }

        // This method will be overwritten by the connectionManager when connectionPooling is enabled!
        // Can still be null when no default or an invalid system sslSocketFactory has been defined
        if (sslSocketFactory != null)
            httpClientBuilder.setSSLSocketFactory(sslSocketFactory);

        credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(credentials.getUsername())) {
            String uname;
            if (StringUtils.isNotEmpty(getAuthDomain())) {
                uname = getAuthDomain() + "\\" + credentials.getUsername();
            } else {
                uname = credentials.getUsername();
            }

            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(uname, credentials.getPassword()));

            requestConfig.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            requestConfig.setAuthenticationEnabled(true);
        }
        if (StringUtils.isNotEmpty(getProxyHost())) {
            HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
            AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);

            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(),
                    getProxyPassword());

            if (StringUtils.isNotEmpty(pcf.getUsername())) {
                Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
                credentialsProvider.setCredentials(scope, credentials);
            }
            log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");

            if (prefillProxyAuthCache()) {
                requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));

                AuthCache authCache = httpClientContext.getAuthCache();
                if (authCache == null)
                    authCache = new BasicAuthCache();

                authCache.put(proxy, new BasicScheme());
                httpClientContext.setAuthCache(authCache);
            }

            requestConfig.setProxy(proxy);
            httpClientBuilder.setProxy(proxy);
        }

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
    }

    if (StringUtils.isNotEmpty(getStyleSheetName())) {
        try {
            URL stylesheetURL = ClassUtils.getResourceURL(getClassLoader(), getStyleSheetName());
            if (stylesheetURL == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
            }
            transformerPool = TransformerPool.getInstance(stylesheetURL);
        } catch (IOException e) {
            throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]",
                    e);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException(
                    getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]",
                    te);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

    // The redirect strategy used to only redirect GET, DELETE and HEAD.
    httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return isFollowRedirects();
        }
    });
}

From source file:com.rabbitmq.http.client.Client.java

private CredentialsProvider getCredentialsProvider(final URL url, final String username,
        final String password) {
    CredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    return cp;/*from   w  w w .j a va2  s  . c  om*/
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Set Authentication to a given {@link DefaultHttpClient} instance.
 * //from   ww  w.  j  a v  a  2 s.c  om
 * @param url
 *            URL of resource.
 * @param username
 *            User name for authentication
 * @param password
 *            Password for authentication.
 * @throws WebserverSystemException
 *             Thrown if connection failed.
 */
public void setAuthentication(final DefaultHttpClient client, final URL url, final String username,
        final String password) {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    final Credentials creds = new UsernamePasswordCredentials(username, password);
    credsProvider.setCredentials(authScope, creds);
    client.setCredentialsProvider(credsProvider);
    // don't wait for auth request
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            final CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            // If not auth scheme has been initialized yet
            if (authState.getAuthScheme() == null) {
                final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                // Obtain credentials matching the target host
                final Credentials creds = credsProvider.getCredentials(authScope);
                // If found, generate BasicScheme preemptively
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    };
    client.addRequestInterceptor(preemptiveAuth, 0);
}

From source file:net.tac42.subtails.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;//w w  w . j  av  a 2s  .  c o  m
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        SharedPreferences prefs = Util.getPreferences(context);
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}