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.ksc.http.apache.utils.ApacheUtils.java

/**
 * Returns a new Credentials Provider for use with proxy authentication.
 *//*from w ww  .  j a v  a2  s .  c  om*/
public static CredentialsProvider newProxyCredentialsProvider(HttpClientSettings settings) {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(newAuthScope(settings), newNTCredentials(settings));
    return provider;
}

From source file:io.fabric8.maven.support.Apps.java

/**
 * Posts a file to the git repository/*from w w w .j  a  va  2 s.c  o  m*/
 */
public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl,
        String branch, String path, Logger logger) throws URISyntaxException, IOException {
    HttpClientBuilder builder = HttpClients.custom();
    if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443),
                new UsernamePasswordCredentials(user, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }

    CloseableHttpClient client = builder.build();
    try {

        String url = consoleUrl;
        if (!url.endsWith("/")) {
            url += "/";
        }
        url += "git/";
        url += branch;
        if (!path.startsWith("/")) {
            url += "/";
        }
        url += path;

        logger.info("Posting App Zip " + file.getName() + " to " + url);
        URI buildUrl = new URI(url);
        HttpPost post = new HttpPost(buildUrl);

        // use multi part entity format
        FileBody zip = new FileBody(file);
        HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build();
        post.setEntity(entity);
        // post.setEntity(new FileEntity(file));

        HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post);
        logger.info("Response: " + response);
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 200 || statusCode >= 300) {
                throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response);
            }
        }
        return response;
    } finally {
        Closeables.closeQuietly(client);
    }
}

From source file:eu.esdihumboldt.util.http.client.ClientProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * //from   ww  w  .  j a v a  2s  . c o m
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    ProxyUtil.init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    createCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:com.github.caldav4j.BaseTestCase.java

public static HttpClient createHttpClient(CaldavCredential caldavCredential) {
    // HttpClient 4 requires a Cred providers, to be added during creation of client
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(caldavCredential.user, caldavCredential.password));

    return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.fcrepo.camel.ldpath.ClientFactory.java

/**
 * Create a linked data client suitable for use with a Fedora Repository.
 * @param authScope the authentication scope
 * @param credentials the credentials//from www.  j av a 2s.  c o  m
 * @param endpoints additional endpoints to enable on the client
 * @param providers additional providers to enable on the client
 * @return a configuration for use with an LDClient
 */
public static ClientConfiguration createClient(final AuthScope authScope, final Credentials credentials,
        final List<Endpoint> endpoints, final List<DataProvider> providers) {

    final ClientConfiguration client = new ClientConfiguration();

    if (credentials != null && authScope != null) {
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);
        client.setHttpClient(HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .useSystemProperties().build());
    }

    // manually add default Providers and Endpoints
    client.addProvider(new LinkedDataProvider());
    client.addProvider(new CacheProvider());
    client.addProvider(new RegexUriProvider());
    client.addProvider(new SPARQLProvider());
    client.addEndpoint(new LinkedDataEndpoint());

    // add any injected endpoints/providers
    endpoints.forEach(client::addEndpoint);
    providers.forEach(client::addProvider);

    return client;
}

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);/*from   ww  w.  j a va2  s. co  m*/

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}

From source file:com.kms.core.io.HttpUtil_In.java

public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) {
    CloseableHttpClient httpclient;/*from w  ww.  j av  a  2  s.  c  o m*/

    // Auth Scheme 
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    // NTLM  
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080),
            new NTCredentials(SoeID, Password, "dummy", "APAC"));
    //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" ));

    // ------------- cookie start ------------------------
    // Auction   
    // Create a local instance of cookie store
    final CookieStore cookieStore = new BasicCookieStore();

    //       Cookie  .
    final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES");
    cookie.setVersion(0);
    cookie.setDomain(".scourt.go.kr");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    // ------------- cookie end ------------------------

    if (type == 0) // TYPE.AuctionInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else // SagunInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build();
    }

    return httpclient;
}

From source file:org.pentaho.di.core.util.HttpClientUtil.java

/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host/*from  www  .j a v a  2  s .c  o  m*/
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication(String host, int port, String user,
        String password, String schema) {
    HttpClientContext localContext = null;
    try {
        HttpHost target = new HttpHost(host, port, schema);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
    } catch (Exception e) {
        return null;
    }
    return localContext;
}

From source file:nl.esciencecenter.octopus.webservice.JobLauncherService.java

/**
 * Adds MAC Access Authentication scheme to http client and registers list of MAC credentials with http client.
 *
 * Http client will use MAC Access Authentication when url is in scope of given MAC credentials.
 *
 * @param httpClient/*from w  w w  .ja v  a  2s. c  o  m*/
 * @param macs
 * @return httpClient with MAC access authentication and credentials injected.
 */
public static AbstractHttpClient macifyHttpClient(AbstractHttpClient httpClient,
        ImmutableList<MacCredential> macs) {

    // Add MAC scheme
    httpClient.getAuthSchemes().register(MacScheme.SCHEME_NAME, new MacSchemeFactory());

    // Add configured MAC id/key pairs.
    CredentialsProvider credentialProvider = httpClient.getCredentialsProvider();
    for (MacCredential mac : macs) {
        credentialProvider.setCredentials(mac.getAuthScope(), mac);
    }

    // Add MAC scheme to ordered list of supported authentication schemes
    // See HTTP authentication parameters chapter on
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authSchemes);

    return httpClient;
}

From source file:com.ibm.CloudResourceBundle.java

private static Rows getServerResponse(CloudDataConnection connect) throws Exception {
    Rows rows = null;//from  www. j  av  a2 s  .  c  om

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("provide.castiron.com", 443),
            new UsernamePasswordCredentials(connect.getUserid(), connect.getPassword()));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    try {
        // Call the service and get all the strings for all the languages
        HttpGet httpget = new HttpGet(connect.getURL());
        httpget.addHeader("API_SECRET", connect.getSecret());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            InputStream in = response.getEntity().getContent();
            ObjectMapper mapper = new ObjectMapper();
            rows = mapper.readValue(new InputStreamReader(in, "UTF-8"), Rows.class);
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return rows;
}