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.zaizi.alfresco.publishing.marklogic.MarkLogicPublishingHelper.java

/**
 * Build a httpContext from channel properties.
 *
 * @param channelProperties the channel properties
 * @return the http context from channel properties
 *///from w  w w .  j a  v  a2  s. c  om
public HttpContext getHttpContextFromChannelProperties(final Map<QName, Serializable> channelProperties) {

    String markLogicUsername = (String) encryptor.decrypt(PublishingModel.PROP_CHANNEL_USERNAME,
            channelProperties.get(PublishingModel.PROP_CHANNEL_USERNAME));
    String markLogicPassword = (String) encryptor.decrypt(PublishingModel.PROP_CHANNEL_PASSWORD,
            channelProperties.get(PublishingModel.PROP_CHANNEL_PASSWORD));

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(markLogicUsername, markLogicPassword);
    HttpContext context = new BasicHttpContext();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, creds);
    context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    return context;
}

From source file:org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory.java

private SolrHttpClientBuilder initHttpClientBuilder(SolrHttpClientBuilder builder) {
    final String basicAuthUser = defaultParams.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = defaultParams.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);
    if (basicAuthUser == null || basicAuthPass == null) {
        throw new IllegalArgumentException(
                "username & password must be specified with " + getClass().getName());
    }/*from   w  w  w.  j a v  a  2  s .  com*/

    builder.setDefaultCredentialsProvider(new CredentialsProviderProvider() {
        @Override
        public CredentialsProvider getCredentialsProvider() {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
            return credsProvider;
        }
    });

    HttpClientUtil.addRequestInterceptor(requestInterceptor);
    return builder;
}

From source file:org.uberfire.provisioning.wildfly.runtime.provider.extras.Wildfly10RemoteClient.java

public int deploy(String user, String password, String host, int port, String filePath) {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + port + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    File file = new File(filePath);
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {/*  w w w . ja  va2 s .co  m*/
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    //entity.writeTo(System.out);
    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);

        out.println(">>> Deploying Response Entity: " + response.getEntity());
        out.println(">>> Deploying Response Satus: " + response.getStatusLine().getStatusCode());
        return response.getStatusLine().getStatusCode();
    } catch (IOException ex) {
        ex.printStackTrace();
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }
    return -1;
}

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

@Before
public void before() throws Exception {

    this.url = new URL("http", managementClient.getMgmtAddress(), MGMT_PORT, MGMT_CTX);
    this.httpContext = new BasicHttpContext();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

    this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.openehealth.ipf.commons.ihe.fhir.SslAwareApacheRestfulClientFactory.java

protected synchronized HttpClient getNativeHttpClient() {
    if (httpClient == null) {

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

        HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
                .setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(getPoolMaxTotal())
                .setMaxConnPerRoute(getPoolMaxPerRoute()).setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .disableCookieManagement();

        if (securityInformation != null) {
            securityInformation.configureHttpClientBuilder(builder);
        }//from   w w w. j  av  a2s  .  c  o  m

        // Need to authenticate against proxy
        if (proxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        httpClient = builder.build();
    }

    return httpClient;
}

From source file:com.restfiddle.handler.http.auth.BasicAuthHandler.java

/**
 * TODO : Not used anywhere right now./*from   w w w .  java2s .  c o  m*/
 */
public CredentialsProvider prepareBasicAuth(String userName, String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, userName);
    provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials);

    return provider;
}

From source file:org.zalando.stups.tokens.CloseableHttpProvider.java

public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {
    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;
    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

    host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme());

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/*  w  ww.j  a  v a2 s .com*/

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}

From source file:edu.cornell.mannlib.vitro.webapp.rdfservice.impl.virtuoso.RDFServiceVirtuoso.java

/**
 * We need an HttpContext that will provide username and password in
 * response to a basic authentication challenge.
 *///  w ww  .  j a v a2  s  .  c o  m
private HttpContext createHttpContext() {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.CREDS_PROVIDER, provider);
    return context;
}

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);/*from w ww. ja  v a  2 s.  c om*/

    return ctx;
}

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 w w . j av  a 2 s  .co  m*/
    this.template = new RestTemplate();
    template.getMessageConverters().add(new BufferedImageHttpMessageConverter());
    template.setRequestFactory(factory);
}