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

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

Introduction

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

Prototype

String ANY_SCHEME

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

Click Source Link

Document

The null value represents any authentication scheme.

Usage

From source file:majordodo.client.http.HTTPClientConnection.java

private HttpClientContext getContext() throws IOException {
    if (context == null) {
        BrokerAddress broker = getBroker();
        String scheme = broker.getProtocol();
        HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme);

        context = HttpClientContext.create();
        if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(),
                    configuration.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(),
                    AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), creds);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }/* ww  w.j  a  v a2s . co m*/

    }
    return context;
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * Add authentication credentials/*from  w  ww  .jav  a 2 s .  co m*/
 */
public <T extends Client> T addCredentials(String target, String realm, String scheme, Credentials credentials)
        throws URISyntaxException {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    if (target != null) {
        URI uri = new URI(target);
        host = uri.getHost();
        port = uri.getPort();
    }
    HttpHost targetHost = new HttpHost(host, port, scheme);
    getDefaultHttpClient().getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(),
                    realm != null ? realm : AuthScope.ANY_REALM,
                    scheme != null ? scheme : AuthScope.ANY_SCHEME), credentials);
    return (T) this;
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

@Override
public void addAuth(AuthCredentials creds) {
    String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST
            : creds.getHost();//from   ww  w. ja v a2  s .  co  m
    String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM
            : creds.getRealm();
    int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT);
    String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME;
    AuthScope scope = new AuthScope(host, port, realm, scheme);
    if (AuthScheme.NTLM == creds.getScheme()) {
        context.getCredentialsProvider().setCredentials(scope,
                new NTCredentials(creds.getUserName(), creds.getPassword(), "tank-test", creds.getRealm()));
    } else {
        context.getCredentialsProvider().setCredentials(scope,
                new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword()));
    }

}

From source file:gov.nasa.ensemble.common.io.RemotableFile.java

private File getConsistentFile(long modified, REMOTE_FILE_MODES myMode, int socketTimeout)
        throws SocketTimeoutException {
    Date modifiedDate = new Date(modified);
    DateFormat df = new SimpleDateFormat(DATE_FORMAT_STR);
    String formatedModifiedDate = df.format(modifiedDate);
    if (remoteFile == null) {
        return localFile;
    }/*from  www.  ja  v  a2 s .  c  om*/
    HttpConnectionParams.setSoTimeout(client.getParams(), socketTimeout);

    // tell the client to use the credential we got as parameter
    // if we have an authenticator
    Authenticator auth = AuthenticationUtil.getAuthenticator();
    if (auth != null) {
        if (client instanceof AbstractHttpClient) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME), auth.getCredentials());
        }
        //         state.setAuthenticationPreemptive(true);
    }

    HttpResponse response = null;
    HttpGet get = new HttpGet(remoteFile.toString());
    HttpClientParams.setRedirecting(get.getParams(), false);
    HttpClientParams.setAuthenticating(get.getParams(), true);
    try {
        get.setHeader(HttpHeaders.IF_MODIFIED_SINCE, formatedModifiedDate);
        response = client.execute(get);
        if (HttpStatus.SC_NOT_MODIFIED == response.getStatusLine().getStatusCode()) {
            return localFile;
        } else if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            InputStream is = response.getEntity().getContent();
            getRemoteFileFromStream(is);
            if (REMOTE_FILE_MODES.CHECK_CUSTOM_TIMESTAMP == myMode) {
                localFile.setLastModified(customTimeStamp);
            } else {
                setModifiedTime(get);
            }
            return localFile;
        } else if (HttpStatus.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
            remoteFileNotFound();
        }
    } catch (SocketTimeoutException e1) {
        throw e1;
    } catch (IOException e1) {
        // HACK HACK HACK HACK
        if (e1.getMessage().contains("SocketTimeoutException"))
            throw new SocketTimeoutException();
        else
            trace.warn("Error connecting to server when " + "checking the file modified time ", e1);
    } finally {
        try {
            HttpUtils.consume(get, response);
        } catch (IOException e) {
            trace.error(e);
        }
    }
    return localFile;

}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

protected static DefaultHttpClient prepareHttpClient(URI uri, GHCredentials apiCredentials) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    httpClient.addRequestInterceptor(preemptiveAuth, 0);

    if (apiCredentials != null) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(apiCredentials.getUsername(), apiCredentials.getPassword()));
    }//w ww. j  a  v  a 2  s.co m
    return httpClient;
}

From source file:org.codelibs.fess.es.config.exentity.DataConfig.java

private AuthScope getAuthScope(final String webAuthName, final String scheme,
        final Map<String, String> paramMap) {
    final String hostname = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".host");
    final String port = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".port");
    final String realm = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".realm");
    AuthScope authScope;/*from w ww  . j a  v  a  2 s .  c  om*/
    if (StringUtil.isBlank(hostname)) {
        authScope = AuthScope.ANY;
    } else {
        int p = AuthScope.ANY_PORT;
        if (StringUtil.isNotBlank(port)) {
            try {
                p = Integer.parseInt(port);
            } catch (final NumberFormatException e) {
                logger.warn("Failed to parse " + port, e);
            }
        }

        String r = realm;
        if (StringUtil.isBlank(realm)) {
            r = AuthScope.ANY_REALM;
        }

        String s = scheme;
        if (StringUtil.isBlank(scheme) || Constants.NTLM.equals(scheme)) {
            s = AuthScope.ANY_SCHEME;
        }
        authScope = new AuthScope(hostname, p, r, s);
    }
    return authScope;
}

From source file:gov.nasa.ensemble.common.io.RemotableFile.java

/**
 * This method will download the specified localFile to the local cache. Any
 * directories that need to be created will be generated as a side-effect of
 * this action. There is no discretion regarding whether the localFile
 * currently exists or not, if a localFile exists in the specified location,
 * it will be overwritten.//from w  ww. ja va2s. c om
 * 
 * If the localFile does not exist in the central repository, this method
 * will throw an IOException and will not create a zero length localFile.
 * However the directories that would have contained the localFile will be
 * created.
 * 
 * @return a copy of the remote localFile specified
 * @throws IOException
 *             Exception will be thrown if the remote localFile does not
 *             exist.
 */
private void downloadRemoteFile(int socketTimeout) throws Exception {
    if (remoteFile == null)
        return;

    // tell the client to use the credential we got as parameter
    Authenticator authenticator = AuthenticationUtil.getAuthenticator();
    if (authenticator != null) {
        if (client instanceof AbstractHttpClient) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                    authenticator.getCredentials());
        }
        //         state.setAuthenticationPreemptive(true);
    }

    final HttpGet get = new HttpGet(remoteFile.toString());
    HttpClientParams.setAuthenticating(get.getParams(), true);
    HttpClientParams.setRedirecting(get.getParams(), false);
    HttpUtils.execute(client, get, new HttpUtils.HttpResponseHandler() {
        @Override
        public void handleResponse(HttpResponse response) throws Exception {
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                getRemoteFileFromStream(response.getEntity().getContent());
                setModifiedTime(get);
            }
        }
    });
}

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   w w w. ja va 2  s  .c o m
        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:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java

private static String executeJsonRpc(SolidFireConnection sfConnection, String strJsonToExecute) {
    DefaultHttpClient httpClient = null;
    StringBuilder sb = new StringBuilder();

    try {/*from  ww w.  j  a v a2 s .  co m*/
        StringEntity input = new StringEntity(strJsonToExecute);

        input.setContentType("application/json");

        httpClient = getHttpClient(sfConnection.getManagementPort());

        URI uri = new URI("https://" + sfConnection.getManagementVip() + ":" + sfConnection.getManagementPort()
                + "/json-rpc/6.0");
        AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword());

        httpClient.getCredentialsProvider().setCredentials(authScope, credentials);

        HttpPost postRequest = new HttpPost(uri);

        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (!isSuccess(response.getStatusLine().getStatusCode())) {
            throw new CloudRuntimeException("Failed on JSON-RPC API call. HTTP error code = "
                    + response.getStatusLine().getStatusCode());
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));) {
            String strOutput;
            while ((strOutput = br.readLine()) != null) {
                sb.append(strOutput);
            }
        } catch (IOException ex) {
            throw new CloudRuntimeException(ex.getMessage());
        }
    } catch (UnsupportedEncodingException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (ClientProtocolException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (IOException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (URISyntaxException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } finally {
        if (httpClient != null) {
            try {
                httpClient.getConnectionManager().shutdown();
            } catch (Exception t) {
                s_logger.info("[ignored]" + "error shutting down http client: " + t.getLocalizedMessage());
            }
        }
    }

    return sb.toString();
}