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:github.madmarty.madsonic.service.RESTMusicService.java

private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) {
    HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // Sometimes the request doesn't contain the "http://host" part
    String redirectedUrl;/*from  w w  w . ja  va  2 s  .  co  m*/
    if (request.getURI().getScheme() == null) {
        redirectedUrl = host.toURI() + request.getURI();
    } else {
        redirectedUrl = request.getURI().toString();
    }

    redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/"));
    redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/"));

    Log.i(TAG, redirectFrom + " redirects to " + redirectTo);
    redirectionLastChecked = System.currentTimeMillis();
    redirectionNetworkType = getCurrentNetworkType(context);
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java

private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) {
    HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // Sometimes the request doesn't contain the "http://host" part so we
    // must take from the HttpHost object.
    String redirectedUrl;/*from   w  ww .j  a  v  a  2 s .  c  o  m*/
    if (request.getURI().getScheme() == null) {
        redirectedUrl = host.toURI() + request.getURI();
    } else {
        redirectedUrl = request.getURI().toString();
    }

    redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/"));
    redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/"));

    LOG.info(redirectFrom + " redirects to " + redirectTo);
    redirectionLastChecked = System.currentTimeMillis();
    redirectionNetworkType = getCurrentNetworkType(context);
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

/**
 * HTTPHttpClient<br>//from  www.  j a  v a 2  s. c  om
 * 'http.connection'HttpConnection? ?
 * 'http.target_host'HttpHost ?
 * 'http.proxy_host'HttpHost? ?
 * 'http.request'HttpRequestHTTP ?
 * 'http.response'HttpResponseHTTP? ?
 * 'http.request_sent'java.lang.Boolean??
 * 
 * @throws Exception
 */
@Test
@SuppressWarnings("deprecation")
public void testHttpContext() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // httpContext ?httpClienthttp?
    HttpContext httpContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(URL1);

    HttpResponse response = httpclient.execute(httpGet, httpContext);

    ManagedClientConnection connection = (ManagedClientConnection) httpContext
            .getAttribute(ExecutionContext.HTTP_CONNECTION);
    System.out.println("LocalAddr ==> " + connection.getLocalAddress().getHostAddress());
    System.out.println("LocalPort ==> " + connection.getLocalPort());
    System.out.println("RemoteAddr ==> " + connection.getRemoteAddress().getHostAddress());
    System.out.println("RemotePort ==> " + connection.getRemotePort());
    System.out.println("isOpen ==> " + connection.isOpen());
    System.out.println("isSecure ==> " + connection.isSecure());
    System.out.println("isStale ==> " + connection.isStale());

    HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    System.out.println(targetHost.toURI());

    // HttpHost proxyHost = (HttpHost) httpContext
    // .getAttribute(ExecutionContext.HTTP_PROXY_HOST);

    // ??
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        String content = parseEntity(entity);
        System.out.println(content);
        // ?
        entity.consumeContent();
    }

    connection.abortConnection();
    connection.shutdown();

}

From source file:org.openqa.selenium.remote.internal.ApacheHttpAsyncClient.java

/** Same implementation as {@link ApacheHttpClient#createResponse(org.apache.http.HttpResponse, HttpContext)} */
private HttpResponse createResponse(org.apache.http.HttpResponse response, HttpContext context)
        throws IOException {
    HttpResponse internalResponse = new HttpResponse();

    internalResponse.setStatus(response.getStatusLine().getStatusCode());
    for (Header header : response.getAllHeaders()) {
        for (HeaderElement headerElement : header.getElements()) {
            internalResponse.addHeader(header.getName(), headerElement.getValue());
        }/*from w  w w .j ava 2 s. co m*/
    }

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            internalResponse.setContent(EntityUtils.toByteArray(entity));
        } finally {
            EntityUtils.consume(entity);
        }
    }

    Object host = context.getAttribute(HTTP_TARGET_HOST);
    if (host instanceof HttpHost) {
        internalResponse.setTargetHost(((HttpHost) host).toURI());
    }

    return internalResponse;
}

From source file:org.apache.olingo.samples.client.core.http.RequestRetryHttpClientFactory.java

@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
    final HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        @Override//from   ww  w .  j a va2s  .co  m
        public boolean retryRequest(final IOException exception, final int executionCount,
                final HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent 
                return true;
            }
            return false;
        }

    };

    final DefaultHttpClient httpClient = super.create(method, uri);
    httpClient.setHttpRequestRetryHandler(myRetryHandler);
    return httpClient;
}

From source file:at.ac.tuwien.big.testsuite.impl.util.HttpClientProducer.java

@Produces
@ApplicationScoped/*from  w  w  w. ja va2  s . c om*/
HttpClient produceHttpClient() {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(100);
    cm.setDefaultMaxPerRoute(20);
    DefaultHttpClient client = new DefaultHttpClient(cm);

    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_RETRY_COUNT) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return true;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return true;
            }
            if (exception instanceof ConnectException) {
                // Connection refused
                return true;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return true;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent 
                return true;
            }
            return false;
        }
    });

    return new DecompressingHttpClient(client);
}

From source file:io.mandrel.requests.http.ApacheHttpRequester.java

public Blob extractWebPage(Uri uri, CloseableHttpResponse result, HttpContext localContext)
        throws MalformedURLException, IOException {
    try {/*from   w  w  w.ja va2  s.c  o  m*/
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        if (result.getAllHeaders() != null) {
            for (Header header : result.getAllHeaders()) {
                headers.put(header.getName(), Arrays.asList(header.getValue()));
            }
        }

        List<io.mandrel.requests.http.Cookie> cookies = null;
        if (localContext != null) {
            CookieStore store = (CookieStore) localContext.getAttribute(HttpClientContext.COOKIE_STORE);
            if (store.getCookies() != null) {
                cookies = store.getCookies().stream().filter(cookie -> cookie != null)
                        .map(cookie -> new io.mandrel.requests.http.Cookie(cookie.getName(), cookie.getValue(),
                                cookie.getDomain(), cookie.getPath(),
                                cookie.getExpiryDate() != null ? cookie.getExpiryDate().getTime() : 0,
                                cookie.getExpiryDate() != null ? (int) cookie.getExpiryDate().getTime() : 0,
                                cookie.isSecure(), false))
                        .collect(Collectors.toList());
            }
        }

        HttpFetchMetadata metadata = new HttpFetchMetadata().headers(headers).cookies(cookies);
        metadata.setUri(uri)
                .setStatusCode(result.getStatusLine() != null ? result.getStatusLine().getStatusCode() : 0)
                .setStatusText(
                        result.getStatusLine() != null ? result.getStatusLine().getReasonPhrase() : null);

        HttpEntity entity = result.getEntity();
        InputStream content = entity.getContent();
        try {
            long contentLength = entity.getContentLength();
            Blob blob = new Blob(new BlobMetadata().setUri(uri)
                    .setSize(contentLength < 0 ? null : contentLength).setFetchMetadata(metadata))
                            .payload(IOUtils.toByteArray(content));
            return blob;
        } catch (IOException ex) {
            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;
        } finally {
            // Closing the input stream will trigger connection release
            content.close();
        }
    } finally {
        result.close();
    }
}

From source file:x.y.z.DefaultRequestDirector.java

protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
            final HttpContext context) throws HttpException, IOException {
        test();//from w w  w.  ja v  a 2s  . c o  m
        String something = new String();
        String somethingElse = "";
        List<Something> somethingList = null;
        test(something);
        final HttpRoute route = roureq.getRoute();
        final RequestWrapper request = roureq.getRequest();
        final HttpParams params = request.getParams();
        int i = org.apache.http.params.HttpConnectionParams.getConnectionTimeout(parmas);
        javax.rmi.CORBA obj;
        if (HttpClientParams.isAuthenticating(params)) {
            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }
            if (target.getPort() < 0) {
                final Scheme scheme = connManager.getSchemeRegistry().getScheme(target);
                target = new HttpHost(target.getHostName(), scheme.getDefaultPort(), target.getSchemeName());
            }
            final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(target, response,
                    this.targetAuthStrategy, targetAuthState, context);
            HttpHost proxy = route.getProxyHost();
            if (proxy == null) {
                proxy = route.getTargetHost();
            }
            final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested(proxy, response,
                    this.proxyAuthStrategy, proxyAuthState, context);
            if (targetAuthRequested) {
                if (this.authenticator.authenticate(target, response, this.targetAuthStrategy, this.targetAuthState,
                        context)) {
                    return roureq;
                }
            }
            if (proxyAuthRequested) {
                if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy, this.proxyAuthState,
                        context)) {
                    return roureq;
                }
            }
        }
        if (HttpClientParams.isRedirecting(params)
                && this.redirectStrategy.isRedirected(request, response, context)) {
            if (redirectCount >= maxRedirects) {
                throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
            }
            redirectCount++;
            virtualHost = null;
            final HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
            final HttpRequest orig = request.getOriginal();
            redirect.setHeaders(orig.getAllHeaders());
            final URI uri = redirect.getURI();
            final HttpHost newTarget = URIUtils.extractHost(uri);
            if (newTarget == null) {
                throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
            }
            if (!route.getTargetHost().equals(newTarget)) {
                this.log.debug("Resetting target auth state");
                targetAuthState.reset();
                final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                if (authScheme != null && authScheme.isConnectionBased()) {
                    this.log.debug("Resetting proxy auth state");
                    proxyAuthState.reset();
                }
            }
            final RequestWrapper wrapper = wrapRequest(redirect);
            wrapper.setParams(params);
            final HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
            final RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
            }
            return newRequest;
        }
        return null;
    }

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.JBossNegotiateScheme.java

/**
 * Produces Negotiate authorization Header based on token created by processChallenge.
 * //from w  ww .  j  av  a2  s .c o m
 * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
 *        from JAAS will be used instead.
 * @param request The request being authenticated
 * 
 * @throws AuthenticationException if authorisation string cannot be generated due to an authentication failure
 * 
 * @return an Negotiate authorisation Header
 */
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = null;
        if (isProxy()) {
            key = ExecutionContext.HTTP_PROXY_HOST;
        } else {
            key = ExecutionContext.HTTP_TARGET_HOST;
        }
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }

        if (log.isDebugEnabled()) {
            log.debug("init " + authServer);
        }
        /*
         * Using the SPNEGO OID is the correct method. Kerberos v5 works for IIS but not JBoss. Unwrapping the initial token
         * when using SPNEGO OID looks like what is described here...
         * 
         * http://msdn.microsoft.com/en-us/library/ms995330.aspx
         * 
         * Another helpful URL...
         * 
         * http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/
         * tsec_SPNEGO_token.html
         * 
         * Unfortunately SPNEGO is JRE >=1.6.
         */

        /** Try SPNEGO by default, fall back to Kerberos later if error */
        negotiationOid = new Oid(SPNEGO_OID);

        boolean tryKerberos = false;
        try {
            GSSManager manager = getManager();
            GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
            gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null,
                    DEFAULT_LIFETIME);
            gssContext.requestMutualAuth(true);
            gssContext.requestCredDeleg(true);
        } catch (GSSException ex) {
            // BAD MECH means we are likely to be using 1.5, fall back to Kerberos MECH.
            // Rethrow any other exception.
            if (ex.getMajor() == GSSException.BAD_MECH) {
                log.debug("GSSException BAD_MECH, retry with Kerberos MECH");
                tryKerberos = true;
            } else {
                throw ex;
            }

        }
        if (tryKerberos) {
            /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */
            log.debug("Using Kerberos MECH " + KERBEROS_OID);
            negotiationOid = new Oid(KERBEROS_OID);
            GSSManager manager = getManager();
            GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
            gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null,
                    DEFAULT_LIFETIME);
            gssContext.requestMutualAuth(true);
            gssContext.requestCredDeleg(true);
        }
        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }

        /*
         * IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish? seem to only accept SPNEGO. Below
         * wraps Kerberos into SPNEGO token.
         */
        if (spengoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) {
            token = spengoGenerator.generateSpnegoDERObject(token);
        }

        state = State.TOKEN_GENERATED;
        String tokenstr = new String(Base64.encodeBase64(token, false));
        if (log.isDebugEnabled()) {
            log.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        return new BasicHeader("Authorization", "Negotiate " + tokenstr);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    } catch (IOException ex) {
        state = State.FAILED;
        throw new AuthenticationException(ex.getMessage());
    }
}

From source file:org.jasig.portlet.proxy.service.web.HttpContentServiceImpl.java

public GenericContentResponseImpl getContent(HttpContentRequestImpl proxyRequest, PortletRequest request,
        boolean runWrapperMethods) {
    try {//  www.ja  v a2 s .c o m

        // get an HttpClient appropriate for this user and portlet instance
        // and set any basic auth credentials, if applicable
        final AbstractHttpClient httpclient = httpClientService.getHttpClient(request);

        // create the request
        final HttpUriRequest httpRequest = getHttpRequest(proxyRequest, request);
        if (log.isTraceEnabled()) {
            log.trace("Proxying " + httpRequest.getURI() + " via " + httpRequest.getMethod());
        }

        // execute the request
        final HttpContext context = new BasicHttpContext();
        final HttpResponse response = httpclient.execute(httpRequest, context);
        final HttpEntity entity = response.getEntity();

        // create the response object and set the content stream
        final HttpContentResponseImpl proxyResponse = new HttpContentResponseImpl(entity);
        proxyResponse.setContent(entity.getContent());

        // add each response header to our response object
        for (Header header : response.getAllHeaders()) {
            proxyResponse.getHeaders().put(header.getName(), header.getValue());
        }

        // set the final URL of the response in case it was redirected
        String finalUrl = (String) context.getAttribute(RedirectTrackingResponseInterceptor.FINAL_URL_KEY);
        if (finalUrl == null) {
            finalUrl = proxyRequest.getProxiedLocation();
        }
        proxyResponse.setProxiedLocation(finalUrl);

        return proxyResponse;

    } catch (ClientProtocolException e) {
        log.error("Exception retrieving remote content", e);
    } catch (IOException e) {
        log.error("Exception retrieving remote content", e);
    }

    return null;
}