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.alfresco.test.util.UserService.java

/**
 * Login in alfresco share/*from w  w  w  .  j av  a 2 s. c  om*/
 * 
 * @param userName login user name
 * @param userPass login user password
 * @return true for successful user login
 * @throws Exception if error
 */
public boolean login(final String userName, final String userPass) throws Exception {
    if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPass)) {
        throw new IllegalArgumentException("Parameter missing");
    }
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    HttpState state;
    org.apache.commons.httpclient.HttpClient theClient = new org.apache.commons.httpclient.HttpClient();
    String reqURL = client.getAlfrescoUrl() + "share/page/dologin";
    org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod(
            reqURL);
    NameValuePair[] formParams;
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setCookieStore(cookieStore);
    formParams = (new NameValuePair[] { new NameValuePair("username", userName),
            new NameValuePair("password", userPass),
            new NameValuePair("success", "/share/page/user/" + userName + "/dashboard"),
            new NameValuePair("failure", "/share/page/type/login?error=true") });
    post.setRequestBody(formParams);
    int postStatus = theClient.executeMethod(post);
    if (302 == postStatus) {
        state = theClient.getState();
        post.releaseConnection();
        org.apache.commons.httpclient.methods.GetMethod get = new org.apache.commons.httpclient.methods.GetMethod(
                client.getAlfrescoUrl() + "share/page/user/" + userName + "/dashboard");
        theClient.setState(state);
        int getStatus = theClient.executeMethod(get);
        get.releaseConnection();
        if (200 == getStatus) {
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }

}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

/**
 * Create HttpClient from given host/port
 * @param request the {@link HttpRequestBase} for which an HttpClient will be created
 * @return CloseableHttpClient//from  ww w . j a v a2 s.c  o m
 */
private CloseableHttpClient getHttpClient(final HttpRequestBase request) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.useSystemProperties();

    RequestConfig.Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(10 * 1000);
    requestConfig.setConnectionRequestTimeout(60 * 1000);
    requestConfig.setSocketTimeout(60 * 1000);
    request.setConfig(requestConfig.build());

    final String host = getMethodHost(request);

    if (authenticator != null) {
        authenticator.configureBuilder(httpClientBuilder);

        context = HttpClientContext.create();
        authenticator.configureContext(context, HttpHost.create(host));
    }

    setClientProxyParams(host, httpClientBuilder);

    return httpClientBuilder.build();
}

From source file:org.glowroot.central.SyntheticMonitorService.java

private HttpClientContext getHttpClientContext() throws Exception {
    HttpProxyConfig httpProxyConfig = configRepository.getHttpProxyConfig();
    if (httpProxyConfig.host().isEmpty() || httpProxyConfig.username().isEmpty()) {
        return HttpClientContext.create();
    }//from   w ww. j  a  v  a2  s  . co m

    // perform preemptive proxy authentication

    int proxyPort = MoreObjects.firstNonNull(httpProxyConfig.port(), 80);
    HttpHost proxyHost = new HttpHost(httpProxyConfig.host(), proxyPort);

    BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm="));
    BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(proxyHost, basicScheme);

    String password = httpProxyConfig.encryptedPassword();
    if (!password.isEmpty()) {
        password = Encryption.decrypt(password, configRepository.getLazySecretKey());
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxyHost),
            new UsernamePasswordCredentials(httpProxyConfig.username(), password));
    HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);
    context.setCredentialsProvider(credentialsProvider);
    return context;
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * Creates HttpClientContext required for basic authentication
 * @return/*from  w  w  w.j  a  v a2s  . co  m*/
 */
private HttpClientContext getAuthContext() {

    //Create target host based on targetURL
    HttpHost targetHost = getTargetHost(this.targetURL);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(this.basicAuthId, this.basicAuthPwd));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    authCache.put(targetHost, new BasicScheme());

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

    return context;
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;/* ww w  . j  a va  2s  .  c  o  m*/
    }

    final Proxy proxy;

    if (proxyConfig != null) {
        URI hostURI = URI.create(host);
        proxy = proxyConfig.createProxy(hostURI.getHost());
    } else {
        proxy = Proxy.NO_PROXY;
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.log(Level.FINE, "Jenkins proxy: {0}", proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Create a basic login context.//ww  w  .j  a  va2  s. c  o  m
 * 
 * @param username
 * @param pass
 * @return
 */
public static HttpContext basicLoginContext(String username, String pass) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, pass);
    provider.setCredentials(AuthScope.ANY, credentials);
    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    return context;
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException {
    final HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(reqConfBuilder.build());
    if (this.host != null)
        context.setTargetHost(new HttpHost(this.host));

    setHeaders(httpUriRequest);//  w  w w .j  a v  a  2  s  . c om
    // statistics
    storeConnectionInfo(httpUriRequest);
    // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF
    if (httpUriRequest instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest;
        final HttpEntity entity = hrequest.getEntity();
        assert entity != null;
        //assert !entity.isChunked();
        //assert entity.getContentLength() >= 0;
        assert !hrequest.expectContinue();
    }

    final String initialThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI());
    final long time = System.currentTimeMillis();
    try {

        if (concurrent) {
            FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>(
                    new Callable<CloseableHttpResponse>() {
                        @Override
                        public CloseableHttpResponse call() throws ClientProtocolException, IOException {
                            final CloseableHttpClient client = clientBuilder.build();
                            CloseableHttpResponse response = client.execute(httpUriRequest, context);
                            return response;
                        }
                    });
            executor.execute(t);
            try {
                this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                throw e.getCause();
            } catch (Throwable e) {
            }
            try {
                t.cancel(true);
            } catch (Throwable e) {
            }
            if (this.httpResponse == null)
                throw new IOException("timout to client after " + this.timeout + "ms" + " for url "
                        + httpUriRequest.getURI().toString());
        } else {
            final CloseableHttpClient client = clientBuilder.build();
            this.httpResponse = client.execute(httpUriRequest, context);
        }
        this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS,
                Long.toString(System.currentTimeMillis() - time));
    } catch (final Throwable e) {
        ConnectionInfo.removeConnection(httpUriRequest.hashCode());
        httpUriRequest.abort();
        if (this.httpResponse != null)
            this.httpResponse.close();
        //e.printStackTrace();
        throw new IOException(
                "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage())
                        + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url "
                        + httpUriRequest.getURI().toString());
    } finally {
        /* Restore the thread initial name */
        Thread.currentThread().setName(initialThreadName);
    }
}

From source file:org.keycloak.testsuite.adapter.servlet.AbstractSAMLServletsAdapterTest.java

@Test
//KEYCLOAK-4020//  w  w  w.  j a  v  a 2 s . co m
public void testBooleanAttribute() throws Exception {
    AuthnRequestType req = SamlClient.createLoginRequestDocument("http://localhost:8081/employee2/",
            getAppServerSamlEndpoint(employee2ServletPage).toString(),
            getAuthServerSamlEndpoint(SAMLSERVLETDEMO));
    Document doc = SAML2Request.convert(req);

    SAMLDocumentHolder res = login(bburkeUser, getAuthServerSamlEndpoint(SAMLSERVLETDEMO), doc, null,
            SamlClient.Binding.POST, SamlClient.Binding.POST);
    Document responseDoc = res.getSamlDocument();

    Element attribute = responseDoc.createElement("saml:Attribute");
    attribute.setAttribute("Name", "boolean-attribute");
    attribute.setAttribute("NameFormat", "urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

    Element attributeValue = responseDoc.createElement("saml:AttributeValue");
    attributeValue.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
    attributeValue.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    attributeValue.setAttribute("xsi:type", "xs:boolean");
    attributeValue.setTextContent("true");

    attribute.appendChild(attributeValue);
    IOUtil.appendChildInDocument(responseDoc, "samlp:Response/saml:Assertion/saml:AttributeStatement",
            attribute);

    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpClientContext context = HttpClientContext.create();

        HttpUriRequest post = SamlClient.Binding.POST
                .createSamlUnsignedResponse(getAppServerSamlEndpoint(employee2ServletPage), null, responseDoc);
        response = client.execute(post, context);
        assertThat(response, statusCodeIsHC(Response.Status.FOUND));
        response.close();

        HttpGet get = new HttpGet(employee2ServletPage.toString() + "/getAttributes");
        response = client.execute(get);
        assertThat(response, statusCodeIsHC(Response.Status.OK));
        assertThat(response, bodyHC(containsString("boolean-attribute: true")));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            try {
                response.close();
            } catch (IOException ex) {
            }
        }
    }
}