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:de.avanux.smartapplianceenabler.appliance.HttpTransactionExecutor.java

/**
 * Send a HTTP request whose response has to be closed by the caller!
 * @param url/*w ww  .  j a  v  a 2 s  .  c om*/
 * @return
 */
protected CloseableHttpResponse sendHttpRequest(String url, String data, ContentType contentType,
        String username, String password) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (username != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    CloseableHttpClient client = httpClientBuilder.build();
    logger.debug("Sending HTTP request");
    logger.debug("url=" + url);
    logger.debug("data=" + data);
    logger.debug("contentType=" + contentType);
    logger.debug("username=" + username);
    logger.debug("password=" + password);
    try {
        HttpRequestBase request = null;
        if (data != null) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(data, contentType));
        } else {
            request = new HttpGet(url);
        }
        CloseableHttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("Response code is " + responseCode);
        return response;
    } catch (IOException e) {
        logger.error("Error executing HTTP request.", e);
        return null;
    }
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected void setup(String key, String domain) {
    this.domain = domain;
    this.key = key;
    host = new HttpHost(domain + ".chargify.com", 443, "https");

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(key, "x");
    credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(domain + ".chargify.com", 443, "ChargifyAdapter API"), creds);

    // todo preemtive and cache autentication
    //        client.getParams().setAuthenticationPreemptive(true);
    //        org.apache.http.client.AuthCache authCache = new BasicAuthCache();
    //        // Generate BASIC scheme object and add it to the local auth cache
    //        BasicScheme basicAuth = new BasicScheme();
    //        authCache.put("chargify.com", basicAuth);

    if (logger.isDebugEnabled())
        logger.debug("ChargifyAdapter client created for domain " + domain);
}

From source file:com.icoin.trading.bitcoin.client.BitcoinClientDefaultConfig.java

private CredentialsProvider credentialsProvicer() {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, Integer.valueOf(port)),
            new UsernamePasswordCredentials(user, password));
    return credsProvider;
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

public CredentialsProvider build() {
    // Create credentials provider for BASIC auth
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    addProxyCredentials(credsProvider);/*from ww w. jav a 2 s . co  m*/
    addTaxiiCredentials(credsProvider);
    return credsProvider;
}

From source file:org.hawkular.client.core.jaxrs.RestFactory.java

public T createAPI(ClientInfo clientInfo) {
    final HttpClient httpclient;
    if (clientInfo.getEndpointUri().toString().startsWith("https")) {
        httpclient = getHttpClient();/*from w ww  .  j  a v  a 2  s.  c  o  m*/
    } else {
        httpclient = HttpClientBuilder.create().build();
    }
    final ResteasyClient client;
    if (clientInfo.getUsername().isPresent() && clientInfo.getPassword().isPresent()) {
        HttpHost targetHost = new HttpHost(clientInfo.getEndpointUri().getHost(),
                clientInfo.getEndpointUri().getPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(clientInfo.getUsername().get(),
                        clientInfo.getPassword().get()));
        // 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 context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    } else {
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient());
        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }

    client.register(JacksonJaxbJsonProvider.class);
    client.register(JacksonObjectMapperProvider.class);
    client.register(RequestLoggingFilter.class);
    client.register(new RequestHeadersFilter(clientInfo.getHeaders()));
    client.register(ResponseLoggingFilter.class);
    client.register(HCJacksonJson2Provider.class);
    client.register(ConvertersProvider.class);

    ProxyBuilder<T> proxyBuilder = client.target(clientInfo.getEndpointUri()).proxyBuilder(apiClassType);
    if (classLoader != null) {
        proxyBuilder = proxyBuilder.classloader(classLoader);
    }
    return proxyBuilder.build();
}

From source file:com.gsma.mobileconnect.utils.RestClient.java

/**
 * Build a HttpClientContext that will preemptively authenticate using Basic Authentication
 *
 * @param username Username for credentials
 * @param password Password for credentials
 * @param uriForRealm uri used to determine the authentication realm
 * @return A HttpClientContext that will preemptively authenticate using Basic Authentication
 *//* w  w w . j a  v  a 2  s.  c o m*/
public HttpClientContext getHttpClientContext(String username, String password, URI uriForRealm) {
    String host = URIUtils.extractHost(uriForRealm).getHostName();
    int port = uriForRealm.getPort();
    if (port == -1) {
        if (Constants.HTTP_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) {
            port = Constants.HTTP_PORT;
        } else if (Constants.HTTPS_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) {
            port = Constants.HTTPS_PORT;
        }
    }

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost(host, port, uriForRealm.getScheme()), new BasicScheme());

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

    return context;
}

From source file:org.apache.jena.fuseki.embedded.TestFusekiTestAuth.java

@Test(expected = HttpException.class)
public void testServer_auth_bad_user() {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials("USERUSER", PASSWORD);
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) {
    } catch (HttpException ex) {
        throw assertAuthHttpException(ex);
    }/*from w w w  .ja  v a  2  s.  c om*/
}

From source file:aajavafx.LoginController.java

public static String getPassword(String userName) throws MalformedURLException, JSONException, IOException {
    String password = "";

    Managers manager = new Managers();
    Managers myManager = new Managers();
    Gson gson = new Gson();

    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ADMIN", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/managers/username/" + userName);

    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);
        manager = gson.fromJson(jo.toString(), Managers.class);
        if (manager.getManUsername().equals(userName)) {
            password = manager.getManPassword();
        }/*ww w  .j  av  a2  s.c o  m*/

        System.out.println(password);

    }
    return password;
}