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:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public ConfluenceSession(String clientId, String clientSecret, String protocol, String host, int port,
        String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername,
        String proxyPassword) throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }/*from   w  ww .j a va  2  s .  c  o m*/

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:aajavafx.CustomerController.java

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

    ObservableList<CustomerProperty> customers = FXCollections.observableArrayList();
    //customers.add(new CustomerProperty(1, "Johny", "Walker", "London", "1972-07-01", "7207012222"));
    Customers myCustomer = new Customers();
    //Managers manager = new Managers();
    Gson gson = new Gson();
    ObservableList<CustomerProperty> customersProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();
    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(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);
        System.out.println(myCustomer.getCuId());
        customersProperty.add(new CustomerProperty(myCustomer.getCuId(), myCustomer.getCuFirstname(),
                myCustomer.getCuLastname(), myCustomer.getCuBirthdate(), myCustomer.getCuAddress(),
                myCustomer.getCuPersonnummer()));
    }//  w  w  w  . ja v  a  2s . com
    return customersProperty;
}

From source file:org.yamj.core.tools.web.PoolingHttpClientBuilder.java

@SuppressWarnings("resource")
public PoolingHttpClient build() {
    // create proxy
    HttpHost proxy = null;//  w w w . j  a va  2  s .co  m
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
    connManager.setMaxTotal(connectionsMaxTotal);
    connManager.setDefaultMaxPerRoute(connectionsMaxPerRoute);

    HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the client
    PoolingHttpClient wrapper = new PoolingHttpClient(builder.build(), connManager);
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}

From source file:org.apache.metron.stellar.dsl.functions.RestFunctionsTest.java

/**
 * The REST_GET function should set the proper credentials in the HttpClientContext.
 * @throws Exception/* w ww.j  av  a 2  s. c  om*/
 */
@Test
public void restGetShouldGetHttpClientContext() throws Exception {
    RestFunctions.RestGet restGet = new RestFunctions.RestGet();
    HttpHost target = new HttpHost("localhost", mockServerRule.getPort());
    HttpHost proxy = new HttpHost("localhost", proxyRule.getHttpPort());

    {
        RestConfig restConfig = new RestConfig();
        HttpClientContext actual = restGet.getHttpClientContext(restConfig, target, Optional.empty());

        assertNull(actual.getCredentialsProvider());
    }

    {
        RestConfig restConfig = new RestConfig();
        restConfig.put(BASIC_AUTH_USER, "user");
        restConfig.put(BASIC_AUTH_PASSWORD_PATH, basicAuthPasswordPath);

        HttpClientContext actual = restGet.getHttpClientContext(restConfig, target, Optional.empty());
        HttpClientContext expected = HttpClientContext.create();
        CredentialsProvider expectedCredentialsProvider = new BasicCredentialsProvider();
        expectedCredentialsProvider.setCredentials(new AuthScope(target),
                new UsernamePasswordCredentials(restConfig.getBasicAuthUser(), basicAuthPassword));
        expected.setCredentialsProvider(expectedCredentialsProvider);

        assertEquals(expected.getCredentialsProvider().getCredentials(new AuthScope(target)),
                actual.getCredentialsProvider().getCredentials(new AuthScope(target)));
        assertEquals(expected.getCredentialsProvider().getCredentials(new AuthScope(proxy)),
                actual.getCredentialsProvider().getCredentials(new AuthScope(proxy)));
    }

    {
        RestConfig restConfig = new RestConfig();
        restConfig.put(PROXY_BASIC_AUTH_USER, "proxyUser");
        restConfig.put(PROXY_BASIC_AUTH_PASSWORD_PATH, proxyBasicAuthPasswordPath);

        HttpClientContext actual = restGet.getHttpClientContext(restConfig, target, Optional.of(proxy));
        HttpClientContext expected = HttpClientContext.create();
        CredentialsProvider expectedCredentialsProvider = new BasicCredentialsProvider();
        expectedCredentialsProvider.setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(restConfig.getProxyBasicAuthUser(), proxyAuthPassword));
        expected.setCredentialsProvider(expectedCredentialsProvider);

        assertEquals(expected.getCredentialsProvider().getCredentials(new AuthScope(target)),
                actual.getCredentialsProvider().getCredentials(new AuthScope(target)));
        assertEquals(expected.getCredentialsProvider().getCredentials(new AuthScope(proxy)),
                actual.getCredentialsProvider().getCredentials(new AuthScope(proxy)));
    }

    {
        RestConfig restConfig = new RestConfig();
        restConfig.put(BASIC_AUTH_USER, "user");
        restConfig.put(BASIC_AUTH_PASSWORD_PATH, basicAuthPasswordPath);
        restConfig.put(PROXY_BASIC_AUTH_USER, "proxyUser");
        restConfig.put(PROXY_BASIC_AUTH_PASSWORD_PATH, proxyBasicAuthPasswordPath);

        HttpClientContext actual = restGet.getHttpClientContext(restConfig, target, Optional.of(proxy));
        HttpClientContext expected = HttpClientContext.create();
        CredentialsProvider expectedCredentialsProvider = new BasicCredentialsProvider();
        expectedCredentialsProvider.setCredentials(new AuthScope(target),
                new UsernamePasswordCredentials(restConfig.getBasicAuthUser(), basicAuthPassword));
        expectedCredentialsProvider.setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(restConfig.getProxyBasicAuthUser(), proxyAuthPassword));
        expected.setCredentialsProvider(expectedCredentialsProvider);

        assertEquals(expected.getCredentialsProvider().getCredentials(new AuthScope(target)),
                actual.getCredentialsProvider().getCredentials(new AuthScope(target)));
        assertEquals(expected.getCredentialsProvider().getCredentials(new AuthScope(proxy)),
                actual.getCredentialsProvider().getCredentials(new AuthScope(proxy)));
    }
}

From source file:com.rbmhtechnology.apidocserver.service.RepositoryService.java

@PostConstruct
void init() {//from ww  w . j  a v  a2 s  .c  o m
    ConstructDocumentationDownloadUrl cacheLoader = new ConstructDocumentationDownloadUrl();
    SnapshotRemovalListener removalListener = new SnapshotRemovalListener();
    // snapshots will expire 30 minutes after their last construction (same for all)
    snapshotDownloadUrlCache = CacheBuilder.newBuilder().maximumSize(1000)
            .expireAfterWrite(snapshotsCacheTimeoutSeconds, TimeUnit.SECONDS).removalListener(removalListener)
            .build(cacheLoader);
    latestVersionCache = CacheBuilder.newBuilder().maximumSize(1000)
            .expireAfterWrite(snapshotsCacheTimeoutSeconds, TimeUnit.SECONDS)
            .build(new MavenXmlVersionRefResolver(MavenVersionRef.LATEST));

    releaseDownloadUrlCache = CacheBuilder.newBuilder().maximumSize(1000).build(cacheLoader);
    releaseVersionCache = CacheBuilder.newBuilder().maximumSize(1000)
            .build(new MavenXmlVersionRefResolver(RELEASE));

    if (localJarStorage == null) {
        localJarStorage = Files.createTempDir();
    }

    // http client
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (!StringUtils.isEmpty(repositoryUser) && !StringUtils.isEmpty(repositoryPassword)) {
        credsProvider.setCredentials(new AuthScope(repositoryUrl.getHost(), repositoryUrl.getPort()),
                new UsernamePasswordCredentials(repositoryUser, repositoryPassword));
    }
    httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static void doDelete(String hostname, String port, String url, String user, String password) {

    try {/*w ww  . j  a va 2 s  .  c om*/

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            String postUrl = "http://" + hostname + ":" + port + url;
            logger.debug("Deleting request as " + user + " with password " + password + " to " + postUrl);
            HttpDelete request = new HttpDelete(postUrl);
            httpClient.execute(target, request, localContext);

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {
        logger.error(e.getMessage());
    }

}

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;//  w  w w  . ja va2s  . c  om
}

From source file:aajavafx.CustomerController.java

@FXML
private void handleRegisterButton(ActionEvent event) {
    //labelError.setText(null);
    try {/*w  ww.java2s .  c o  m*/
        //String customerNumber = customerID.getText();
        //customerID.clear();
        String lastName = lastNameID.getText();
        lastNameID.clear();
        String firstName = firstNameID.getText();
        firstNameID.clear();
        String address = addressID.getText();
        addressID.clear();
        String birthdate = birthdateID.getText();
        birthdateID.clear();
        String persunnumer = persunnumerID.getText();
        persunnumerID.clear();
        try {
            Gson gson = new Gson();
            Customers customer = new Customers(1, firstName, lastName, address, birthdate, persunnumer);
            String jsonString = new String(gson.toJson(customer));
            System.out.println("json string: " + jsonString);
            StringEntity postString = new StringEntity(jsonString);
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
            HttpPost post = new HttpPost(postCustomerURL);
            post.setEntity(postString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            if (response != null) {
                response.getEntity().writeTo(outstream);
                byte[] responseBody = outstream.toByteArray();
                String str = new String(responseBody, "UTF-8");
                System.out.print(str);
            } else {
                System.out.println("Success");
            }
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex);
        } catch (IOException e) {
            System.out.println(e);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        // labelError.setText("Salary or phone field does not have a integer!");
    }
}

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

private void configureAuthentication(CredentialsProvider provider, final String scheme,
        final Principal principal) {
    provider.setCredentials(new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, scheme), new Credentials() {
        public Principal getUserPrincipal() {
            return principal;
        }//from   w  w w.j  av a2s  .c  o  m

        public String getPassword() {
            return password;
        }
    });
}