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.appenders.log4j2.elasticsearch.jest.BasicCredentials.java

@Override
public void applyTo(HttpClientConfig.Builder builder) {

    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    builder.credentialsProvider(basicCredentialsProvider);

}

From source file:org.kaaproject.kaa.server.common.admin.HttpComponentsRequestFactoryBasicAuth.java

/**
 * Create new instance of <code>HttpComponentsRequestFactoryBasicAuth</code>.
 *
 * @param host the http host/*from   ww  w .  j a  va 2  s .  co m*/
 */
public HttpComponentsRequestFactoryBasicAuth(HttpHost host) {
    super(createHttpClient());
    this.host = host;
    credsProvider = new BasicCredentialsProvider();
    this.setConnectTimeout(60000);
    this.setReadTimeout(0);
}

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

protected HttpClientContext proxyContext(final String user, final String pass) {
    final CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setCredentialsProvider(creds);//w ww  . j a  v  a2  s.c o  m

    return ctx;
}

From source file:org.trustedanalytics.servicebroker.hdfs.config.hgm.HgmHttpsConfiguration.java

@Bean
@Qualifier("hgmRestTemplate")
public RestTemplate getHgmHttpsRestTemplate()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();/*  w  ww. jav  a2 s. com*/
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));

    HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(connectionFactory)
            .setDefaultCredentialsProvider(credentialsProvider).build();

    ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(requestFactory);
}

From source file:com.temenos.useragent.generic.http.DefaultHttpClientHelper.java

/**
 * Builds and returns the basic authentication provider.
 * //from ww  w. j av a 2 s  .c  o m
 * @return
 */
public static CredentialsProvider getBasicCredentialProvider() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    ConnectionConfig config = ContextFactory.get().getContext().connectionCongfig();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            config.getValue(ConnectionConfig.USER_NAME), config.getValue(ConnectionConfig.PASS_WORD)));
    return credentialsProvider;
}

From source file:com.quartzdesk.executor.core.job.UrlInvokerJob.java

@Override
protected void executeJob(final JobExecutionContext context) throws JobExecutionException {
    log.debug("Inside job: {}", context.getJobDetail().getKey());
    JobDataMap jobDataMap = context.getMergedJobDataMap();

    // url (required)
    final String url = jobDataMap.getString(JDM_KEY_URL);
    if (url == null) {
        throw new JobExecutionException("Missing required '" + JDM_KEY_URL + "' job data map parameter.");
    }/*from   w  ww .  j ava 2  s  .  c om*/

    // username (optional)
    String username = jobDataMap.getString(JDM_KEY_USERNAME);
    // password (optional)
    String password = jobDataMap.getString(JDM_KEY_PASSWORD);

    CloseableHttpClient httpClient;
    if (username != null && password != null) {
        // use HTTP basic authentication
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    } else {
        // use no HTTP authentication
        httpClient = HttpClients.custom().build();
    }

    try {
        HttpPost httpPost = new HttpPost(url);

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse) throws IOException {
                int status = httpResponse.getStatusLine().getStatusCode();

                //context.setResult( Integer.toString( status ) );

                if (status >= 200 && status < 300) {
                    HttpEntity entity = httpResponse.getEntity();
                    return entity == null ? null : EntityUtils.toString(entity);
                } else {
                    throw new ClientProtocolException(
                            "URL: " + url + " returned unexpected response status code: " + status);
                }
            }
        };

        log.debug("HTTP request line: {}", httpPost.getRequestLine());

        log.info("Invoking target URL: {}", url);
        String responseText = httpClient.execute(httpPost, responseHandler);

        log.debug("Response text: {}", responseText);

        if (!responseText.trim().isEmpty()) {
            /*
             * We use the HTTP response text as the Quartz job execution result. This code can then be easily
             * viewed in the Execution History in the QuartzDesk GUI and it can be, for example, used to trigger
             * execution notifications.
             */
            context.setResult(responseText);
        }

    } catch (IOException e) {
        throw new JobExecutionException("Error invoking URL: " + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            log.error("Error closing HTTP client.", e);
        }
    }
}

From source file:org.fcrepo.camel.FedoraClient.java

/**
 * Create a FedoraClient with a set of authentication values.
 *///  ww  w  .ja v a 2 s  .  c om
public FedoraClient(final String username, final String password, final String host,
        final Boolean throwExceptionOnFailure) {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = null;

    this.throwExceptionOnFailure = throwExceptionOnFailure;

    if ((username == null || username.isEmpty()) || (password == null || password.isEmpty())) {
        this.httpclient = HttpClients.createDefault();
    } else {
        if (host != null) {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        this.httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
}

From source file:org.nekorp.workflow.desktop.rest.util.RestTemplateFactory.java

@PostConstruct
public void init() {
    targetHost = new HttpHost(host, port, protocol);
    //connectionPool = new PoolingHttpClientConnectionManager();
    //connectionPool.setDefaultMaxPerRoute(10);
    //connectionPool.setMaxTotal(20);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    //wildcard ssl certificate
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            //.setConnectionManager(connectionPool)
            .setSSLSocketFactory(sslsf).build();
    // 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(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth(
            httpclient, localContext);/*from  w  ww  .j  av a2s .co m*/
    this.template = new RestTemplate();
    template.getMessageConverters().add(new BufferedImageHttpMessageConverter());
    template.setRequestFactory(factory);
}

From source file:org.dmfs.android.authenticator.handlers.BasicHttpClientAuthenticationHandler.java

@Override
public void authenticate(AbstractHttpClient client) {
    // just set the credentials assuming that proper authentication schemes are registered with the AbstractHttpClient.
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, mAuthToken.getRealm()),
            new UsernamePasswordCredentials(mAuthToken.getUsername(), mAuthToken.getPassword()));

    client.setCredentialsProvider(credsProvider);
}

From source file:com.apm4all.tracy.TracyAsyncHttpClientPublisher.java

TracyAsyncHttpClientPublisher(String hostname, int port, boolean waitForResponse, String resourcePath,
        HttpProxyConfig httpProxyConfig, boolean debug) {
    this.uri = "http://" + hostname + ":" + port + "/" + resourcePath;
    this.waitForResponse = waitForResponse;
    this.httpProxyConfig = httpProxyConfig;
    this.debug = debug;
    if (httpProxyConfig.isEnabled()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(httpProxyConfig.getHost(), httpProxyConfig.getPort()),
                new UsernamePasswordCredentials(httpProxyConfig.getUsername(), httpProxyConfig.getPassword()));
        this.httpClient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    } else {//from   w ww .j a  va  2 s. c  o  m
        this.httpClient = HttpAsyncClients.custom().build();
    }
    this.httpClient.start();
}