Example usage for org.apache.http.impl.auth BasicScheme BasicScheme

List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme BasicScheme.

Prototype

public BasicScheme() 

Source Link

Usage

From source file:org.apache.reef.runtime.hdinsight.client.yarnrest.HDInsightInstance.java

private HttpClientContext getClientContext(final String hostname, final String username, final String password)
        throws IOException {
    final HttpHost targetHost = new HttpHost(hostname, 443, "https");
    final HttpClientContext result = HttpClientContext.create();

    // Setup credentials provider
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    result.setCredentialsProvider(credentialsProvider);

    // Setup preemptive authentication
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    result.setAuthCache(authCache);//  ww w.  j  a  v  a2 s.  c  o  m
    final HttpGet httpget = new HttpGet("/");

    // Prime the cache
    try (final CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) {
        // empty try block used to automatically close resources
    }
    return result;
}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

private static void authenticate(String username, String password, HttpUriRequest request,
        HttpContext preemptiveContext) {
    try {/*from  w w  w. ja v  a 2  s  .  c  om*/
        BasicScheme basicScheme = new BasicScheme();
        Header authenticateHeader = basicScheme
                .authenticate(new UsernamePasswordCredentials(username, password), request, preemptiveContext);
        request.addHeader(authenticateHeader);
    } catch (AuthenticationException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:gov.nrel.bacnet.consumer.DatabusSender.java

BasicHttpContext setupPreEmptiveBasicAuth(DefaultHttpClient httpclient) {
    HttpHost targetHost = new HttpHost(host, port, mode);
    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, key));

    // 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
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return localcontext;
}

From source file:org.jspringbot.keyword.http.HTTPHelper.java

/**
 * Set Basic Authentication//from   w ww  . j a v a 2 s .  c o  m
 * @param username
 * @param password
 */
public void setBasicAuthentication(String username, String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    client.getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);

    // 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);

    LOG.createAppender().appendBold("Set Basic Authentication:").appendProperty("Username", username)
            .appendProperty("Password", password).log();

    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:com.rightscale.provider.rest.DashboardSession.java

private HttpRequestInterceptor createBasicAuthInterceptor() {
    return new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }/*from   w w  w . j  a v a2s.co m*/
            }
        }
    };
}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // 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(httpHost, basicAuth);/*from  ww w .j a v  a2s. c  o  m*/

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }

}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String getDataFromDHISEndpoint(String endpoint) {
    String url = Context.getAdministrationService().getGlobalProperty("dhisconnector.url");
    String user = Context.getAdministrationService().getGlobalProperty("dhisconnector.user");
    String pass = Context.getAdministrationService().getGlobalProperty("dhisconnector.pass");

    DefaultHttpClient client = null;//from w w  w . j a v  a2 s . co  m
    String payload = "";

    try {
        URL dhisURL = new URL(url);

        String host = dhisURL.getHost();
        int port = dhisURL.getPort();

        HttpHost targetHost = new HttpHost(host, port, dhisURL.getProtocol());
        client = new DefaultHttpClient();
        BasicHttpContext localcontext = new BasicHttpContext();

        HttpGet httpGet = new HttpGet(dhisURL.getPath() + endpoint);
        Credentials creds = new UsernamePasswordCredentials(user, pass);
        Header bs = new BasicScheme().authenticate(creds, httpGet, localcontext);
        httpGet.addHeader("Authorization", bs.getValue());
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Accept", "application/json");
        HttpResponse response = client.execute(targetHost, httpGet, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null && response.getStatusLine().getStatusCode() == 200) {
            payload = EntityUtils.toString(entity);

            saveToBackUp(endpoint, payload);
        } else {
            payload = getFromBackUp(endpoint);
        }
    } catch (Exception ex) {
        ex.printStackTrace();

        payload = getFromBackUp(endpoint);
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }

    return payload;
}

From source file:pl.llp.aircasting.util.http.HttpBuilder.java

private HttpRequestInterceptor preemptiveAuth() {
    return new HttpRequestInterceptor() {
        @Override//from   w ww.j a  v a2 s  .c o m
        public void process(HttpRequest httpRequest, HttpContext httpContext)
                throws HttpException, IOException {
            AuthState authState = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);

            Credentials credentials;
            if (useLogin) {
                credentials = new UsernamePasswordCredentials(login, password);
            } else {
                credentials = new UsernamePasswordCredentials(settingsHelper.getAuthToken(), "X");
            }

            authState.setAuthScope(AuthScope.ANY);
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(credentials);
        }
    };
}

From source file:org.cleverbus.core.common.ws.transport.http.CloseableHttpComponentsMessageSender.java

/**
 * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections
 * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows:
 * <p/>// ww w .  ja  va 2  s .c o m
 * <pre>
 * https://esb.cleverbus.org/esb/=1
 * http://esb.cleverbus.org:8080/esb/=7
 * http://esb.cleverbus.org/esb/=10
 * </pre>
 * <p/>
 * The host can be specified as a URI (with scheme and port).
 *
 * @param maxConnectionsPerHost a properties object specifying the maximum number of connection
 * @see PoolingHttpClientConnectionManager#setMaxPerRoute(org.apache.http.conn.routing.HttpRoute, int)
 */
@Override
public void setMaxConnectionsPerHost(Map<String, String> maxConnectionsPerHost) throws URISyntaxException {
    for (Map.Entry<String, String> entry : maxConnectionsPerHost.entrySet()) {
        URI uri = new URI(entry.getKey());
        HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        HttpRoute route = new HttpRoute(host);

        PoolingHttpClientConnectionManager connectionManager = (PoolingHttpClientConnectionManager) getConnPoolControl();

        int max = Integer.parseInt(entry.getValue());
        connectionManager.setMaxPerRoute(route, max);
        BasicScheme basicAuth = new BasicScheme();
        authCache.get().put(host, basicAuth);
    }
}