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.opensaml.security.httpclient.HttpClientSecuritySupportTest.java

@Test
public void testMarshalSecurityParametersWithoutReplacement() {
    HttpClientContext context = HttpClientContext.create();

    CredentialsProvider credProvider = new BasicCredentialsProvider();
    TrustEngine<X509Credential> trustEngine = new MockTrustEngine();
    CriteriaSet criteriaSet = new CriteriaSet();
    List<String> protocols = Lists.newArrayList("foo");
    List<String> cipherSuites = Lists.newArrayList("foo");
    X509Credential clientTLSCred = new BasicX509Credential(cert);
    HostnameVerifier verifier = new StrictHostnameVerifier();

    context.setCredentialsProvider(credProvider);
    context.setAttribute(CONTEXT_KEY_TRUST_ENGINE, trustEngine);
    context.setAttribute(CONTEXT_KEY_CRITERIA_SET, criteriaSet);
    context.setAttribute(CONTEXT_KEY_TLS_PROTOCOLS, protocols);
    context.setAttribute(CONTEXT_KEY_TLS_CIPHER_SUITES, cipherSuites);
    context.setAttribute(CONTEXT_KEY_CLIENT_TLS_CREDENTIAL, clientTLSCred);
    context.setAttribute(CONTEXT_KEY_HOSTNAME_VERIFIER, verifier);

    HttpClientSecurityParameters params = new HttpClientSecurityParameters();
    params.setCredentialsProvider(new BasicCredentialsProvider());
    params.setTLSTrustEngine(new MockTrustEngine());
    params.setTLSCriteriaSet(new CriteriaSet());
    params.setTLSProtocols(Lists.newArrayList("foo"));
    params.setTLSCipherSuites(Lists.newArrayList("foo"));
    params.setClientTLSCredential(new BasicX509Credential(cert));
    params.setHostnameVerifier(new StrictHostnameVerifier());

    HttpClientSecuritySupport.marshalSecurityParameters(context, params, false);

    Assert.assertSame(context.getCredentialsProvider(), credProvider);
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_TRUST_ENGINE), trustEngine);
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_CRITERIA_SET), criteriaSet);
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_TLS_PROTOCOLS), protocols);
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_TLS_CIPHER_SUITES), cipherSuites);
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_CLIENT_TLS_CREDENTIAL), clientTLSCred);
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_HOSTNAME_VERIFIER), verifier);
}

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

/**
 * Retrieves the groups that the user is a nested member of
 * /*from  w ww  .j a v  a2s . c o m*/
 * @param username
 * @return a set of roles (as strings)
 * @throws RemoteException
 */
public Set<String> getNestedGroups(String username) throws RemoteException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getNestedGroups({})", username);
    }

    HttpClientContext hc = HttpClientContext.create();
    int maxResults = 100;
    int startIndex = 0;
    StringBuilder request = new StringBuilder("user/group/nested?username=").append(urlEncode(username))
            .append("&max-results=").append(maxResults).append("&start-index=");

    return getGroupsFromCrowdLoop(hc, request, startIndex, maxResults);
}

From source file:com.logsniffer.event.publisher.http.HttpPublisher.java

/**
 * Init method for this publisher.//from   w ww  .j  a  v  a 2  s. c  o m
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer, final HttpClient httpClient) {
    this.velocityRenderer = velocityRenderer;
    this.httpClient = httpClient;
    if (getHttpAuthentication() != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getHttpAuthentication().getUsername(),
                        getHttpAuthentication().getPassword()));
        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.RestStream.java

private static String executeRequest(HttpClient client, HttpUriRequest req, String username, String password)
        throws IOException {
    HttpResponse response;/*from   w  ww.ja va 2s.  co  m*/

    if (StringUtils.isNotEmpty(username)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(req.getURI().getAuthority(), DEFAULT_AUTH_PORT),
                new UsernamePasswordCredentials(username, password));

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

        response = client.execute(req, context);
    } else {
        response = client.execute(req);
    }

    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
        throw new HttpResponseException(responseCode, response.getStatusLine().getReasonPhrase());
    }

    String respStr = EntityUtils.toString(response.getEntity(), Utils.UTF8);

    return respStr;
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request with preemptive basic authentication.
 *
 * @param request the request to execute
 * @param username usename to use/*from   ww  w .ja  v  a  2s  .  c o m*/
 * @param password password to use
 * @return the open responses
 * @throws IOException in case of IOException
 */
@SuppressWarnings("resource")
protected CloseableHttpResponse executeWithBasicAuth(final HttpUriRequest request, final String username,
        final String password) throws IOException {
    final HttpHost target = new HttpHost(HOSTNAME, SERVER_PORT, PROTOCOL);
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return httpclient.execute(request, localContext);
}

From source file:org.callimachusproject.client.HttpClientRedirectTest.java

@Test
public void testRelativeRequestURIWithFragment() throws Exception {
    register("*", new SimpleService());
    final HttpHost target = getServerHttp();

    final HttpGet httpget = new HttpGet("/stuff#blahblah");
    final HttpClientContext context = HttpClientContext.create();

    final HttpResponse response = this.httpclient.execute(target, httpget, context);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    final HttpRequest request = context.getRequest();
    Assert.assertEquals("/stuff", request.getRequestLine().getUri());

    final URI uri = new URIBuilder(httpget.getURI()).setHost(target.getHostName()).setPort(target.getPort())
            .setScheme(target.getSchemeName()).build();

    final URI location = getHttpLocation(httpget, context);
    Assert.assertEquals(uri, location);//from   ww  w . ja  va  2  s.co  m
}

From source file:microsoft.exchange.webservices.data.core.ExchangeServiceBase.java

/**
 * (Re)initializes the HttpContext object. This removes any existing state (mainly cookies). Use an own
 * cookie store, instead of the httpClient's global store, so cookies get reset on reinitialization
 *//*from   ww  w.  ja  va 2s . co m*/
private void initializeHttpContext() {
    CookieStore cookieStore = new BasicCookieStore();
    httpContext = HttpClientContext.create();
    httpContext.setCookieStore(cookieStore);
}

From source file:ext.deployit.onfailurehandler.OnReleaseFailureEventListener.java

private void invokeOnFailureHandler(Release release) throws IOException, URISyntaxException {
    String handlerEndpoint = getHandlerEndpoint();
    // sentinel object so OK to use ==
    if (handlerEndpoint == UNINITIALIZED) {
        logger.error("Global variable '{}' not found! Doing nothing", ENDPOINT_VARIABLE_NAME);
        return;//from  w  w w  . j a  va 2 s.c  om
    }

    URIBuilder requestUri = new URIBuilder().setScheme(ENDPOINT_SCHEME).setHost(ENDPOINT_HOST)
            .setPort(ENDPOINT_PORT).setPath(getHandlerEndpoint()).addParameter("releaseId", release.getId())
            .addParameter("onFailureUser", ENDPOINT_USER);
    HttpGet request = new HttpGet(requestUri.build());
    // without this, Apache HC will only send auth *after* a failure
    HttpClientContext authenticatingContext = HttpClientContext.create();
    authenticatingContext.setAuthCache(PREEMPTIVE_AUTH_CACHE);
    logger.debug("About to execute callback to {}", request);
    CloseableHttpResponse response = HTTP_CLIENT.execute(request, authenticatingContext);
    try {
        logger.info("Response line from request: {}", response.getStatusLine());
        logger.debug("Response body: {}", EntityUtils.toString(response.getEntity()));
    } finally {
        response.close();
    }
}