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.hardincoding.sonar.subsonic.service.SubsonicMusicService.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   ww  w  .  j a v  a2  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:ch.cyberduck.core.http.HttpSession.java

protected void configure(final AbstractHttpClient client) {
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override//  w  ww .j  a va2 s  . c o  m
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            log(true, request.getRequestLine().toString());
            for (Header header : request.getAllHeaders()) {
                log(true, header.toString());
            }
            domain = ((HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST)).getHostName();
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            log(false, response.getStatusLine().toString());
            for (Header header : response.getAllHeaders()) {
                log(false, header.toString());
            }
        }
    });
    if (Preferences.instance().getBoolean("http.compression.enable")) {
        client.addRequestInterceptor(new RequestAcceptEncoding());
        client.addResponseInterceptor(new ResponseContentEncoding());
    }
}

From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java

private URI buildUri(HttpContext context, String location) throws URISyntaxException {
    URI uri;//  w w  w . ja  v a 2  s  .c  o m
    uri = new URI(location);
    if (!uri.isAbsolute()) {
        HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        uri = new URI(host.toURI() + location);
    }
    return uri;
}

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

public boolean needAuthentication(final HttpRoute route, final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {
    final AuthState targetAuthState = getTargetAuthState(context);
    final AuthState proxyAuthState = getProxyAuthState(context);
    HttpHost target = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    if (target == null) {
        target = route.getTargetHost();/*from  www  .  j  ava  2 s  .  co  m*/
    }
    HttpHost proxy = route.getProxyHost();
    if (this.needAuthentication(target, proxy, targetAuthState, proxyAuthState, response, context)) {
        // discard previous auth headers
        request.removeHeaders(AUTH.WWW_AUTH_RESP);
        request.removeHeaders(AUTH.PROXY_AUTH_RESP);
        return true;
    } else {
        return false;
    }
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

/**
 * Triggered when the connection is ready to send an HTTP request.
 *
 * @see NHttpClientConnection// ww w.j a  v  a  2s.  c om
 *
 * @param conn HTTP connection that is ready to send an HTTP request
 */
public void requestReady(final NHttpClientConnection conn) {
    System.out.println(conn + " [proxy->origin] request ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    // TODO: change it to ReentrantLock
    synchronized (proxyTask) {
        if (requestReadyValidateConnectionState(proxyTask))
            return;

        HttpRequest request = proxyTask.getRequest();
        if (request == null) {
            throw new IllegalStateException("HTTP request is null");
        }

        requestReadyCleanUpHeaders(request);

        HttpHost targetHost = proxyTask.getTarget();

        try {

            request.setParams(new DefaultedHttpParams(request.getParams(), this.params));

            // Pre-process HTTP request
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);

            this.httpProcessor.process(request, context);
            // and send it to the origin server
            Request originalRequest = proxyTask.getOriginalRequest();
            int length = originalRequest.getContentLength();
            if (length > 0) {
                BasicHttpEntity httpEntity = new BasicHttpEntity();
                httpEntity.setContentLength(originalRequest.getContentLengthLong());
                /*
                          httpEntity.setContent(((InternalInputBuffer) originalRequest.getInputBuffer()).getInputStream());
                          ((BasicHttpEntityEnclosingRequest) request).setEntity(httpEntity);
                */
            }
            conn.submitRequest(request);
            // Update connection state
            proxyTask.setOriginState(ConnState.REQUEST_SENT);

            System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString());

        } catch (IOException ex) {
            shutdownConnection(conn);
        } catch (HttpException ex) {
            shutdownConnection(conn);
        }

    }
}

From source file:com.soulgalore.crawler.core.impl.HTTPClientResponseFetcher.java

public HTMLPageResponse get(CrawlerURL url, boolean getPage, Map<String, String> requestHeaders,
        boolean followRedirectsToNewDomain) {

    if (url.isWrongSyntax()) {
        return new HTMLPageResponse(url, StatusCode.SC_MALFORMED_URI.getCode(),
                Collections.<String, String>emptyMap(), "", "", 0, "", 0);
    }//  w w  w  .ja v a2  s .c o m

    final HttpGet get = new HttpGet(url.getUri());

    for (String key : requestHeaders.keySet()) {
        get.setHeader(key, requestHeaders.get(key));
    }

    HttpEntity entity = null;
    final long start = System.currentTimeMillis();

    try {

        HttpContext localContext = new BasicHttpContext();
        final HttpResponse resp = httpClient.execute(get, localContext);

        final long fetchTime = System.currentTimeMillis() - start;

        // Get the last URL in the redirect chain
        final HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        final HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        // Fix when using proxy, relative URI (no proxy used)
        String newURL;
        if (req.getURI().toString().startsWith("http")) {
            newURL = req.getURI().toString();
        } else {
            newURL = target + req.getURI().toString();
        }

        entity = resp.getEntity();

        // this is a hack to minimize the amount of memory used
        // should make this configurable maybe
        // don't fetch headers for request that don't fetch the body and
        // response isn't 200
        // these headers will not be shown in the results
        final Map<String, String> headersAndValues = getPage
                || !StatusCode.isResponseCodeOk(resp.getStatusLine().getStatusCode()) ? getHeaders(resp)
                        : Collections.<String, String>emptyMap();

        final String encoding = entity.getContentEncoding() != null ? entity.getContentEncoding().getValue()
                : "";

        final String body = getPage ? getBody(entity, "".equals(encoding) ? "UTF-8" : encoding) : "";
        final long size = entity.getContentLength();
        // TODO add log when null
        final String type = (entity.getContentType() != null) ? entity.getContentType().getValue() : "";
        final int sc = resp.getStatusLine().getStatusCode();
        EntityUtils.consume(entity);

        // If we want to only collect only URLS that don't redirect to a new domain
        // This solves the problem with local links like:
        // http://www.peterhedenskog.com/facebook that redirects to http://www.facebook.com/u/peter.hedenskog
        // TODO the host check can be done better :)
        if (!followRedirectsToNewDomain && !newURL.contains(url.getHost())) {
            return new HTMLPageResponse(url, StatusCode.SC_SERVER_REDIRECT_TO_NEW_DOMAIN.getCode(),
                    Collections.<String, String>emptyMap(), "", "", 0, "", fetchTime);
        }
        return new HTMLPageResponse(
                !url.getUrl().equals(newURL) ? new CrawlerURL(newURL, url.getReferer()) : url, sc,
                headersAndValues, body, encoding, size, type, fetchTime);

    } catch (SocketTimeoutException e) {
        System.err.println(e);
        return new HTMLPageResponse(url, StatusCode.SC_SERVER_RESPONSE_TIMEOUT.getCode(),
                Collections.<String, String>emptyMap(), "", "", 0, "", System.currentTimeMillis() - start);
    }

    catch (ConnectTimeoutException e) {
        System.err.println(e);
        return new HTMLPageResponse(url, StatusCode.SC_SERVER_RESPONSE_TIMEOUT.getCode(),
                Collections.<String, String>emptyMap(), "", "", 0, "", System.currentTimeMillis() - start);
    }

    catch (IOException e) {
        System.err.println(e);
        return new HTMLPageResponse(url, StatusCode.SC_SERVER_RESPONSE_UNKNOWN.getCode(),
                Collections.<String, String>emptyMap(), "", "", 0, "", -1);
    } finally {
        get.releaseConnection();
    }

}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
    System.out.println(conn + " [proxy->origin] output ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.REQUEST_SENT && connState != ConnState.REQUEST_BODY_STREAM) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }/*from  ww w.  j  a va  2 s  . c om*/

        try {

            // TODO: propper handling of POST
            ByteBuffer src = proxyTask.getInBuffer();
            final int srcSize = src.limit();
            if (src.position() != 0) {
                System.out.println(conn + " [proxy->origin] buff not consumed yet");
                return;
            }
            ByteChunk chunk = new ByteChunk(srcSize);
            Request originalRequest = proxyTask.getOriginalRequest();
            int read;
            int encRead = 0;
            long bytesWritten = 0;
            while ((read = originalRequest.doRead(chunk)) != -1) {
                System.out.println(conn + " [proxy->origin] " + read + " bytes read");
                if (read > srcSize) {
                    src = ByteBuffer.wrap(chunk.getBytes(), chunk.getOffset(), read);
                } else {
                    src.put(chunk.getBytes(), chunk.getOffset(), read);
                }
                src.flip();
                encRead = encoder.write(src);
                bytesWritten += encRead;
                src.compact();
                chunk.reset();
                if (encRead == 0) {
                    System.out.println(conn + " [proxy->origin] encoder refused to consume more");
                    break;
                } else {
                    System.out.println(conn + " [proxy->origin] " + encRead + " consumed by encoder");
                }
            }
            System.out.println(conn + " [proxy->origin] " + bytesWritten + " bytes written");
            System.out.println(conn + " [proxy->origin] " + encoder);
            src.compact();

            if (src.position() == 0 && encRead != 0) {
                encoder.complete();
            }
            // Update connection state
            if (encoder.isCompleted()) {
                System.out.println(conn + " [proxy->origin] request body sent");
                proxyTask.setOriginState(ConnState.REQUEST_BODY_DONE);
            } else {
                proxyTask.setOriginState(ConnState.REQUEST_BODY_STREAM);
            }

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void responseReceived(final NHttpClientConnection conn) {
    System.out.println(conn + " [proxy<-origin] response received");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.REQUEST_SENT && connState != ConnState.REQUEST_BODY_DONE) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }/*ww w  .  j a  v a 2  s.  c o m*/

        HttpResponse response = conn.getHttpResponse();
        HttpRequest request = proxyTask.getRequest();

        StatusLine line = response.getStatusLine();
        System.out.println(conn + " [proxy<-origin] << " + line);

        int statusCode = line.getStatusCode();
        if (statusCode < HttpStatus.SC_OK) {
            // Ignore 1xx response, TODO: are you sure?
            return;
        }
        try {

            // Update connection state
            final Response clientResponse = proxyTask.getResponse();

            proxyTask.setOriginState(ConnState.RESPONSE_RECEIVED);

            clientResponse.setStatus(statusCode);
            clientResponse.setMessage(line.getReasonPhrase());
            for (Header header : response.getAllHeaders()) {
                clientResponse.setHeader(header.getName(), header.getValue());
            }

            if (!canResponseHaveBody(request, response)) {
                conn.resetInput();
                if (!this.connStrategy.keepAlive(response, context)) {
                    System.out.println(conn + " [proxy<-origin] close connection");
                    proxyTask.setOriginState(ConnState.CLOSING);
                    conn.close();
                }
                proxyTask.getCompletion().run();
            } else {
                final HttpEntity httpEntity = response.getEntity();
                if (httpEntity.isStreaming()) {
                    final InputStream is = httpEntity.getContent();
                    ByteChunk bc = new ByteChunk(1024);
                    while (is.read(bc.getBytes()) != -1) {
                        clientResponse.doWrite(bc);
                    }
                }
            }
            /*
                    // Make sure client output is active
                    proxyTask.getClientIOControl().requestOutput();
            */

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }

}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
    System.out.println(conn + " [proxy<-origin] input ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.RESPONSE_RECEIVED && connState != ConnState.RESPONSE_BODY_STREAM) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }/*from  w  w w  .j av  a  2  s  .co m*/

        final Response response = proxyTask.getResponse();
        try {

            ByteBuffer dst = proxyTask.getOutBuffer();
            int bytesRead = decoder.read(dst);
            if (bytesRead > 0) {
                dst.flip();
                final ByteChunk chunk = new ByteChunk(bytesRead);
                final byte[] buf = new byte[bytesRead];
                dst.get(buf);
                chunk.setBytes(buf, 0, bytesRead);
                dst.compact();
                try {
                    response.doWrite(chunk);
                } catch (ClassCastException e) {
                    System.err.println("gone bad: " + e.getMessage());
                    e.printStackTrace(System.err);
                }
                response.flush();
                System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read");
                System.out.println(conn + " [proxy<-origin] " + decoder);
            }
            if (!dst.hasRemaining()) {
                // Output buffer is full. Suspend origin input until
                // the client handler frees up some space in the buffer
                conn.suspendInput();
            }
            /*
                    // If there is some content in the buffer make sure client output
                    // is active
                    if (dst.position() > 0) {
                      proxyTask.getClientIOControl().requestOutput();
                    }
            */

            if (decoder.isCompleted()) {
                System.out.println(conn + " [proxy<-origin] response body received");
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE);
                if (!this.connStrategy.keepAlive(conn.getHttpResponse(), context)) {
                    System.out.println(conn + " [proxy<-origin] close connection");
                    proxyTask.setOriginState(ConnState.CLOSING);
                    conn.close();
                }
                proxyTask.getCompletion().run();
            } else {
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM);
            }

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }
}

From source file:org.everit.authentication.http.session.ecm.tests.SessionAuthenticationComponentTest.java

private void logoutGet(final HttpContext httpContext) throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(logoutUrl);
    HttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatusLine().getStatusCode());

    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString()
            : (currentHost.toURI() + currentReq.getURI());
    Assert.assertEquals(loggedOutUrl, currentUrl);
}