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:com.github.sardine.impl.SardineImpl.java

@Override
public void enablePreemptiveAuthentication(String hostname) {
    AuthCache cache = new BasicAuthCache();
    // Generate Basic preemptive scheme object and stick it to the local execution context
    BasicScheme basicAuth = new BasicScheme();
    // Configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.
    for (String scheme : Arrays.asList("http", "https")) {
        cache.put(new HttpHost(hostname, -1, scheme), basicAuth);
    }//from   w  ww .  j  av a2 s .  c  o m
    // Add AuthCache to the execution context
    this.context.setAttribute(HttpClientContext.AUTH_CACHE, cache);
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

@VisibleForTesting
static RestTemplate buildRestTemplate(String adminUri, String user, String password) {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local; from the apache docs...
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    URI uri;//from  www  .  j  a v a  2s  .c om
    try {
        uri = new URI(adminUri);
    } catch (URISyntaxException e) {
        throw new RabbitAdminException("Invalid URI", e);
    }
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) {

        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return localContext;
        }

    });
    restTemplate.setMessageConverters(
            Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter()));
    return restTemplate;
}

From source file:com.maxmind.minfraud.WebServiceClient.java

private HttpPost requestFor(Transaction transaction, URL url) throws MinFraudException, IOException {
    Credentials credentials = new UsernamePasswordCredentials(Integer.toString(userId), licenseKey);

    HttpPost request;/*  w ww . ja  va2s .  c  o  m*/
    try {
        request = new HttpPost(url.toURI());
    } catch (URISyntaxException e) {
        throw new MinFraudException("Error parsing request URL", e);
    }
    try {
        request.addHeader(new BasicScheme().authenticate(credentials, request, null));
    } catch (org.apache.http.auth.AuthenticationException e) {
        throw new AuthenticationException("Error setting up request authentication", e);
    }
    request.addHeader("Accept", "application/json");
    request.addHeader("User-Agent", this.userAgent());

    String requestBody = transaction.toJson();

    StringEntity input = new StringEntity(requestBody, APPLICATION_JSON);

    request.setEntity(input);
    return request;
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClient.java

private HttpContext httpContext() {
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    if (isNotBlank(this.username) && this.password != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        HttpHost httpHost = HttpHost.create(this.rootConfluenceUrl);
        AuthScope authScope = new AuthScope(httpHost);
        basicCredentialsProvider.setCredentials(authScope, credentials);

        BasicAuthCache basicAuthCache = new BasicAuthCache();
        basicAuthCache.put(httpHost, new BasicScheme());

        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCredentialsProvider(basicCredentialsProvider);
        httpClientContext.setAuthCache(basicAuthCache);

        return httpClientContext;
    } else {//from  ww w . jav a  2s .c om
        return null;
    }
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username,
        String password, boolean preAuth) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = client.getCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        BasicHttpContext httpContext = new BasicHttpContext();
        if (preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }/*ww  w  .j  a va  2 s .  c o m*/
        return httpContext;
    }
    return null;
}

From source file:de.undercouch.gradle.tasks.download.DownloadAction.java

/**
 * Opens a connection to the given HTTP host and requests a file. Checks
 * the last-modified header on the server if the given timestamp is
 * greater than 0./*from   w w w  .j a v a 2s.com*/
 * @param httpHost the HTTP host to connect to
 * @param file the file to request
 * @param timestamp the timestamp of the destination file, in milliseconds
 * @param client the HTTP client to use to perform the request
 * @return the URLConnection
 * @throws IOException if the connection could not be opened
 */
private CloseableHttpResponse openConnection(HttpHost httpHost, String file, long timestamp,
        CloseableHttpClient client) throws IOException {
    //perform preemptive authentication
    HttpClientContext context = null;
    if ((username != null && password != null) || credentials != null) {
        context = HttpClientContext.create();
        AuthScheme as = authScheme;
        if (as == null) {
            as = new BasicScheme();
        }
        Credentials c;
        if (username != null && password != null) {
            if (!(as instanceof BasicScheme) && !(as instanceof DigestScheme)) {
                throw new IllegalArgumentException("If 'username' and "
                        + "'password' are set 'authScheme' must be either " + "'Basic' or 'Digest'.");
            }
            c = new UsernamePasswordCredentials(username, password);
        } else {
            c = credentials;
        }
        addAuthentication(httpHost, c, as, context);
    }

    //create request
    HttpGet get = new HttpGet(file);

    //configure timeouts
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeoutMs)
            .setConnectionRequestTimeout(timeoutMs).setSocketTimeout(timeoutMs).build();
    get.setConfig(config);

    //add authentication information for proxy
    String scheme = httpHost.getSchemeName();
    String proxyHost = System.getProperty(scheme + ".proxyHost");
    String proxyPort = System.getProperty(scheme + ".proxyPort");
    String proxyUser = System.getProperty(scheme + ".proxyUser");
    String proxyPassword = System.getProperty(scheme + ".proxyPassword");
    if (proxyHost != null && proxyPort != null && proxyUser != null && proxyPassword != null) {
        if (context == null) {
            context = HttpClientContext.create();
        }
        int nProxyPort = Integer.parseInt(proxyPort);
        HttpHost proxy = new HttpHost(proxyHost, nProxyPort, scheme);
        Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        addAuthentication(proxy, credentials, null, context);
    }

    //set If-Modified-Since header
    if (timestamp > 0) {
        get.setHeader("If-Modified-Since", DateUtils.formatDate(new Date(timestamp)));
    }

    //set headers
    if (headers != null) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            get.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }

    //enable compression
    if (compress) {
        get.setHeader("Accept-Encoding", "gzip");
    }

    //execute request
    CloseableHttpResponse response = client.execute(httpHost, get, context);

    //handle response
    int code = response.getStatusLine().getStatusCode();
    if ((code < 200 || code > 299) && code != HttpStatus.SC_NOT_MODIFIED) {
        throw new ClientProtocolException(response.getStatusLine().getReasonPhrase());
    }

    return response;
}

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username,
        String password, boolean preAuth) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = new BasicCredentialsProvider();
        builder.setDefaultCredentialsProvider(cp);

        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        BasicHttpContext httpContext = new BasicHttpContext();
        if (preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }/* w w  w  .ja v a  2 s .c om*/
        return httpContext;
    }
    return null;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);/*from  w ww.  j ava2s.c  om*/
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider,
                authData);
    }

    return client;
}

From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//w  w  w . java2 s .c o m
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        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);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}