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

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

Introduction

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

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:cn.com.loopj.android.http.MyRedirectHandler.java

@Override
public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }//from w w w. j  a v  a 2s.  c  om
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    //HERE IS THE MODIFIED LINE OF CODE
    String location = locationHeader.getValue().replaceAll(" ", "%20");

    URI uri;
    try {
        uri = new URI(location);
    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }

        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

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

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*from   w w w  .ja  v  a  2s .  co m*/
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri;
    try {
        uri = new URI(location);
    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }

        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:org.apache.synapse.transport.nhttp.ClientHandler.java

/**
 * Perform processing of the received response though Axis2
 *
 * @param conn HTTP connection to be processed
 * @param context HTTP context associated with the connection
 * @param response HTTP response associated with the connection
 *///from  w  ww .java2 s  .co m
private void processResponse(final NHttpClientConnection conn, HttpContext context, HttpResponse response) {

    ContentInputBuffer inputBuffer = null;
    MessageContext outMsgContext = (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT);
    String endptPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX);
    String requestMethod = (String) context.getAttribute(NhttpConstants.HTTP_REQ_METHOD);
    int statusCode = response.getStatusLine().getStatusCode();

    boolean expectEntityBody = false;
    if (!"HEAD".equals(requestMethod) && !"OPTIONS".equals(requestMethod) && statusCode >= HttpStatus.SC_OK
            && statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_NOT_MODIFIED
            && statusCode != HttpStatus.SC_RESET_CONTENT) {
        expectEntityBody = true;
    } else if (NhttpConstants.HTTP_HEAD.equals(requestMethod)) {
        // When invoking http HEAD request esb set content length as 0 to response header. Since there is no message
        // body content length cannot be calculated inside synapse. Hence additional two headers are added to
        // which contains content length of the backend response and the request method. These headers are removed
        // before submitting the actual response.
        response.addHeader(NhttpConstants.HTTP_REQUEST_METHOD, requestMethod);

        if (response.getFirstHeader(HTTP.CONTENT_LEN) != null) {
            response.addHeader(NhttpConstants.ORIGINAL_CONTENT_LEN,
                    response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
        }
    }

    if (expectEntityBody) {
        inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator);
        context.setAttribute(RESPONSE_SINK_BUFFER, inputBuffer);

        BasicHttpEntity entity = new BasicHttpEntity();
        if (response.getStatusLine().getProtocolVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);

    } else {
        conn.resetInput();
        conn.resetOutput();

        if (context.getAttribute(NhttpConstants.DISCARD_ON_COMPLETE) != null
                || !connStrategy.keepAlive(response, context)) {
            try {
                // this is a connection we should not re-use
                connpool.forget(conn);
                shutdownConnection(conn, false, null);
                context.removeAttribute(RESPONSE_SINK_BUFFER);
                context.removeAttribute(REQUEST_SOURCE_BUFFER);
            } catch (Exception ignore) {
            }
        } else {
            connpool.release(conn);
        }
    }

    workerPool
            .execute(new ClientWorker(cfgCtx, inputBuffer == null ? null : new ContentInputStream(inputBuffer),
                    response, outMsgContext, endptPrefix));
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Slightly modified version of {@link DefaultRedirectStrategy#getLocationURI(HttpRequest, HttpResponse, HttpContext)}
 * which also adds the query string from the original request URI to the new URI.
 *///www. j  a  va  2 s . c  om
private URI getRedirectLocationURI(IDeltaSyncSession session, HttpUriRequest request, HttpResponse response,
        HttpContext context) throws DeltaSyncException {

    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new DeltaSyncException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (session.getLogger().isDebugEnabled()) {
        session.getLogger().debug("Redirect requested to location '" + location + "'");
    }

    URI uri = null;
    try {
        uri = new URI(location);
        if (request.getURI().getRawQuery() != null) {
            String query = request.getURI().getRawQuery();
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                    query, uri.getFragment());
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException("Invalid redirect URI: " + location, ex);
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final RequestConfig config = clientContext.getRequestConfig();

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (config.isRelativeRedirectsAllowed()) {
                throw new DeltaSyncException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            HttpHost target = clientContext.getTargetHost();
            if (target == null) {
                throw new IllegalStateException("Target host not available " + "in the HTTP context");
            }

            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
    }

    if (config.isCircularRedirectsAllowed()) {
        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new DeltaSyncException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new DeltaSyncException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.java

@Override
public HttpResponse execute(HttpHost originalTarget, final HttpRequest request, HttpContext context)
        throws HttpException, IOException {
    HttpHost target = originalTarget;/*from  ww w . j  a v a 2s . co  m*/
    final HttpRoute route = determineRoute(target, request, context);

    virtualHost = (HttpHost) request.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    long timeout = ConnManagerParams.getTimeout(params);

    try {
        HttpResponse response = null;

        // See if we have a user token bound to the execution context
        Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

        // Allocate connection if needed
        if (managedConn == null) {
            ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
            if (request instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) request).setConnectionRequest(connRequest);
            }

            try {
                managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException interrupted) {
                InterruptedIOException iox = new InterruptedIOException();
                iox.initCause(interrupted);
                throw iox;
            }

            if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                // validate connection
                if (managedConn.isOpen()) {
                    LOGGER.debug("Stale connection check");
                    if (managedConn.isStale()) {
                        LOGGER.debug("Stale connection detected");
                        managedConn.close();
                    }
                }
            }
        }

        if (request instanceof AbortableHttpRequest) {
            ((AbortableHttpRequest) request).setReleaseTrigger(managedConn);
        }

        // Reopen connection if needed
        if (!managedConn.isOpen()) {
            managedConn.open(route, context, params);
        } else {
            managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
        }

        try {
            establishRoute(route, context);
        } catch (TunnelRefusedException ex) {
            LOGGER.debug(ex.getMessage());
            response = ex.getResponse();
        }

        // Use virtual host if set
        target = virtualHost;

        if (target == null) {
            target = route.getTargetHost();
        }

        HttpHost proxy = route.getProxyHost();

        // Populate the execution context
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
        context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
        context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

        // Run request protocol interceptors
        requestExec.preProcess(request, httpProcessor, context);

        try {
            response = requestExec.execute(request, managedConn, context);
        } catch (IOException ex) {
            LOGGER.debug("Closing connection after request failure.");
            managedConn.close();
            throw ex;
        }

        if (response == null) {
            return null;
        }

        // Run response protocol interceptors
        response.setParams(params);
        requestExec.postProcess(response, httpProcessor, context);

        // The connection is in or can be brought to a re-usable state.
        boolean reuse = reuseStrategy.keepAlive(response, context);
        if (reuse) {
            // Set the idle duration of this connection
            long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
            managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

            if (duration >= 0) {
                LOGGER.trace("Connection can be kept alive for " + duration + " ms");
            } else {
                LOGGER.trace("Connection can be kept alive indefinitely");
            }
        }

        if ((managedConn != null) && (userToken == null)) {
            userToken = userTokenHandler.getUserToken(context);
            context.setAttribute(ClientContext.USER_TOKEN, userToken);
            if (userToken != null) {
                managedConn.setState(userToken);
            }
        }

        // check for entity, release connection if possible
        if ((response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse) {
                managedConn.markReusable();
            }
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:czd.lib.network.AsyncHttpClient.java

/**
 * Simple interface method, to enable or disable redirects. If you set manually RedirectHandler
 * on underlying HttpClient, effects of this method will be canceled.
 *
 * @param enableRedirects boolean/*from   w  w w.  j ava2 s  . c  o  m*/
 */
public void setEnableRedirects(final boolean enableRedirects) {
    if (enableRedirects) {
        httpClient.setRedirectHandler(new DefaultRedirectHandler() {
            @Override
            public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                int statusCode = response.getStatusLine().getStatusCode();
                switch (statusCode) {
                case HttpStatus.SC_MOVED_TEMPORARILY:
                case HttpStatus.SC_MOVED_PERMANENTLY:
                case HttpStatus.SC_SEE_OTHER:
                case HttpStatus.SC_TEMPORARY_REDIRECT:
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                //get the location header to find out where to redirect to
                Header locationHeader = response.getFirstHeader("location");
                if (locationHeader == null) {
                    // got a redirect response, but no location header
                    throw new ProtocolException("Received redirect response " + response.getStatusLine()
                            + " but no location header");
                }
                //HERE IS THE MODIFIED LINE OF CODE
                String location = locationHeader.getValue().replaceAll(" ", "%20");

                URI uri;
                try {
                    uri = new URI(location);
                } catch (URISyntaxException ex) {
                    throw new ProtocolException("Invalid redirect URI: " + location, ex);
                }

                HttpParams params = response.getParams();
                // rfc2616 demands the location value be a complete URI
                // Location       = "Location" ":" absoluteURI
                if (!uri.isAbsolute()) {
                    if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
                        throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
                    }
                    // Adjust location URI
                    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                    if (target == null) {
                        throw new IllegalStateException("Target host not available " + "in the HTTP context");
                    }

                    HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

                    try {
                        URI requestURI = new URI(request.getRequestLine().getUri());
                        URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
                        uri = URIUtils.resolve(absoluteRequestURI, uri);
                    } catch (URISyntaxException ex) {
                        throw new ProtocolException(ex.getMessage(), ex);
                    }
                }

                if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

                    RedirectLocations redirectLocations = (RedirectLocations) context
                            .getAttribute("http.protocol.redirect-locations");

                    if (redirectLocations == null) {
                        redirectLocations = new RedirectLocations();
                        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
                    }

                    URI redirectURI;
                    if (uri.getFragment() != null) {
                        try {
                            HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                            redirectURI = URIUtils.rewriteURI(uri, target, true);
                        } catch (URISyntaxException ex) {
                            throw new ProtocolException(ex.getMessage(), ex);
                        }
                    } else {
                        redirectURI = uri;
                    }

                    if (redirectLocations.contains(redirectURI)) {
                        throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
                    } else {
                        redirectLocations.add(redirectURI);
                    }
                }

                return uri;
            }
        });
    }

}