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:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionMergeSource.java

private Requisition getRequisition(String url, String userName, String password) {
    Requisition requisition = null;/*from   ww  w .ja  va 2  s .  c  o  m*/

    if (url != null) {
        try {
            HttpClientBuilder builder = HttpClientBuilder.create();

            // If username and password was found, inject the credentials
            if (userName != null && password != null) {

                CredentialsProvider provider = new BasicCredentialsProvider();

                // Create the authentication scope
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

                // Create credential pair
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);

                // Inject the credentials
                provider.setCredentials(scope, credentials);

                // Set the default credentials provider
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            try {

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader);

            } catch (JAXBException e) {
                LOGGER.error("The response did not contain a valid requisition as xml.", e);
            }
            LOGGER.debug("Got Requisition {}", requisition);
        } catch (IOException ex) {
            LOGGER.error("Requesting requisition from {} failed", url, ex);
            return null;
        }
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
        return null;
    }
    return requisition;
}

From source file:org.alfresco.tutorials.webscripts.HelloWorldWebScriptIT.java

@Test
public void testWebScriptCall() throws Exception {
    String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld";
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 8080),
            new UsernamePasswordCredentials(ALFRESCO_USERNAME, ALFRESCO_PWD));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    try {/*w w w  . ja v a  2  s  .com*/
        HttpGet httpget = new HttpGet(webscriptURL);
        HttpResponse httpResponse = httpclient.execute(httpget);
        assertEquals("HTTP Response Status is not OK(200)", HttpStatus.SC_OK,
                httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity = httpResponse.getEntity();
        assertNotNull("Response from Web Script is null", entity);
        String response = EntityUtils.toString(entity);
        JSONParser parser = new JSONParser();
        JSONObject jsonResponseObj = (JSONObject) parser.parse(response);
        assertTrue("Folder not found", (boolean) jsonResponseObj.get("foundFolder"));
        assertTrue("Doc not found", (boolean) jsonResponseObj.get("foundDoc"));
    } finally {
        httpclient.close();
    }
}

From source file:multichain.command.builders.QueryBuilderCommon.java

protected void initialize(String ip, String port, String login, String password,
        RuntimeParameters queryParameter) {
    httppost = new HttpPost("http://" + ip + ":" + port);

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(login, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    queryParameters = queryParameter;//from www .ja va  2 s  .  c  om

    httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

}

From source file:org.thingsboard.server.dao.audit.sink.ElasticsearchAuditLogSink.java

@PostConstruct
public void init() {
    try {/*from  www .  ja  v  a 2 s .  c  o m*/
        log.trace("Adding elastic rest endpoint... host [{}], port [{}], scheme name [{}]", host, port,
                schemeName);
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, schemeName));

        if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
            log.trace("...using username [{}] and password ***", userName);
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(userName, password));
            builder.setHttpClientConfigCallback(
                    httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }

        this.restClient = builder.build();
    } catch (Exception e) {
        log.error("Sink init failed!", e);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*  ww w  .j av  a 2  s  .  c  o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}

From source file:org.commonjava.indy.httprox.AbstractHttproxFunctionalTest.java

protected CloseableHttpClient proxiedHttp(final String user, final String pass, SSLSocketFactory socketFactory)
        throws Exception {
    CredentialsProvider creds = null;/* ww  w .  j  a  v  a2 s .co m*/

    if (user != null) {
        creds = new BasicCredentialsProvider();
        creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
    }

    HttpHost proxy = new HttpHost(HOST, proxyPort);

    final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(proxy);
    HttpClientBuilder builder = HttpClients.custom().setRoutePlanner(planner)
            .setDefaultCredentialsProvider(creds).setProxy(proxy).setSSLSocketFactory(socketFactory);

    return builder.build();
}

From source file:org.apache.metamodel.elasticsearch.rest.ElasticSearchRestDataContextFactory.java

private ElasticSearchRestClient createClient(final DataContextProperties properties)
        throws MalformedURLException {
    final URL url = new URL(properties.getUrl());
    final RestClientBuilder builder = RestClient.builder(new HttpHost(url.getHost(), url.getPort()));

    if (properties.getUsername() != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword()));

        builder.setHttpClientConfigCallback(
                httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }/*from w  w w.  j a v  a  2 s . com*/

    return new ElasticSearchRestClient(builder.build());
}

From source file:io.bosh.client.SpringDirectorClientBuilder.java

private ClientHttpRequestFactory createRequestFactory(String host, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
            new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = null;
    try {//from  w  w w .j av  a2 s .c  o m
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
                .build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new DirectorException("Unable to configure ClientHttpRequestFactory", e);
    }

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    // disabling redirect handling is critical for the way BOSH uses 302's
    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();

    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java

public synchronized HttpClient getNativeHttpClient() {
    if (myHttpClient == null) {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(getPoolMaxTotal());
        connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectTimeout())
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true)
                .setProxy(myProxy).build();

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement();

        if (myProxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credsProvider);
        }//from  w  ww.  ja va 2s  .c  o  m

        myHttpClient = builder.build();
        // @formatter:on

    }

    return myHttpClient;
}

From source file:org.apache.cloudstack.cloudian.client.CloudianClient.java

public CloudianClient(final String host, final Integer port, final String scheme, final String username,
        final String password, final boolean validateSSlCertificate, final int timeout)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    final HttpHost adminHost = new HttpHost(host, port, scheme);
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(adminHost, new BasicScheme());

    this.adminApiUrl = adminHost.toURI();
    this.httpContext = HttpClientContext.create();
    this.httpContext.setCredentialsProvider(provider);
    this.httpContext.setAuthCache(authCache);

    final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
            .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();

    if (!validateSSlCertificate) {
        final SSLContext sslcontext = SSLUtils.getSSLContext();
        sslcontext.init(null, new X509TrustManager[] { new TrustAllManager() }, new SecureRandom());
        final SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
    } else {/*from   www . ja  v a  2 s .  com*/
        this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config).build();
    }
}