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:ee.ria.xroad.proxy.clientproxy.AuthTrustVerifier.java

static void verify(HttpContext context, SSLSession sslSession, URI selectedAddress) {
    log.debug("verify()");

    ServiceId service = (ServiceId) context.getAttribute(ID_PROVIDERNAME);
    if (service == null) {
        throw new CodedException(X_SSL_AUTH_FAILED, "Could not get provider name from context");
    }/*from  www .j a  v  a  2s .c  o m*/

    X509Certificate[] certs = getPeerCertificates(sslSession);
    if (certs.length == 0) {
        throw new CodedException(X_SSL_AUTH_FAILED, "Could not get peer certificates from context");
    }

    try {
        verifyAuthCert(service.getClientId(), certs, selectedAddress);
    } catch (Exception e) {
        throw translateException(e);
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

private static URI[] getAddressesFromContext(HttpContext context) {
    Object targets = context.getAttribute(ID_TARGETS);
    if (targets == null || !(targets instanceof URI[]) || ((URI[]) targets).length == 0) {
        throw new CodedException(X_INTERNAL_ERROR, "Target hosts not specified in http context");
    }//from  w w w . j  a va  2s.c  o m

    return (URI[]) targets;
}

From source file:com.msopentech.thali.utilities.universal.ThaliClientToDeviceHubUtilities.java

/**
 * This is a horrible hack used by clients to get the server key for the local Thali Device Hub. Eventually we'll
 * introduce something actually reasonably secure for this purposes.
 * @param  httpClient//  w w w  .ja va2s .  co m
 * @return
 * @throws java.io.IOException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 */
public static PublicKey getServersRootPublicKey(org.apache.http.client.HttpClient httpClient)
        throws IOException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException {
    // Taken from http://stackoverflow.com/questions/13273305/apache-httpclient-get-server-certificate
    // And yes we should do this with a request interceptor since it would work in all cases where we get a SSL
    // connection even if the HTTP request fails and I'm too lazy to rewrite it.
    ((AbstractHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(org.apache.http.HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            Object unTypedHttpConnection = context.getAttribute(ExecutionContext.HTTP_CONNECTION);

            // Android doesn't return an object that supports the HttpRoutedConnection interface which makes no sense!
            // What it does return is BasicPooledConnAdapter but that is supposed to support HttpRoutedConnection! But doesn't.
            if (unTypedHttpConnection instanceof BasicPooledConnAdapter) {
                BasicPooledConnAdapter basicPooledConnAdapter = (BasicPooledConnAdapter) unTypedHttpConnection;
                if (basicPooledConnAdapter.isSecure()) {
                    java.security.cert.Certificate[] certificates = basicPooledConnAdapter.getSSLSession()
                            .getPeerCertificates();
                    context.setAttribute(PEER_CERT_ATTRIBUTE, certificates);
                }
                return;
            }

            if (unTypedHttpConnection instanceof HttpRoutedConnection) {
                HttpRoutedConnection httpRoutedConnection = (HttpRoutedConnection) unTypedHttpConnection;
                if (httpRoutedConnection.isSecure()) {
                    java.security.cert.Certificate[] certificates = httpRoutedConnection.getSSLSession()
                            .getPeerCertificates();
                    context.setAttribute(PEER_CERT_ATTRIBUTE, certificates);
                }
                return;
            }

            throw new RuntimeException("Unexpected HTTP_CONNECTION: " + unTypedHttpConnection.toString());
        }
    });
    HttpContext httpContext = new BasicHttpContext();
    HttpUriRequest httpUriRequest = new HttpGet("/");
    org.apache.http.HttpResponse apacheHttpResponse = httpClient.execute(httpUriRequest, httpContext);
    java.security.cert.Certificate[] certificates = (java.security.cert.Certificate[]) httpContext
            .getAttribute(PEER_CERT_ATTRIBUTE);
    // TODO: Where is it written that the last cert is the server's root cert? Are certs guaranteed to be returned in order from leaf to root?
    return certificates[certificates.length - 1].getPublicKey();
}

From source file:com.predic8.membrane.test.AssertUtils.java

private static DefaultHttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    DefaultHttpClient hc = new DefaultHttpClient();
    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.update(new BasicScheme(), creds);
                }/*from   ww  w  .ja v  a2s. c om*/
            }
        }
    };
    hc.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    hc.setCredentialsProvider(bcp);
    hc.setCookieStore(new BasicCookieStore());
    return hc;
}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

private static DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url, String username,
        String password) throws HttpException, IOException {
    HttpHost targetHost = new HttpHost(url);
    final UsernamePasswordCredentials access = new UsernamePasswordCredentials(username, password);

    httpclient.getCredentialsProvider()//w w w. ja v  a2  s. c om
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(access);
            }
        }
    }, 0);
    return httpclient;
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static Socket newSocket(final HttpContext context) throws IOException {
    InetSocketAddress proxySocks = (InetSocketAddress) context.getAttribute("proxy.socks.address");
    Socket socket;/*from www.  j ava 2  s.com*/
    if (proxySocks != null) {
        socket = new Socket(new Proxy(Proxy.Type.SOCKS, proxySocks));
    } else {
        socket = new Socket();
    }
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    return socket;
}

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

public static String getLatestRedirectedUrl(final HttpContext httpContext) {
    final HttpRequest request = (HttpRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    final HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final String requestUri = host.getSchemeName() + "://" + host.getHostName()
            + (host.getPort() <= 0 ? "" : ":" + host.getPort()) + request.getRequestLine().getUri();
    return requestUri;
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

private static void updateOpMonitoringData(HttpContext context, SocketInfo socketInfo) {
    try {/*from w w w  .  ja va  2 s  .  c o m*/
        OpMonitoringData opMonitoringData = (OpMonitoringData) context
                .getAttribute(OpMonitoringData.class.getName());

        if (opMonitoringData != null) {
            opMonitoringData.setServiceSecurityServerAddress(socketInfo.getUri().getHost());
        }
    } catch (Exception e) {
        log.error("Failed to assign op monitoring data field {}",
                OpMonitoringData.SERVICE_SECURITY_SERVER_ADDRESS, e);
    }
}

From source file:org.opendatakit.briefcase.util.WebUtils.java

public static final void clearAllCredentials(HttpContext localContext) {
    CredentialsProvider credsProvider = (CredentialsProvider) localContext
            .getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider != null) {
        credsProvider.clear();/*  w  w  w .  j av a2s.com*/
    }
}

From source file:org.opendatakit.briefcase.util.WebUtils.java

private static final void addCredentials(HttpContext localContext, Credentials c, String host) {
    CredentialsProvider credsProvider = (CredentialsProvider) localContext
            .getAttribute(ClientContext.CREDS_PROVIDER);

    List<AuthScope> asList = buildAuthScopes(host);
    for (AuthScope a : asList) {
        credsProvider.setCredentials(a, c);
    }/*from w w  w.java 2s .  com*/
}