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:org.apache.synapse.transport.nhttp.ClientHandler.java

/**
 * Process ready output (i.e. write request to remote server)
 * // w  w w  . ja v a 2  s  . c o  m
 * @param conn the connection being processed
 * @param encoder the encoder in use
 */
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
    HttpContext context = conn.getContext();

    ContentOutputBuffer outBuf = (ContentOutputBuffer) context.getAttribute(REQUEST_SOURCE_BUFFER);
    if (outBuf == null)
        return;

    try {
        int bytesWritten = outBuf.produceContent(encoder);
        if (metrics != null) {
            if (bytesWritten > 0) {
                if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                    metrics.incrementBytesSent(getMessageContext(conn), bytesWritten);
                } else {
                    metrics.incrementBytesSent(bytesWritten);
                }
            }

            if (encoder.isCompleted()) {
                if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                    metrics.incrementMessagesSent(getMessageContext(conn));
                } else {
                    metrics.incrementMessagesSent();
                }
            }
        }

        if (encoder.isCompleted()) {
            ClientConnectionDebug ccd = (ClientConnectionDebug) context.getAttribute(CLIENT_CONNECTION_DEBUG);
            if (ccd != null) {
                ccd.recordRequestCompletionTime();
            }

            setServerContextAttribute(NhttpConstants.REQ_TO_BACKEND_WRITE_END_TIME, System.currentTimeMillis(),
                    conn);
        }

    } catch (IOException e) {
        if (metrics != null) {
            if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                metrics.incrementFaultsSending(NhttpConstants.SND_IO_ERROR_SENDING, getMessageContext(conn));
            } else {
                metrics.incrementFaultsSending();
            }
        }
        handleException("I/O Error at outputReady : " + e.getMessage(), e, conn);
    }
}

From source file:com.mycompany.allasync.NHttpRequestHandler.java

private void handleInternal(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//from   w w  w.  ja  va  2s  .c o  m

    String target = request.getRequestLine().getUri();
    final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
    if (!file.exists()) {

        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        NStringEntity entity = new NStringEntity(
                "<html><body><h1>File" + file.getPath() + " not found</h1></body></html>",
                ContentType.create("text/html", "UTF-8"));
        response.setEntity(entity);
        System.out.println("File " + file.getPath() + " not found");

    } else if (!file.canRead() || file.isDirectory()) {

        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        NStringEntity entity = new NStringEntity("<html><body><h1>Access denied</h1></body></html>",
                ContentType.create("text/html", "UTF-8"));
        response.setEntity(entity);
        System.out.println("Cannot read file " + file.getPath());

    } else {
        NHttpConnection conn = (NHttpConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
        response.setStatusCode(HttpStatus.SC_OK);
        NFileEntity body = new NFileEntity(file, ContentType.create("text/html"));
        response.setEntity(body);
        System.out.println(conn + ": serving file " + file.getPath());
    }
}

From source file:clj_httpc.CustomRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, 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  2 s  . 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");
    }
    String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    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");
        }
        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)) {

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

        if (redirectLocations == null) {
            redirectLocations = new CustomRedirectLocations();
            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 {
            int statusCode = response.getStatusLine().getStatusCode();
            redirectLocations.add(redirectURI, statusCode);
        }
    }

    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
 */// w w  w.  ja v  a2s  .  c  o 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:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * Store in JMeter Variables the UserToken so that the SSL context is reused
 * See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
 * @param localContext {@link HttpContext}
 *///from www  .ja  v a  2 s.c  om
private void extractClientContextAfterSample(HttpContext localContext) {
    Object userToken = localContext.getAttribute(HttpClientContext.USER_TOKEN);
    if (userToken != null) {
        if (log.isDebugEnabled()) {
            log.debug("Extracted from HttpContext user token:" + userToken + ", storing it as JMeter variable:"
                    + USER_TOKEN);
        }
        // During recording JMeterContextService.getContext().getVariables() is null
        JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
        if (jMeterVariables != null) {
            jMeterVariables.putObject(USER_TOKEN, userToken);
        }
    }
}

From source file:com.mongolduu.android.ng.misc.RedirectHandler.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  .j av  a2s . 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");
    }
    // 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:spaceRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/* w ww.  j a v  a 2 s.  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().replaceAll(" ", "%20");
    ;
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    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");
        }
        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.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?//from  ww  w  . jav a  2s .co  m
 *
 * @param httpRequest
 * @param acceptHeaderValue
 */
private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager,
        HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean,
        Map<String, String> urlParameters, CredentialsProvider credentialsProvider) {
    // headers are set identically for all HTTP methods, therefore can do
    // centrally - here

    // If the user wants to set MIME type for the 'Accepts' header
    String acceptsHeaderValue = configBean.getAcceptsHeaderValue();
    if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) {
        httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue,
                urlParameters, configBean.getEscapeParameters()));
    }

    // See if user wanted to set any other HTTP headers
    ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders();
    if (!otherHTTPHeaders.isEmpty())
        for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders)
            if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) {
                String headerParameterizedValue = httpHeaderNameValuePair.get(1);
                String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue,
                        urlParameters, configBean.getEscapeParameters());
                httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue);
            }

    try {
        HTTPRequestResponse requestResponse = new HTTPRequestResponse();
        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null);
        ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider);
        HttpContext localContext = new BasicHttpContext();

        // Set the proxy settings, if any
        if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) {
            // Instruct HttpClient to use the standard
            // JRE proxy selector to obtain proxy information
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
            httpClient.setRoutePlanner(routePlanner);
            // Do we need to authenticate the user to the proxy?
            if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty())
                // Add the proxy username and password to the list of
                // credentials
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(System.getProperty(PROXY_HOST),
                                Integer.parseInt(System.getProperty(PROXY_PORT))),
                        new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME),
                                System.getProperty(PROXY_PASSWORD)));
        }

        // execute the request
        HttpResponse response = httpClient.execute(httpRequest, localContext);

        // record response code
        requestResponse.setStatusCode(response.getStatusLine().getStatusCode());
        requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());

        // record header values for Content-Type of the response
        requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME));

        // track where did the final redirect go to (if there was any)
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest targetRequest = (HttpUriRequest) localContext
                .getAttribute(ExecutionContext.HTTP_REQUEST);
        requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI());
        requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod());
        requestResponse.setHeaders(response.getAllHeaders());

        /* read and store response body
         (check there is some content - negative length of content means
         unknown length;
         zero definitely means no content...)*/
        // TODO - make sure that this test is sufficient to determine if
        // there is no response entity
        if (response.getEntity() != null && response.getEntity().getContentLength() != 0)
            requestResponse.setResponseBody(readResponseBody(response.getEntity()));

        // release resources (e.g. connection pool, etc)
        httpClient.getConnectionManager().shutdown();
        return requestResponse;
    } catch (Exception ex) {
        return new HTTPRequestResponse(ex);
    }
}