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:com.rightscale.provider.rest.DashboardSession.java

private HttpRequestInterceptor createBasicAuthInterceptor() {
    return 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);
                }/*  w  w  w  .ja  v a  2s . c om*/
            }
        }
    };
}

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

private AuthState getProxyAuthState(final HttpContext context) {
    AuthState proxyAuthState = (AuthState) context.getAttribute(HttpClientContext.PROXY_AUTH_STATE);
    if (proxyAuthState == null) {
        proxyAuthState = new AuthState();
        context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);
    }/*www .  j a  v a2  s .  c  om*/
    return proxyAuthState;
}

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

private AuthState getTargetAuthState(final HttpContext context) {
    AuthState targetAuthState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
    if (targetAuthState == null) {
        targetAuthState = new AuthState();
        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState);
    }//  ww w.ja  v a2 s. c  om
    return targetAuthState;
}

From source file:z.hol.net.http.entity.compress.ResponseGzipCompress.java

public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }//ww w. j  av  a  2 s. com
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        Header aeheader = request.getFirstHeader(ACCEPT_ENCODING);
        if (aeheader != null) {
            HeaderElement[] codecs = aeheader.getElements();
            for (int i = 0; i < codecs.length; i++) {
                if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) {
                    response.setEntity(new GzipCompressingEntity(entity));
                    return;
                }
            }
        }
    }
}

From source file:com.gistlabs.mechanize.impl.MechanizeAgent.java

protected HttpResponse execute(final HttpClient client, final HttpRequestBase request) throws Exception {
    HttpContext context = new BasicHttpContext();
    HttpResponse response = requestChain.execute(request, context);

    if (context.getAttribute("Location") != null)
        response.setHeader(MECHANIZE_LOCATION, (String) context.getAttribute("Location"));

    response.setEntity(new BufferedHttpEntity(response.getEntity()));

    return response;
}

From source file:fr.univsavoie.ltp.client.LoginActivity.java

/**
 * Pav de code permetant de se connecter de faon scuris au serveur
 *///from   ww  w . j av a 2s . c o m
private void auth() {
    try {
        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.getText().toString(),
                password.getText().toString());
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (Exception e) {
        Log.e("Catch", "Auth: " + e.getLocalizedMessage());
    }
}

From source file:org.aludratest.service.gui.web.selenium.httpproxy.RequestProcessorThread.java

/** The {@link Thread}'s worker method which processes the request. */
@Override//from w  w w .j a v a2 s.c o  m
public void run() {
    LOGGER.debug("New request processor thread");

    // Create context and bind connection objects to the execution context
    HttpContext context = new BasicHttpContext(null);
    context.setAttribute(HTTP_IN_CONN, this.inconn);
    context.setAttribute(HTTP_OUT_CONN, this.outconn);

    // checking request's keep-alive attribute
    Boolean keepAliveObj = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
    boolean keepAlive = (keepAliveObj != null && keepAliveObj.booleanValue());

    // handle in/out character transfer according to keep-alive setting
    try {
        while (!Thread.interrupted()) {
            if (!this.inconn.isOpen()) {
                this.outconn.close();
                break;
            }
            LOGGER.debug("Handling request");

            this.httpservice.handleRequest(this.inconn, context);

            if (!keepAlive) {
                this.outconn.close();
                this.inconn.close();
                LOGGER.debug("Finishing request");
                break;
            }
        }
    } catch (ConnectionClosedException ex) {
        if (keepAlive && owner.isRunning()) {
            LOGGER.error("Client closed connection");
        } else {
            LOGGER.debug("Client closed connection");
        }
    } catch (IOException ex) {
        LOGGER.error("I/O error: " + ex.getMessage());
    } catch (HttpException ex) {
        LOGGER.error("Unrecoverable HTTP protocol violation: " + ex.getMessage());
    } finally {
        try {
            this.inconn.shutdown();
        } catch (IOException ignore) {
            // ignore possible exceptions
        }
        try {
            this.outconn.shutdown();
        } catch (IOException ignore) {
            // ignore possible exceptions
        }
        LOGGER.debug("Finished connection thread");
    }
}

From source file:org.wildfly.camel.test.olingo4.Olingo4IntegrationTest.java

private String getRealServiceUrl(String baseUrl) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpContext httpContext = new BasicHttpContext();
    httpclient.execute(httpGet, httpContext);
    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString()
            : (currentHost.toURI() + currentReq.getURI());

    return currentUrl;
}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {

    final X509Credential credential = (X509Credential) context
            .getAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS);
    if (credential == null) {
        throw new IOException("Client credentials are missing from context.");
    }/*from   ww w .  jav  a  2  s  . c om*/
    final SSLContext sslContext;
    try {
        sslContext = contextProvider.getContext(credential);
    } catch (GeneralSecurityException e) {
        throw new IOException("Failed to create SSLContext: " + e.getMessage(), e);
    }
    final SSLSocket sslsock = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, target, port,
            true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Enabled protocols: {}", Arrays.asList(sslsock.getEnabledProtocols()));
        LOGGER.debug("Enabled cipher suites: {}", Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    LOGGER.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:org.robam.xutils.http.client.RetryHandler.java

/**
 * @param exception//from   ww w . j ava2 s.c o m
 * @param retriedTimes
 * @param context      HTTP,??,ActivityContext
 * @return
 */
@Override
public boolean retryRequest(IOException exception, int retriedTimes, HttpContext context) {
    boolean retry = true;

    if (exception == null || context == null) {
        return false;
    }

    // ?????,?,True
    Object isReqSent = context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = isReqSent == null ? false : (Boolean) isReqSent;

    // ???
    if (retriedTimes > maxRetries) {
        // ??,
        retry = false;
    } else if (exceptionBlackList.contains(exception.getClass())) {
        // ?BlackList???.
        retry = false;
    } else if (exceptionWhiteList.contains(exception.getClass())) {
        // ?????.
        retry = true;
    } else if (!sent) {
        // ??
        retry = true;
    }

    if (retry) {
        try {
            Object currRequest = context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (currRequest != null) {
                if (currRequest instanceof HttpRequestBase) {
                    // ???GET?retry,?GET,??
                    HttpRequestBase requestBase = (HttpRequestBase) currRequest;
                    retry = "GET".equals(requestBase.getMethod());
                } else if (currRequest instanceof RequestWrapper) {
                    RequestWrapper requestWrapper = (RequestWrapper) currRequest;
                    retry = "GET".equals(requestWrapper.getMethod());
                }
            } else {
                retry = false;
                LogUtils.e("retry error, curr request is null");
            }
        } catch (Throwable e) {
            retry = false;
            LogUtils.e("retry error", e);
        }
    }

    if (retry) {
        // sleep a while and retry http request again.
        SystemClock.sleep(RETRY_SLEEP_INTERVAL);
    }

    return retry;
}