Example usage for org.apache.http.nio NHttpClientConnection resetOutput

List of usage examples for org.apache.http.nio NHttpClientConnection resetOutput

Introduction

In this page you can find the example usage for org.apache.http.nio NHttpClientConnection resetOutput.

Prototype

void resetOutput();

Source Link

Document

Resets output state.

Usage

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 . j a  v a  2  s.  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.http.impl.nio.client.NHttpClientProtocolHandler.java

private void cancelRequest(final NHttpClientConnection conn, final HttpExchange httpexchange)
        throws IOException {
    int timeout = httpexchange.getTimeout();
    conn.setSocketTimeout(timeout);/*from   www.j  a  v  a2 s  .com*/
    conn.resetOutput();
    httpexchange.resetOutput();
}

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

private static void cleanConnectionReferences(NHttpClientConnection conn) {

    HttpContext ctx = conn.getContext();
    Axis2HttpRequest axis2Req = (Axis2HttpRequest) ctx.getAttribute(ClientHandler.AXIS2_HTTP_REQUEST);
    axis2Req.clear(); // this is linked via the selection key attachment and will free itself
                      // on timeout of the keep alive connection. Till then minimize the
                      // memory usage to a few bytes 

    ctx.removeAttribute(ClientHandler.ATTACHMENT_KEY);
    ctx.removeAttribute(ClientHandler.TUNNEL_HANDLER);
    ctx.removeAttribute(ClientHandler.AXIS2_HTTP_REQUEST);
    ctx.removeAttribute(ClientHandler.OUTGOING_MESSAGE_CONTEXT);
    ctx.removeAttribute(ClientHandler.REQUEST_SOURCE_BUFFER);
    ctx.removeAttribute(ClientHandler.RESPONSE_SINK_BUFFER);

    ctx.removeAttribute(ExecutionContext.HTTP_REQUEST);
    ctx.removeAttribute(ExecutionContext.HTTP_RESPONSE);

    conn.resetOutput();
}

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

/**
 * This method queues the message for delivery. If a connection is already existing for
 * the destination epr, the message will be delivered immediately. Otherwise message has
 * to wait until a connection is established. In this case this method will inform the
 * system about the need for a connection.
 *
 * @param msgContext the message context to be sent
 * @param epr the endpoint to which the message should be sent
 * @throws AxisFault if an error occurs/*from ww  w  . j av a2s  .  c o m*/
 */
public void submit(MessageContext msgContext, EndpointReference epr) throws AxisFault {
    try {
        URL url = new URL(epr.getAddress());
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());

        HttpHost proxy = proxyConfig.selectProxy(target);
        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }

        // first we queue the message
        Queue<MessageContext> queue = null;
        lock.lock();
        try {
            queue = waitingMessages.get(route);
            if (queue == null) {
                queue = new ConcurrentLinkedQueue<MessageContext>();
                waitingMessages.put(route, queue);
            }
            if (queue.size() == maxWaitingMessages) {
                MessageContext msgCtx = queue.poll();

                targetErrorHandler.handleError(msgCtx, ErrorCodes.CONNECTION_TIMEOUT,
                        "Error connecting to the back end", null, ProtocolState.REQUEST_READY);
            }

            queue.add(msgContext);
        } finally {
            lock.unlock();
        }

        NHttpClientConnection conn = targetConnections.getConnection(route);
        if (conn != null) {
            conn.resetInput();
            conn.resetOutput();
            MessageContext messageContext = queue.poll();

            if (messageContext != null) {
                tryNextMessage(messageContext, route, conn);
            }
        }

    } catch (MalformedURLException e) {
        handleException("Malformed URL in the target EPR", e);
    }
}

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;//ww w . jav  a 2s. c  o  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.siddhiesb.transport.passthru.DeliveryAgent.java

/**
 * This method queues the message for delivery. If a connection is already existing for
 * the destination epr, the message will be delivered immediately. Otherwise message has
 * to wait until a connection is established. In this case this method will inform the
 * system about the need for a connection.
 *
 * @param commonContext the message context to be sent
 *///from  w w  w .java 2  s  .  com
public void submit(CommonContext commonContext) {
    try {

        String toAddress = (String) commonContext.getProperty(CommonAPIConstants.ENDPOINT);
        URL url = new URL(toAddress);
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());

        HttpHost proxy = null; //proxyConfig.selectProxy(target);

        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }

        // first we queue the message
        Queue<CommonContext> queue = null;
        lock.lock();
        try {
            queue = waitingMessages.get(route);
            if (queue == null) {
                queue = new ConcurrentLinkedQueue<CommonContext>();
                waitingMessages.put(route, queue);
            }
            if (queue.size() == maxWaitingMessages) {
                CommonContext msgCtx = queue.poll();
            }

            queue.add(commonContext);
        } finally {
            lock.unlock();
        }

        NHttpClientConnection conn = targetConnections.getConnection(route);
        if (conn != null) {
            conn.resetInput();
            conn.resetOutput();
            CommonContext commonContext1 = queue.poll();

            if (commonContext1 != null) {
                tryNextMessage(commonContext1, route, conn);
            }
        }

    } catch (MalformedURLException e) {
        handleException("Malformed URL in the target EPR", e);
    }
}