Example usage for org.apache.http.nio ContentDecoder isCompleted

List of usage examples for org.apache.http.nio ContentDecoder isCompleted

Introduction

In this page you can find the example usage for org.apache.http.nio ContentDecoder isCompleted.

Prototype

boolean isCompleted();

Source Link

Document

Returns true if the entity has been received in its entirety.

Usage

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

/**
 * Process ready input (i.e. response from remote server)
 * /*from   www .  j a  v a  2  s.  com*/
 * @param conn connection being processed
 * @param decoder the content decoder in use
 */
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();
    ContentInputBuffer inBuf = (ContentInputBuffer) context.getAttribute(RESPONSE_SINK_BUFFER);

    try {
        int bytesRead = inBuf.consumeContent(decoder);
        if (metrics != null && bytesRead > 0) {
            if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                metrics.incrementBytesReceived(getMessageContext(conn), bytesRead);
            } else {
                metrics.incrementBytesReceived(bytesRead);
            }
        }

        if (decoder.isCompleted()) {
            setServerContextAttribute(NhttpConstants.RES_ARRIVAL_TIME, System.currentTimeMillis(), conn);
            setServerContextAttribute(NhttpConstants.RES_FROM_BACKEND_READ_END_TIME, System.currentTimeMillis(),
                    conn);
            ClientConnectionDebug ccd = (ClientConnectionDebug) conn.getContext()
                    .getAttribute(CLIENT_CONNECTION_DEBUG);
            if (ccd != null) {
                ccd.recordResponseCompletionTime();
            }

            if (metrics != null) {
                if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                    MessageContext mc = getMessageContext(conn);
                    metrics.incrementMessagesReceived(mc);
                    metrics.notifyReceivedMessageSize(mc, conn.getMetrics().getReceivedBytesCount());
                    metrics.notifySentMessageSize(mc, conn.getMetrics().getSentBytesCount());
                    metrics.reportResponseCode(mc, response.getStatusLine().getStatusCode());
                } else {
                    metrics.incrementMessagesReceived();
                    metrics.notifyReceivedMessageSize(conn.getMetrics().getReceivedBytesCount());
                    metrics.notifySentMessageSize(conn.getMetrics().getSentBytesCount());
                }
            }
            // reset metrics on connection
            conn.getMetrics().reset();
            if (context.getAttribute(NhttpConstants.DISCARD_ON_COMPLETE) != null) {
                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 if (!connStrategy.keepAlive(response, context)) {
                shutdownConnection(conn, false, null);
                context.removeAttribute(RESPONSE_SINK_BUFFER);
                context.removeAttribute(REQUEST_SOURCE_BUFFER);
            } else {
                connpool.release(conn);
            }
        }

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

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
 */// ww w.j  a va  2  s .  c  om
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.TargetHandler.java

public void inputReady(NHttpClientConnection conn, ContentDecoder decoder) {
    ProtocolState connState;/*ww  w . ja  v  a 2 s  . com*/
    MessageContext msgCtx = TargetContext.get(conn).getRequestMsgCtx();
    try {
        connState = TargetContext.getState(conn);
        if (connState.compareTo(ProtocolState.RESPONSE_HEAD) < 0) {
            return;
        }
        if (connState != ProtocolState.RESPONSE_HEAD && connState != ProtocolState.RESPONSE_BODY) {
            handleInvalidState(conn, "Response received");
            return;
        }

        TargetContext.updateState(conn, ProtocolState.RESPONSE_BODY);

        TargetResponse response = TargetContext.getResponse(conn);
        int statusCode = -1;

        if (response != null) {
            statusCode = conn.getHttpResponse().getStatusLine().getStatusCode();
            int responseRead = response.read(conn, decoder);
            if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                metrics.incrementBytesReceived(msgCtx, responseRead);
            } else {
                metrics.incrementBytesReceived(responseRead);
            }
        }
        if (decoder.isCompleted()) {
            if (metrics.getLevel() == MetricsCollector.LEVEL_FULL) {
                metrics.incrementMessagesReceived(msgCtx);
                metrics.notifyReceivedMessageSize(msgCtx, conn.getMetrics().getReceivedBytesCount());
                metrics.notifySentMessageSize(msgCtx, conn.getMetrics().getSentBytesCount());
                if (statusCode != -1) {
                    metrics.reportResponseCode(msgCtx, statusCode);
                }
            } else {
                metrics.incrementMessagesReceived();
                metrics.notifyReceivedMessageSize(conn.getMetrics().getReceivedBytesCount());
                metrics.notifySentMessageSize(conn.getMetrics().getSentBytesCount());
            }
            MessageContext requestMsgContext = TargetContext.get(conn).getRequestMsgCtx();
            NHttpServerConnection sourceConn = (NHttpServerConnection) requestMsgContext
                    .getProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION);
            if (sourceConn != null) {
                if (conn.getContext()
                        .getAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_END_TIME) != null) {
                    sourceConn.getContext().setAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_END_TIME,
                            conn.getContext()
                                    .getAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_END_TIME));
                    conn.getContext().removeAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_END_TIME);

                }
                sourceConn.getContext().setAttribute(PassThroughConstants.RES_ARRIVAL_TIME,
                        conn.getContext().getAttribute(PassThroughConstants.RES_ARRIVAL_TIME));
                conn.getContext().removeAttribute(PassThroughConstants.RES_ARRIVAL_TIME);
            }
        }
    } catch (IOException e) {
        logIOException(conn, e);
        informReaderError(conn);

        TargetContext.updateState(conn, ProtocolState.CLOSED);
        targetConfiguration.getConnections().shutdownConnection(conn, true);
    } catch (Exception ex) {
        log.error("Exception occurred while reading request body", ex);

        informReaderError(conn);

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

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

/**
 * Testing whether input-ready connection is processed
 *
 * @throws Exception/*from www  .j  av  a  2s . c  o m*/
 */
@Test
public void testInputReady() throws Exception {
    DeliveryAgent deliveryAgent = mock(DeliveryAgent.class);
    ClientConnFactory connFactory = mock(ClientConnFactory.class);

    ConfigurationContext configurationContext = new ConfigurationContext(new AxisConfiguration());
    WorkerPool workerPool = new NativeWorkerPool(3, 4, 5, 5, "name", "id");
    PassThroughTransportMetricsCollector metrics = new PassThroughTransportMetricsCollector(true, "testScheme");
    TargetConfiguration targetConfiguration = new TargetConfiguration(configurationContext, null, workerPool,
            metrics, null);
    TargetContext targetContext = new TargetContext(targetConfiguration);
    MessageContext messageContext = new MessageContext();
    targetContext.setRequestMsgCtx(messageContext);
    TargetHandler targetHandler = new TargetHandler(deliveryAgent, connFactory, targetConfiguration);

    TargetResponse response = mock(TargetResponse.class);
    NHttpClientConnection conn = mock(NHttpClientConnection.class, Mockito.RETURNS_DEEP_STUBS);
    ContentDecoder decoder = mock(ContentDecoder.class);
    mockStatic(TargetContext.class);
    when(TargetContext.get(conn)).thenReturn(targetContext);
    when(TargetContext.getState(conn)).thenReturn(ProtocolState.RESPONSE_HEAD);
    when(TargetContext.getResponse(conn)).thenReturn(response);
    when(decoder.isCompleted()).thenReturn(true);

    targetHandler.inputReady(conn, decoder);

}

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

/**
 * Read the data from the wire and read in to the pipe so that other end of
 * the pipe can write.//from  ww  w. j ava 2  s  . c  o m
 * @param conn the target connection
 * @param decoder content decoder
 * @throws java.io.IOException if an error occurs
 * @return number of bites read
 */
public int read(NHttpClientConnection conn, ContentDecoder decoder) throws IOException {

    int bytes = 0;

    if (pipe != null) {
        bytes = pipe.produce(decoder);
    }

    // Update connection state
    if (decoder.isCompleted()) {
        conn.getContext().setAttribute(PassThroughConstants.RES_FROM_BACKEND_READ_END_TIME,
                System.currentTimeMillis());
        conn.getContext().setAttribute(PassThroughConstants.RES_ARRIVAL_TIME, System.currentTimeMillis());
        TargetContext.updateState(conn, ProtocolState.RESPONSE_DONE);

        targetConfiguration.getMetrics().notifyReceivedMessageSize(conn.getMetrics().getReceivedBytesCount());

        if (!this.connStrategy.keepAlive(response, conn.getContext()) || forceShutdownConnectionOnComplete) {
            TargetContext.updateState(conn, ProtocolState.CLOSED);

            targetConfiguration.getConnections().shutdownConnection(conn);
        } else {
            if (conn instanceof LoggingNHttpClientConnection) {
                ((LoggingNHttpClientConnection) conn).setReleaseConn(true);
            }
        }
    }
    return bytes;
}

From source file:org.siddhiesb.transport.passthru.TargetResponse.java

/**
 * Read the data from the wire and read in to the pipe so that other end of
 * the pipe can write./*from   w  w w. j  av  a2 s.  c  o  m*/
 * @param conn the target connection
 * @param decoder content decoder
 * @throws java.io.IOException if an error occurs
 * @return number of bites read
 */
public int read(NHttpClientConnection conn, ContentDecoder decoder) throws IOException {

    int bytes = 0;

    if (pipe != null) {
        bytes = pipe.produce(decoder);
    }

    // Update connection state
    if (decoder.isCompleted()) {
        org.siddhiesb.transport.passthru.TargetContext.updateState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.RESPONSE_DONE);

        if (!this.connStrategy.keepAlive(response, conn.getContext())) {
            org.siddhiesb.transport.passthru.TargetContext.updateState(conn, ProtocolState.CLOSED);

            targetConfiguration.getConnections().shutdownConnection(conn);
        } else {
            targetConfiguration.getConnections().releaseConnection(conn);
        }
    }
    return bytes;
}