Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ClientCredentials} and optional {@code Proxy}
 * configuration.// w w w .  j  a v  a  2 s . c o  m
 * @param clientCredentials the Okta account API Key that will be used to authenticate the client with Okta's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Okta API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Okta API server.
 *                             If null, then SSWS will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Okta configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}

From source file:com.stormpath.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ApiKey} and optional {@code Proxy}
 * configuration./*from w w w.j a  va 2s .co  m*/
 * @param clientCredentials the Stormpath account API Key that will be used to authenticate the client with Stormpath's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Stormpath API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Stormpath API server.
 *                             If null, then Sauthc1 will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Stormpath configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}

From source file:com.polydeucesys.eslogging.core.jest.JestHttpConnection.java

private JestClientFactory setupDefaultClientFactory() {
    JestClientFactory factory = new JestClientFactory();
    if (getClientCredentialConfig() != null) {
        factory = new JestClientFactory() {
            @Override//from ww  w . j  a v a  2  s.com
            protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) {
                HttpClientCredentialConfig credConfig = getClientCredentialConfig();
                CredentialsProvider baseProvider = new BasicCredentialsProvider();
                AuthScope scope = new AuthScope(credConfig.getAuthScopeHost(), credConfig.getAuthScopePort(),
                        credConfig.getAuthScopeRealm());

                baseProvider.setCredentials(scope, credConfig.getCredentials());
                builder.setDefaultCredentialsProvider(baseProvider);
                return builder;
            }
        };
    }
    return factory;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);/*from   w w  w  .  ja va 2 s .co  m*/
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider,
                authData);
    }

    return client;
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Initializes the connector and prepares it for use.
 *//*w w w .  j a v  a2  s.c  om*/
public void initialize() throws IOException {
    log.info("HttpDataSource: initialize");

    SSLConnectionSocketFactory sf = getSocketFactory();
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sf).build();

    connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connectionManager.setMaxTotal(maxConnections);
    connectionManager.setDefaultMaxPerRoute(maxConnections);

    /*
     * Create our client 
     */

    // HttpClientBuilder cb = HttpClients.custom().setConnectionManager(connectionManager);
    HttpClientBuilder cb = HttpClientBuilder.create().setConnectionManager(connectionManager);
    // requires lib 4.x
    // cb = cb.setConnectionManagerShared(true);

    if (username != null && password != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username,
                password);
        credsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
        cb = cb.setDefaultCredentialsProvider(credsProvider);
        log.info("HttpDataSource: added basic creds ");
    }
    httpClient = cb.build();
}

From source file:fr.paris.lutece.plugins.mylutece.modules.oauth.authentication.OAuthAuthentication.java

/**
 * Builds a new {@link HttpClient}/*from  ww  w  .jav a  2 s  . c  om*/
 * @return new HttpClient
 */
private HttpClient getHttpClient() {
    DefaultHttpClient client = new DefaultHttpClient();

    String strUserName = AppPropertiesService.getProperty(PROPERTY_PROXY_USERNAME);
    String strPassword = AppPropertiesService.getProperty(PROPERTY_PROXY_PASSWORD);
    String strDomainName = AppPropertiesService.getProperty(PROPERTY_DOMAIN_NAME);

    if (StringUtils.isNotBlank(strUserName) && StringUtils.isNotBlank(strPassword)) {
        // at least Userpasswordcredz
        Credentials creds;

        if (StringUtils.isBlank(strDomainName)) {
            creds = new UsernamePasswordCredentials(strUserName, strPassword);
        } else {
            creds = new NTCredentials(strUserName, strPassword, "", strDomainName);
        }

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        client.setCredentialsProvider(credsProvider);

        HttpHost proxy = new HttpHost(AppPropertiesService.getProperty(PROPERTY_PROXY_HOST),
                AppPropertiesService.getPropertyInt(PROPERTY_PROXY_PORT, 8080));
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return client;
}

From source file:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java

private HttpClient getHttpClient(URL url) {
    shutdownHttpClient();//from  w w  w  .  j a va  2  s . c  om
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST),
            new UsernamePasswordCredentials(DomainLifecycleUtil.SLAVE_HOST_USERNAME,
                    DomainLifecycleUtil.SLAVE_HOST_PASSWORD));

    httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();

    return httpClient;
}

From source file:com.helger.httpclient.HttpClientFactory.java

@Nullable
public CredentialsProvider createCredentialsProvider() {
    final HttpHost aProxyHost = getProxyHost();
    final Credentials aProxyCredentials = getProxyCredentials();
    if (aProxyHost != null && aProxyCredentials != null) {
        final CredentialsProvider aCredentialsProvider = new BasicCredentialsProvider();
        aCredentialsProvider.setCredentials(new AuthScope(aProxyHost), aProxyCredentials);
        return aCredentialsProvider;
    }//from   w w  w .  j  a va2s  .c  o  m
    return null;
}

From source file:aajavafx.CustomerMedicineController.java

public ObservableList<Customers> getCustomer() throws IOException, JSONException {

    ObservableList<Customers> customers = FXCollections.observableArrayList();
    Customers myCustomer = new Customers();
    Gson gson = new Gson();
    JSONObject jo = new JSONObject();
    // SSL update..........
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);

    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customers");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    //................

    //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(CustomersRootURL), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));

    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myCustomer = gson.fromJson(jo.toString(), Customers.class);
        customers.add(myCustomer);// w  w  w . j av a2 s  . c om

    }
    return customers;
}

From source file:aajavafx.CustomerMedicineController.java

public ObservableList<Medicines> getMedicines() throws IOException, JSONException {

    ObservableList<Medicines> medicines = FXCollections.observableArrayList();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    JSONObject jo = new JSONObject();

    //........SSL Update
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/medicines");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    //...................
    // JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineRootURL), Charset.forName("UTF-8")));
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));

    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        Medicines medicine = gson.fromJson(jo.toString(), Medicines.class);
        System.out.println("JSON OBJECT #" + i + " " + jo);
        medicines.add(medicine);//w w w.j a  v  a  2 s .c o  m

    }
    return medicines;
}