Example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider.

Prototype

public BasicCredentialsProvider() 

Source Link

Document

Default constructor.

Usage

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare asynchronous connection./*  w ww .j a v a 2  s  . co m*/
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException
 */
public void prepareAsyncConnection() throws EWSHttpException {
    try {
        //ssl config
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);
        builder.setSchemePortResolver(new DefaultSchemePortResolver());

        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger);
        builder.setSSLSocketFactory(factory);
        builder.setSslcontext(factory.getContext());

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials(getUserName(), getPassword(), "", getDomain()));
        builder.setDefaultCredentialsProvider(credsProvider);

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

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

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthSchemes.NTLM);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        //

        builder.setDefaultRequestConfig(rcBuilder.build());

        //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects
        //create the client and execute requests
        client = builder.build();
        httpPostReq = new HttpPost(getUrl().toString());
        response = client.execute(httpPostReq);
    } catch (IOException e) {
        client = null;
        httpPostReq = null;
        throw new EWSHttpException("Unable to open connection to " + this.getUrl());
    } catch (Exception e) {
        client = null;
        httpPostReq = null;
        e.printStackTrace();
        throw new EWSHttpException("SSL problem " + this.getUrl());
    }
}

From source file:com.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClient createHttpClient() {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(createConnectionManager())
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(graphiteConnectionRequestTimeout)
                    .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build());

    // Set auth header for graphite if username and password are provided
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        context.setAttribute("preemptive-auth", new BasicScheme());
        clientBuilder.addInterceptorFirst(new PreemptiveAuth());
    }// ww w. ja v a  2 s  . co  m

    return clientBuilder.build();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

/**
 * Define the Credentials// w  ww  .j av a 2 s  .co  m
 *
 * @param uri
 * @return {@code HttpClientBuilder}
 */
private HttpClientBuilder configCredentials(final URI uri) throws DSSException {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry : authenticationMap.entrySet()) {

        final HttpHost httpHost = entry.getKey();
        final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue();
        final AuthScope authscope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
        credentialsProvider.setCredentials(authscope, usernamePasswordCredentials);
    }
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpClientBuilder = configureProxy(httpClientBuilder, credentialsProvider, uri);
    return httpClientBuilder;
}

From source file:org.jboss.as.test.integration.management.extension.customcontext.testbase.CustomManagementContextTestBase.java

private static CloseableHttpClient createAuthenticatingClient(ManagementClient managementClient) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(managementClient.getMgmtAddress(), 9990),
            new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

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

From source file:org.jboss.as.test.integration.management.http.HttpDeploymentUploadUnitTestCase.java

private CloseableHttpClient createHttpClient() {
    try {//from w w  w.  j  a v a2  s.  c  o  m
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(managementClient.getMgmtAddress(), managementClient.getMgmtPort()),
                new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));
        return HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

/**
 * Create http client//w ww.java  2 s. com
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            if (props.getProperty("http.proxyUser") != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                        props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd")));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:aajavafx.CustomerMedicineController.java

@FXML
private void handleSaveButton(ActionEvent event) {
    //labelError.setText(null);
    try {/*from w  w  w  .j  a  va2 s.  c om*/

        String dosage = dose.getText();
        dose.clear();
        String stDate = startDate.getText();
        startDate.clear();
        String sched = schedule.getText();
        schedule.clear();
        Customers customer = (Customers) customerBox.getSelectionModel().getSelectedItem();
        Medicines medicine = (Medicines) medicinesBox.getSelectionModel().getSelectedItem();
        CustomersTakesMedicinesPK ctmPK = new CustomersTakesMedicinesPK(customer.getCuId(),
                medicine.getmedId());
        CustomersTakesMedicines ctm = new CustomersTakesMedicines(ctmPK, dosage, stDate,
                Double.parseDouble(sched));
        ctm.setCustomers(customer);
        ctm.setMedicines(medicine);
        //System.out.println(customerBox.getValue());
        //String string = (String)customerBox.getValue();
        //System.out.println("STRING VALUE: "+string);
        //int customerId = Integer.parseInt(""+string.charAt(0));
        //System.out.println("CUSTOMER ID VALUE:"+customerId);
        //Customers customer = getCustomerByID(customerId);

        Gson gson = new Gson();
        //......for ssl handshake....
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        //........
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
        if (startDate.isEditable()) { //then we are posting a new record
            HttpEntity = new HttpPost(MedicineCustomerRootURL); //so make a http post object
        } else { //we are editing a record 
            HttpEntity = new HttpPut(MedicineCustomerRootURL + startDate); //so make a http put object
        }

        String jsonString = new String(gson.toJson(ctm));
        System.out.println("json string: " + jsonString);
        StringEntity postString = new StringEntity(jsonString);

        HttpEntity.setEntity(postString);
        HttpEntity.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(HttpEntity);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 204) {
            System.out.println("Customer binded to medicine successfully");
        } else {
            System.out.println("Server error: " + response.getStatusLine());
        }
        dose.setEditable(false);
        startDate.setEditable(false);
        schedule.setEditable(false);
        customerBox.setDisable(true);

    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
    try {
        //refresh table
        tableCustomer.setItems(getCustomersTakesMedicines());
    } catch (IOException ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testKnox674SslCipherSuiteConfig() throws Exception {
    LOG_ENTER();/*from  w  ww.  j av a2 s  .c  o m*/

    String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml");
    FileUtils.writeStringToFile(topoFile, topoStr);

    topos.reloadTopologies();

    String username = "guest";
    String password = "guest-password";
    String serviceUrl = gatewayUrl + "/test-topology/api/v1/version";

    HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(
                    new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                            new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts()))
            .build();
    HttpGet request = new HttpGet(serviceUrl);
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();

    gateway.stop();
    config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }));
    config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }));

    startGatewayServer();
    serviceUrl = gatewayUrl + "/test-topology/api/v1/version";

    try {
        client = HttpClients.custom()
                .setSSLSocketFactory(
                        new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                                new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts()))
                .build();
        request = new HttpGet(serviceUrl);
        client.execute(request, context);
        fail("Expected SSLHandshakeException");
    } catch (SSLHandshakeException e) {
        // Expected.
        client.close();
    }

    client = HttpClients.custom()
            .setSSLSocketFactory(
                    new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" },
                            new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts()))
            .build();
    request = new HttpGet(serviceUrl);
    response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();

    LOG_EXIT();
}

From source file:com.thinkbiganalytics.metadata.rest.client.MetadataClient.java

/**
 * creates a credentials provider//from  ww w.j  a  v a 2 s. c o  m
 *
 * @param username the user name f
 * @param password the password
 * @return a credentials provider
 */
public static CredentialsProvider createCredentialProvider(String username, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    return credsProvider;
}