Example usage for org.apache.http.nio.entity ContentInputStream ContentInputStream

List of usage examples for org.apache.http.nio.entity ContentInputStream ContentInputStream

Introduction

In this page you can find the example usage for org.apache.http.nio.entity ContentInputStream ContentInputStream.

Prototype

public ContentInputStream(final ContentInputBuffer buffer) 

Source Link

Usage

From source file:com.alibaba.openapi.client.rpc.AliNHttpRequstExecutionHandler.java

public ConsumingNHttpEntity responseEntity(final HttpResponse httpResponse, final HttpContext context)
        throws IOException {
    //System.out.println("AliNHttpRequstExecutionHandler responseEntity");

    LoggerHelper.getClientLogger().finer("Enter request handler's response entity.");
    final InvokeContext invokeContext = (InvokeContext) context.getAttribute(CONTEXT_ATTACHMENT);
    final Response response = protocolProvider
            .getResponseParser(invokeContext.getPolicy().getResponseProtocol())
            .initResponse(httpResponse, invokeContext);
    //ConsumingNHttpEntityTemplateContentListener??
    ContentListener contentListener = new ContentListener() {
        private final SimpleInputBuffer buffer = new SimpleInputBuffer(2048, allocator);

        @SuppressWarnings("unchecked")
        public void finished() {
            InputStream istream = new ContentInputStream(this.buffer);
            protocolProvider.getResponseParser(invokeContext.getPolicy().getResponseProtocol())
                    .parseResponse(httpResponse, istream, response, invokeContext);
            invokeContext.completed();//from   w ww .j a v  a  2  s.  com
            if (response.getException() != null) {
                invokeContext.failed(response.getException());
            } else {
                try {
                    ((FutureCallback<Object>) invokeContext.getCallback()).completed(response.getResult());
                } catch (RuntimeException e) {
                    invokeContext.failed(e);
                }
            }
        }

        //TODO ??,??
        public void contentAvailable(ContentDecoder decoder, IOControl ioctrl) throws IOException {
            this.buffer.consumeContent(decoder);
            LoggerHelper.getClientLogger().finer("content Listener " + this.buffer.available());
        }
    };
    HttpEntity entity = httpResponse.getEntity();
    return new ConsumingNHttpEntityTemplate(entity, contentListener);
}

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  w w  .  j a va2  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.synapse.transport.nhttp.ServerHandler.java

/**
 * Process a new incoming request//  w ww .j  av  a  2 s. c om
 * @param conn the connection
 */
public void requestReceived(final NHttpServerConnection conn) {

    HttpContext context = conn.getContext();
    context.setAttribute(NhttpConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());
    context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_START_TIME, System.currentTimeMillis());
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    context.setAttribute(NhttpConstants.MESSAGE_IN_FLIGHT, "true");

    // prepare to collect debug information
    conn.getContext().setAttribute(ServerHandler.SERVER_CONNECTION_DEBUG, new ServerConnectionDebug(conn));

    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    try {
        InputStream is;
        // Only create an input buffer and ContentInputStream if the request has content
        if (request instanceof HttpEntityEnclosingRequest) {
            // Mark request as not yet fully read, to detect timeouts from harmless keepalive deaths
            conn.getContext().setAttribute(NhttpConstants.REQUEST_READ, Boolean.FALSE);

            ContentInputBuffer inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator);
            context.setAttribute(REQUEST_SINK_BUFFER, inputBuffer);
            is = new ContentInputStream(inputBuffer);
        } else {
            is = null;
            conn.getContext().removeAttribute(NhttpConstants.REQUEST_READ);
        }

        ContentOutputBuffer outputBuffer = new SharedOutputBuffer(cfg.getBufferSize(), conn, allocator);
        context.setAttribute(RESPONSE_SOURCE_BUFFER, outputBuffer);
        OutputStream os = new ContentOutputStream(outputBuffer);

        // create the default response to this request
        ProtocolVersion httpVersion = request.getRequestLine().getProtocolVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);

        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);

        if (metrics != null) {
            metrics.incrementMessagesReceived();
        }
        // hand off processing of the request to a thread off the pool
        ServerWorker worker = new ServerWorker(cfgCtx, scheme.getName(), metrics, conn, this, request, is,
                response, os, listenerContext.isRestDispatching(),
                listenerContext.getHttpGetRequestProcessor());

        if (workerPool != null) {
            workerPool.execute(worker);
        } else if (executor != null) {
            Map<String, String> headers = new HashMap<String, String>();
            for (Header header : request.getAllHeaders()) {
                headers.put(header.getName(), header.getValue());
            }

            EvaluatorContext evaluatorContext = new EvaluatorContext(request.getRequestLine().getUri(),
                    headers);
            int priority = parser.parse(evaluatorContext);
            executor.execute(worker, priority);
        }

        // See if the client expects a 100-Continue
        Header expect = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE);
        if (expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue())) {
            HttpResponse ack = new BasicHttpResponse(request.getProtocolVersion(), HttpStatus.SC_CONTINUE,
                    "Continue");
            conn.submitResponse(ack);
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Expect :100 Continue hit, sending ack back to the server");
            }
            return;
        }

    } catch (Exception e) {
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e,
                conn);
    }
}