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

/**
 * Process ready input by writing it into the Pipe
 * @param conn the connection being processed
 * @param decoder the content decoder in use
 *//*from   w w  w  .  j  a  va2s.  com*/
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {

    HttpContext context = conn.getContext();
    ContentInputBuffer inBuf = (ContentInputBuffer) context.getAttribute(REQUEST_SINK_BUFFER);

    try {
        int bytesRead = inBuf.consumeContent(decoder);
        if (metrics != null && bytesRead > 0) {
            metrics.incrementBytesReceived(bytesRead);
        }

        if (decoder.isCompleted()) {

            ((ServerConnectionDebug) conn.getContext().getAttribute(SERVER_CONNECTION_DEBUG))
                    .recordRequestCompletionTime();
            // remove the request we have fully read, to detect harmless keepalive timeouts from
            // real timeouts while reading requests
            context.setAttribute(NhttpConstants.REQUEST_READ, Boolean.TRUE);
            context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_END_TIME, System.currentTimeMillis());
        }

    } catch (IOException e) {
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        handleException("I/O Error at inputReady : " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.synapse.transport.passthru.SourceHandler.java

public void requestReceived(NHttpServerConnection conn) {
    try {/*www.  j  a  v a  2  s.  c  o m*/
        HttpContext httpContext = conn.getContext();
        httpContext.setAttribute(PassThroughConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());
        httpContext.setAttribute(PassThroughConstants.REQ_FROM_CLIENT_READ_START_TIME,
                System.currentTimeMillis());

        SourceRequest request = getSourceRequest(conn);
        if (request == null) {
            return;
        }

        String method = request.getRequest() != null
                ? request.getRequest().getRequestLine().getMethod().toUpperCase()
                : "";

        if (!request.isEntityEnclosing()) {
            conn.getContext().setAttribute(PassThroughConstants.REQ_FROM_CLIENT_READ_END_TIME,
                    System.currentTimeMillis());
        }
        OutputStream os = getOutputStream(method, request);
        sourceConfiguration.getWorkerPool().execute(new ServerWorker(request, sourceConfiguration, os));
    } catch (HttpException e) {
        log.error("HttpException occurred when request is processing probably when creating SourceRequest", e);

        informReaderError(conn);

        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    } catch (IOException e) {
        logIOException(conn, e);

        informReaderError(conn);

        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    }
}

From source file:org.apache.synapse.transport.passthru.SourceHandler.java

public void outputReady(NHttpServerConnection conn, ContentEncoder encoder) {
    try {// w w w . j  a  v a2  s  .c  o  m
        ProtocolState protocolState = SourceContext.getState(conn);

        //special case to handle WSDLs
        if (protocolState == ProtocolState.WSDL_RESPONSE_DONE) {
            // we need to shut down if the shutdown flag is set
            HttpContext context = conn.getContext();
            ContentOutputBuffer outBuf = (ContentOutputBuffer) context
                    .getAttribute("synapse.response-source-buffer");
            int bytesWritten = outBuf.produceContent(encoder);
            if (metrics != null && bytesWritten > 0) {
                metrics.incrementBytesSent(bytesWritten);
            }

            conn.requestInput();
            if (outBuf instanceof SimpleOutputBuffer && !((SimpleOutputBuffer) outBuf).hasData()) {
                sourceConfiguration.getSourceConnections().releaseConnection(conn);
            }
            endTransaction(conn);
            return;
        }

        if (protocolState != ProtocolState.RESPONSE_HEAD && protocolState != ProtocolState.RESPONSE_BODY) {
            log.warn("Illegal incoming connection state: " + protocolState + " . Possibly two send backs "
                    + "are happening for the same request");

            handleInvalidState(conn, "Trying to write response body");
            endTransaction(conn);
            return;
        }

        SourceContext.updateState(conn, ProtocolState.RESPONSE_BODY);

        SourceResponse response = SourceContext.getResponse(conn);

        int bytesSent = response.write(conn, encoder);

        if (encoder.isCompleted()) {
            HttpContext context = conn.getContext();
            long departure = System.currentTimeMillis();
            context.setAttribute(PassThroughConstants.RES_TO_CLIENT_WRITE_END_TIME, departure);
            context.setAttribute(PassThroughConstants.RES_DEPARTURE_TIME, departure);
            updateLatencyView(context);
        }
        endTransaction(conn);
        metrics.incrementBytesSent(bytesSent);
    } catch (IOException e) {
        logIOException(conn, e);

        informWriterError(conn);

        SourceContext.updateState(conn, ProtocolState.CLOSING);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    }
}

From source file:org.apache.synapse.transport.passthru.SourceHandler.java

public void exception(NHttpServerConnection conn, Exception ex) {
    boolean isFault = false;
    if (ex instanceof IOException) {
        logIOException(conn, (IOException) ex);

        metrics.incrementFaultsReceiving();

        ProtocolState state = SourceContext.getState(conn);
        if (state == ProtocolState.REQUEST_BODY || state == ProtocolState.REQUEST_HEAD) {
            informReaderError(conn);//from  w  w w  .  ja va  2  s  .co m
        } else if (state == ProtocolState.RESPONSE_BODY || state == ProtocolState.RESPONSE_HEAD) {
            informWriterError(conn);
        } else if (state == ProtocolState.REQUEST_DONE) {
            informWriterError(conn);
        } else if (state == ProtocolState.RESPONSE_DONE) {
            informWriterError(conn);
        }
        isFault = true;
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
    } else if (ex instanceof HttpException) {
        try {
            if (conn.isResponseSubmitted()) {
                sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
                return;
            }
            HttpContext httpContext = conn.getContext();

            HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST,
                    "Bad request");
            response.setParams(
                    new DefaultedHttpParams(sourceConfiguration.getHttpParams(), response.getParams()));
            response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);

            // Pre-process HTTP request
            httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            httpContext.setAttribute(ExecutionContext.HTTP_REQUEST, null);
            httpContext.setAttribute(ExecutionContext.HTTP_RESPONSE, response);

            sourceConfiguration.getHttpProcessor().process(response, httpContext);

            conn.submitResponse(response);
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            conn.close();
        } catch (Exception ex1) {
            log.error(ex.getMessage(), ex);
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
            isFault = true;
        }
    } else {
        log.error("Unexpected error: " + ex.getMessage(), ex);
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn, true);
        isFault = true;
    }

    if (isFault) {
        rollbackTransaction(conn);
    }
}

From source file:org.apache.synapse.transport.passthru.TargetHandler.java

public void connected(NHttpClientConnection conn, Object o) {
    assert o instanceof HostConnections : "Attachment should be a HostConnections";
    HostConnections pool = (HostConnections) o;
    conn.getContext().setAttribute(PassThroughConstants.CONNECTION_POOL, pool);
    HttpRoute route = pool.getRoute();//  w w  w. ja v a2  s .co  m

    // create the connection information and set it to request ready
    TargetContext.create(conn, ProtocolState.REQUEST_READY, targetConfiguration);

    // notify the pool about the new connection
    targetConfiguration.getConnections().addConnection(conn);

    // notify about the new connection
    deliveryAgent.connected(pool.getRoute(), conn);

    HttpContext context = conn.getContext();
    context.setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis());

    metrics.connected();

    if (route.isTunnelled()) {
        // Requires a proxy tunnel
        ProxyTunnelHandler tunnelHandler = new ProxyTunnelHandler(route, connFactory);
        context.setAttribute(PassThroughConstants.TUNNEL_HANDLER, tunnelHandler);
    }
}

From source file:org.apache.synapse.transport.passthru.TargetHandler.java

public void requestReady(NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    ProtocolState connState = null;/*from w w w .j  a  v a  2s .  c o  m*/
    try {

        connState = TargetContext.getState(conn);

        if (connState == ProtocolState.REQUEST_DONE || connState == ProtocolState.RESPONSE_BODY) {
            return;
        }

        if (connState != ProtocolState.REQUEST_READY) {
            handleInvalidState(conn, "Request not started");
            return;
        }

        ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context
                .getAttribute(PassThroughConstants.TUNNEL_HANDLER);
        if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
            if (!tunnelHandler.isRequested()) {
                HttpRequest request = tunnelHandler.generateRequest(context);
                if (targetConfiguration.getProxyAuthenticator() != null) {
                    targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, context);
                }
                if (log.isDebugEnabled()) {
                    log.debug(conn + ": Sending CONNECT request to " + tunnelHandler.getProxy());
                }
                conn.submitRequest(request);
                tunnelHandler.setRequested();
            }
            return;
        }

        TargetRequest request = TargetContext.getRequest(conn);
        if (request != null) {
            request.start(conn);
            targetConfiguration.getMetrics().incrementMessagesSent();
        }
        context.setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME, System.currentTimeMillis());
        context.setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME, System.currentTimeMillis());
    } catch (IOException e) {
        logIOException(conn, e);
        TargetContext.updateState(conn, ProtocolState.CLOSED);
        targetConfiguration.getConnections().shutdownConnection(conn, true);

        MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();
        if (requestMsgCtx != null) {
            targetErrorHandler.handleError(requestMsgCtx, ErrorCodes.SND_IO_ERROR, "Error in Sender", null,
                    connState);
        }
    } catch (HttpException e) {
        log.error(e.getMessage(), e);
        TargetContext.updateState(conn, ProtocolState.CLOSED);
        targetConfiguration.getConnections().shutdownConnection(conn, true);

        MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();
        if (requestMsgCtx != null) {
            targetErrorHandler.handleError(requestMsgCtx, ErrorCodes.SND_HTTP_ERROR, "Error in Sender", null,
                    connState);
        }
    }
}

From source file:org.apache.synapse.transport.passthru.TargetHandler.java

public void responseReceived(NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();
    ProtocolState connState;/*w  ww. j  a v  a  2 s.co m*/
    try {
        String method = null;
        ProxyTunnelHandler tunnelHandler = (ProxyTunnelHandler) context
                .getAttribute(PassThroughConstants.TUNNEL_HANDLER);
        if (tunnelHandler != null && !tunnelHandler.isCompleted()) {
            method = "CONNECT";
            context.removeAttribute(PassThroughConstants.TUNNEL_HANDLER);
            tunnelHandler.handleResponse(response, conn);
            if (tunnelHandler.isSuccessful()) {
                log.debug(conn + ": Tunnel established");
                conn.resetInput();
                conn.requestOutput();
                return;
            } else {
                TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
            }
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode < HttpStatus.SC_OK) {
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Received a 100 Continue response");
            }
            // Ignore 1xx response
            return;
        }
        boolean isError = false;
        context.setAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME, System.currentTimeMillis());
        connState = TargetContext.getState(conn);
        MessageContext requestMsgContext = TargetContext.get(conn).getRequestMsgCtx();
        NHttpServerConnection sourceConn = (NHttpServerConnection) requestMsgContext
                .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);

        if (connState != ProtocolState.REQUEST_DONE) {
            isError = true;
            StatusLine errorStatus = response.getStatusLine();
            /* We might receive a 404 or a similar type, even before we write the request body. */
            if (errorStatus != null) {
                if (errorStatus.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
                    TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
                    conn.resetOutput();
                    if (sourceConn != null) {
                        SourceContext.updateState(sourceConn, ProtocolState.REQUEST_DONE);
                        SourceContext.get(sourceConn).setShutDown(true);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug(conn + ": Received response with status code : "
                                + response.getStatusLine().getStatusCode() + " in invalid state : "
                                + connState.name());
                    }
                }
            } else {
                handleInvalidState(conn, "Receiving response");
                return;
            }
        }
        context.setAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME, System.currentTimeMillis());
        TargetRequest targetRequest = TargetContext.getRequest(conn);

        if (targetRequest != null) {
            method = targetRequest.getMethod();
        }
        if (method == null) {
            method = "POST";
        }
        boolean canResponseHaveBody = isResponseHaveBodyExpected(method, response);
        if (!canResponseHaveBody) {
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Received no-content response " + response.getStatusLine().getStatusCode());
            }
            conn.resetInput();
        }
        TargetResponse targetResponse = new TargetResponse(targetConfiguration, response, conn,
                canResponseHaveBody, isError);
        TargetContext.setResponse(conn, targetResponse);
        targetResponse.start(conn);

        if (statusCode == HttpStatus.SC_ACCEPTED && handle202(requestMsgContext)) {
            return;
        }

        targetConfiguration.getWorkerPool()
                .execute(new ClientWorker(targetConfiguration, requestMsgContext, targetResponse));

        targetConfiguration.getMetrics().incrementMessagesReceived();

        sourceConn = (NHttpServerConnection) requestMsgContext
                .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);
        if (sourceConn != null) {
            sourceConn.getContext().setAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME,
                    conn.getContext().getAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME));
            conn.getContext().removeAttribute(PassThroughConstants.RES_HEADER_ARRIVAL_TIME);

            sourceConn.getContext().setAttribute(PassThroughConstants.REQ_DEPARTURE_TIME,
                    conn.getContext().getAttribute(PassThroughConstants.REQ_DEPARTURE_TIME));
            conn.getContext().removeAttribute(PassThroughConstants.REQ_DEPARTURE_TIME);
            sourceConn.getContext().setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME,
                    conn.getContext().getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME));

            conn.getContext().removeAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_START_TIME);
            sourceConn.getContext().setAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME,
                    conn.getContext().getAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME));
            conn.getContext().removeAttribute(PassThroughConstants.REQ_TO_BACKEND_WRITE_END_TIME);
            sourceConn.getContext().setAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME,
                    conn.getContext().getAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME));
            conn.getContext().removeAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_START_TIME);

        }

    } catch (Exception ex) {
        log.error("Exception occurred while processing response", ex);

        informReaderError(conn);

        TargetContext.updateState(conn, ProtocolState.CLOSED);
        targetConfiguration.getConnections().shutdownConnection(conn, true);
    }
}

From source file:org.everit.authentication.http.form.ecm.tests.FormAuthenticationServletTestComponent.java

@Test
@TestDuringDevelopment/*from www . j a v  a2 s. com*/
public void testAccessHelloPage() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    hello(httpContext, defaultResourceId);
    login(httpContext, USERNAME, WRONG_PASSWORD, loginFailedUrl);
    login(httpContext, USERNAME, PASSWORD, loginSuccessUrl);
    hello(httpContext, authenticatedResourceId);
}

From source file:org.everit.osgi.authentication.http.form.tests.FormAuthenticationServletTestComponent.java

@Test
public void testAccessHelloPage() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    hello(httpContext, defaultResourceId);
    login(httpContext, USERNAME, WRONG_PASSWORD, loginFailedUrl);
    login(httpContext, USERNAME, PASSWORD, loginSuccessUrl);
    hello(httpContext, authenticatedResourceId);
}

From source file:org.hibernate.search.elasticsearch.aws.impl.AWSPayloadHashingRequestInterceptor.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    String contentHash = computeContentHash(request);
    context.setAttribute(CONTEXT_ATTRIBUTE_HASH, contentHash);
}