Example usage for org.apache.http.protocol HttpContext getAttribute

List of usage examples for org.apache.http.protocol HttpContext getAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext getAttribute.

Prototype

Object getAttribute(String str);

Source Link

Usage

From source file:org.xwiki.android.rest.HttpConnector.java

/**
 * set user credentials with manually developed preemtive Auth
 */// w w w .j a  va  2 s .c  om
private void setCredentials() {
    if (isSecured) {

        // Setting preemtiveAuth manually since org.apache.http does not support it
        preemptiveAuth = new HttpRequestInterceptor() {

            @Override
            public void process(HttpRequest request, 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);
                    }
                }
            }

        };

        client.addRequestInterceptor(preemptiveAuth, 0);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM),
                defaultcreds);
    }
}

From source file:test.integ.be.e_contract.cdi.crossconversation.CrossConversationScopedTest.java

@Test
public void testAndroidScopedNewSessionIsNewAndroidScope() throws Exception {
    String browserLocation = this.baseURL + "browser";
    String valueLocation = this.baseURL + "value";
    LOGGER.debug("location: {}", browserLocation);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    HttpClient httpClient = httpClientBuilder.build();

    HttpContext httpContext = new BasicHttpContext();
    String androidCode = doGet(httpClient, httpContext, browserLocation);
    LOGGER.debug("result: {}", androidCode);
    String value = doGet(httpClient, httpContext, valueLocation);

    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
    cookieStore.clear();/*w w  w.  j  ava2 s  . com*/

    String androidCode2 = doGet(httpClient, httpContext, browserLocation);
    LOGGER.debug("result 2: {}", androidCode2);
    String value2 = doGet(httpClient, httpContext, valueLocation);

    assertNotEquals(androidCode, androidCode2);
    assertNotEquals(value, value2);
}

From source file:com.bincode.util.DefaultRedirectHandler.java

public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*ww w .  j  ava  2s .c  om*/

    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        String method = request.getRequestLine().getMethod();
        return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default:
        return false;
    } //end of switch
}

From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

public HttpConnectionPoolBuilder(final Host host, final ThreadLocalHostnameDelegatingTrustManager trust,
        final X509KeyManager key, final ProxyFinder proxy) {
    this(host, new PlainConnectionSocketFactory() {
        @Override/*from  w  w  w  .ja v a2 s.  co m*/
        public Socket createSocket(final HttpContext context) throws IOException {
            // Return socket factory with disabled support for HTTP tunneling as provided internally
            return new ProxySocketFactory(host.getProtocol(), new TrustManagerHostnameCallback() {
                @Override
                public String getTarget() {
                    return context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST).toString();
                }
            }, proxy).disable(Proxy.Type.HTTP).disable(Proxy.Type.HTTPS).createSocket();
        }
    }, new SSLConnectionSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key),
            new DisabledX509HostnameVerifier()) {
        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            return new ProxySocketFactory(host.getProtocol(), new TrustManagerHostnameCallback() {
                @Override
                public String getTarget() {
                    return context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST).toString();
                }
            }, proxy).disable(Proxy.Type.HTTP).disable(Proxy.Type.HTTPS).createSocket();
        }

        @Override
        public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
                final InetSocketAddress remoteAddress, final InetSocketAddress localAddress,
                final HttpContext context) throws IOException {
            trust.setTarget(remoteAddress.getHostName());
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    }, proxy);
}

From source file:test.integ.be.e_contract.cdi.crossconversation.CrossConversationScopedTest.java

@Test
public void testAndroidScopedBasicUsage() throws Exception {
    String browserLocation = this.baseURL + "browser";
    String valueLocation = this.baseURL + "value";
    LOGGER.debug("location: {}", browserLocation);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    HttpClient httpClient = httpClientBuilder.build();

    HttpContext httpContext = new BasicHttpContext();
    String androidCode = doGet(httpClient, httpContext, browserLocation);
    LOGGER.debug("result: {}", androidCode);
    String value = doGet(httpClient, httpContext, valueLocation);

    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
    cookieStore.clear();/*from   w  w  w  . java2s .  c  om*/

    String androidLocation = this.baseURL + "android?androidCode=" + androidCode;
    valueLocation += "?androidCode=" + androidCode;

    HttpClient androidHttpClient = httpClientBuilder.build();
    HttpContext androidHttpContext = new BasicHttpContext();

    String androidCode2 = doGet(androidHttpClient, androidHttpContext, androidLocation);
    LOGGER.debug("result 2: {}", androidCode2);
    String value2 = doGet(androidHttpClient, androidHttpContext, valueLocation);

    assertEquals(androidCode, androidCode2);
    assertEquals(value, value2);
}

From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java

private HttpPost getForm(final HttpContext httpContext, final HttpResponse response, final String user,
        final String password) throws IllegalStateException, IOException {
    final HttpEntity entity = response.getEntity();
    final HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final String requestUri = getLatestRedirectedUrl(httpContext);
    final String requestBaseUrl = requestUri.substring(0, requestUri.lastIndexOf('/'));
    final String userFormId = getHtmlElementId(host, FormId.USER);
    final String passFormId = getHtmlElementId(host, FormId.PASS);
    final String loginFormId = getHtmlElementId(host, FormId.LOGIN_FORM);
    final String loginButton = getSsoErrorHandler(host).getSsoLoginButtonName();

    log.debug("Looking for HTML input form retrieved from " + requestUri);

    final List<NameValuePair> formNvps = new ArrayList<NameValuePair>();

    final Document doc = Jsoup.parse(entity.getContent(), "UTF-8", requestBaseUrl);
    final org.jsoup.nodes.Element form = doc
            .select("form" + (loginFormId == null ? "" : "[id=" + loginFormId + "]")).first();
    final String formAction = form.attr("action");
    final HttpPost formPost = new HttpPost(getUrl(requestBaseUrl, formAction));
    final Elements formFields = form.select("input");
    for (final Element element : formFields) {
        final String fieldName = element.attr("name");
        String fieldValue = element.attr("value");
        final String fieldId = element.attr("id");

        log.debug(String.format("Processing form field: name='%s' value='%s' id='%s'", fieldName, fieldValue,
                fieldId));//from  w ww .  j  a  va  2  s . co m

        if (fieldId.equalsIgnoreCase(userFormId)) {
            fieldValue = user;
            log.debug(String.format("Set formField user='%s'", user));
        } else if (fieldId.equalsIgnoreCase(passFormId)) {
            log.debug("Set formField password='*******'");
            fieldValue = password;
        }

        if (loginButton != null && element.attr("type").equalsIgnoreCase("submit")) {
            if (element.attr("name").equalsIgnoreCase(loginButton)) {
                formNvps.add(new BasicNameValuePair(fieldName, fieldValue));
            }
        } else {
            formNvps.add(new BasicNameValuePair(fieldName, fieldValue));
        }
    }

    formPost.setEntity(new UrlEncodedFormEntity(formNvps, "UTF-8"));
    return formPost;
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

@Override
@Guarded(by = STARTED)/*from   w w  w .j  a v  a2 s.  c  o m*/
public HttpClientBuilder prepare(@Nullable final Customizer customizer) {
    final HttpClientPlan plan = httpClientPlan();

    // attach connection manager early, so customizer has chance to replace it if needed
    plan.getClient().setConnectionManager(sharedConnectionManager);

    // apply defaults
    defaultsCustomizer.customize(plan);

    // apply globals
    new ConfigurationCustomizer(getConfigurationInternal()).customize(plan);

    // apply instance customization
    if (customizer != null) {
        customizer.customize(plan);
    }

    // apply plan to builder
    HttpClientBuilder builder = plan.getClient();
    // User agent must be set here to apply to all apache http requests, including over proxies
    String userAgent = plan.getUserAgent();
    if (userAgent != null) {
        setUserAgent(builder, userAgent);
    }
    builder.setDefaultConnectionConfig(plan.getConnection().build());
    builder.setDefaultSocketConfig(plan.getSocket().build());
    builder.setDefaultRequestConfig(plan.getRequest().build());
    builder.setDefaultCredentialsProvider(plan.getCredentials());

    builder.addInterceptorFirst((HttpRequest request, HttpContext context) -> {
        // add custom http-context attributes
        for (Entry<String, Object> entry : plan.getAttributes().entrySet()) {
            // only set context attribute if not already set, to allow per request overrides
            if (context.getAttribute(entry.getKey()) == null) {
                context.setAttribute(entry.getKey(), entry.getValue());
            }
        }

        // add custom http-request headers
        for (Entry<String, String> entry : plan.getHeaders().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    });
    builder.addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
        if (outboundLog.isDebugEnabled()) {
            httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted());
            httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext));
            outboundLog.debug("{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine());
        }
    });
    builder.addInterceptorLast((HttpResponse httpResponse, HttpContext httpContext) -> {
        Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH);
        if (stopwatch != null) {
            outboundLog.debug("{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI),
                    httpResponse.getStatusLine(), stopwatch);
        }
    });

    return builder;
}

From source file:android.net.http.Connection.java

/**
 * Use same logic as ConnectionReuseStrategy
 * @see ConnectionReuseStrategy// w w  w .j av a 2 s  .  com
 */
private boolean keepAlive(HttpEntity entity, ProtocolVersion ver, int connType, final HttpContext context) {
    org.apache.http.HttpConnection conn = (org.apache.http.HttpConnection) context
            .getAttribute(ExecutionContext.HTTP_CONNECTION);

    if (conn != null && !conn.isOpen())
        return false;
    // do NOT check for stale connection, that is an expensive operation

    if (entity != null) {
        if (entity.getContentLength() < 0) {
            if (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0)) {
                // if the content length is not known and is not chunk
                // encoded, the connection cannot be reused
                return false;
            }
        }
    }
    // Check for 'Connection' directive
    if (connType == Headers.CONN_CLOSE) {
        return false;
    } else if (connType == Headers.CONN_KEEP_ALIVE) {
        return true;
    }
    // Resorting to protocol version default close connection policy
    return !ver.lessEquals(HttpVersion.HTTP_1_0);
}

From source file:fr.univsavoie.ltp.client.map.Session.java

/**
 * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS).
 * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...)
 */// w w w.j  a  va2  s. c  o m
private void secureAuth() {
    try {
        // Instance de SharedPreferences pour lire les donnes dans un fichier
        SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE);
        String login = myPrefs.getString("Login", null);
        String password = myPrefs.getString("Password", null);

        HttpRequestInterceptor preemptiveAuth = 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);
                    }
                }
            }
        };

        // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Enable HTTP parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        httpClient = new DefaultHttpClient(ccm, params);

        CredentialsProvider authCred = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials(login, password);
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}

From source file:br.ufsc.das.gtscted.shibbauth.Connection.java

public String[] httpGetWithEndpoint(String url) throws IOException {
    HttpGet httpget = new HttpGet(url);
    HttpContext context = new BasicHttpContext();
    HttpResponse response = httpClient.execute(httpget, context);
    String responseAsStr = readResponse(response.getEntity().getContent()).toString();
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(response.getStatusLine().toString());
    }/* ww  w. j  a va  2  s .co  m*/
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String currentUrl = currentHost.toURI() + currentReq.getURI();

    URL endpointUrl = new URL(currentUrl);
    String endpointDomain = "https://" + endpointUrl.getHost();

    String[] returnArray = { endpointDomain, responseAsStr };
    return returnArray;
}