Example usage for org.apache.http.client.protocol HttpClientContext create

List of usage examples for org.apache.http.client.protocol HttpClientContext create

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext create.

Prototype

public static HttpClientContext create() 

Source Link

Usage

From source file:org.datacleaner.cluster.http.HttpClusterManager.java

/**
 * Creates a new HTTP cluster manager//ww  w .j  av  a2s. c  om
 * 
 * @param slaveEndpoints
 *            the endpoint URLs of the slaves
 */
public HttpClusterManager(List<String> slaveEndpoints) {
    this(HttpClients.custom().useSystemProperties()
            .setConnectionManager(new PoolingHttpClientConnectionManager()).build(), HttpClientContext.create(),
            slaveEndpoints);
}

From source file:org.datacleaner.monitor.pentaho.PentahoCarteClient.java

private HttpClientContext createHttpClientContext(PentahoJobType pentahoJobType) {
    final String hostname = pentahoJobType.getCarteHostname();
    final Integer port = pentahoJobType.getCartePort();
    final String username = pentahoJobType.getCarteUsername();
    final String password = pentahoJobType.getCartePassword();

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

    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);

    return context;
}

From source file:org.fcrepo.client.utils.HttpHelper.java

/**
 * Create an HTTP helper with a pre-configured HttpClient instance.
 * @param repositoryURL Fedora base URL.
 * @param httpClient Pre-configured HttpClient instance.
 * @param readOnly If true, throw an exception when an update is attempted.
**//*from   ww w. j a v  a  2 s  . co  m*/
public HttpHelper(final String repositoryURL, final HttpClient httpClient, final boolean readOnly) {
    this.repositoryURL = repositoryURL;
    this.httpClient = httpClient;
    this.readOnly = readOnly;

    // Use pre-emptive Auth whether the repository is actually protected or not.
    final URI uri = URI.create(repositoryURL);
    final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

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

    this.httpContext = localContext;
}

From source file:org.jboss.as.test.integration.security.common.CoreUtils.java

/**
 * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
 * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new
 * request is created with the provided credentials (basic authentication).
 *
 * @param url URL to which the request should be made
 * @param user Username (may be null)/*from w ww.  j a  v  a  2 s . c om*/
 * @param pass Password (may be null)
 * @param expectedStatusCode expected status code returned from the requested server
 * @return HTTP response body
 * @throws IOException
 * @throws URISyntaxException
 */
public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode)
        throws IOException, URISyntaxException {
    LOGGER.info("Requesting URL " + url);
    try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpGet httpGet = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (401 != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        final HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        response = httpClient.execute(httpGet, context);
        statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode,
                statusCode);
        return EntityUtils.toString(response.getEntity());
    }
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to:/*from  w ww  .  j  a va  2s .c om*/
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Creates an Apache HTTP Client object, ignoring SSL Exceptions like self signed
 * certificates, and sets Auth. Scheme to Digest Auth.
 *
 * @param fboxUrl//from w ww.ja va  2 s .  com
 *            the URL from config file of fbox to connect to
 * @return the ready-to-use httpclient for tr064 requests
 */
private synchronized CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);

    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth
    // cache. Digeste is standard for fbox auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", "HTTPS Access"); // known from fbox specification
    digestAuth.overrideParamter("nonce", ""); // never known at first request
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);

    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // accept self signed certs
        // dont verify hostname against cert CN
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null,
                new NoopHostnameVerifier());
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000)
            .setConnectionRequestTimeout(4000).build();

    // BUILDER
    // setup builder with parameters defined before
    hc = HttpClientBuilder.create().setSSLSocketFactory(sslsf) // set the SSL options which trust every self signed
            // cert
            .setDefaultCredentialsProvider(credp) // set auth options using digest
            .setDefaultRequestConfig(rc) // set the request config specifying timeout
            .build();

    return hc;
}

From source file:org.xwiki.extension.repository.xwiki.internal.XWikiExtensionRepository.java

public XWikiExtensionRepository(ExtensionRepositoryDescriptor repositoryDescriptor,
        XWikiExtensionRepositoryFactory repositoryFactory, ExtensionLicenseManager licenseManager,
        HttpClientFactory httpClientFactory) throws Exception {
    super(repositoryDescriptor.getURI().getPath().endsWith("/")
            ? new DefaultExtensionRepositoryDescriptor(repositoryDescriptor.getId(),
                    repositoryDescriptor.getType(),
                    new URI(StringUtils.chop(repositoryDescriptor.getURI().toString())))
            : repositoryDescriptor);/*from   w w w  .  j av  a2s.c  om*/

    this.repositoryFactory = repositoryFactory;
    this.licenseManager = licenseManager;
    this.httpClientFactory = httpClientFactory;

    // Uri builders
    this.rootUriBuider = createUriBuilder(Resources.ENTRYPOINT);
    this.extensionVersionUriBuider = createUriBuilder(Resources.EXTENSION_VERSION);
    this.extensionVersionFileUriBuider = createUriBuilder(Resources.EXTENSION_VERSION_FILE);
    this.extensionVersionsUriBuider = createUriBuilder(Resources.EXTENSION_VERSIONS);
    this.searchUriBuider = createUriBuilder(Resources.SEARCH);

    // Setup preemptive authentication
    if (getDescriptor().getProperty("auth.user") != null) {
        // 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(new HttpHost(getDescriptor().getURI().getHost(), getDescriptor().getURI().getPort(),
                getDescriptor().getURI().getScheme()), basicAuth);

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