Search in sources :

Example 1 with ContentOutputStream

use of org.apache.http.nio.entity.ContentOutputStream in project wso2-synapse by wso2.

the class Axis2HttpRequest method streamMessageContents.

/**
 * Start streaming the message into the Pipe, so that the contents could be read off the source
 * channel returned by getSourceChannel()
 *
 * @throws AxisFault on error
 */
public void streamMessageContents() throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Start streaming outgoing http request : [Message ID : " + msgContext.getMessageID() + "]");
        if (log.isTraceEnabled()) {
            log.trace("Message [Request Message ID : " + msgContext.getMessageID() + "] " + "[Request Message Payload : [ " + msgContext.getEnvelope() + "]");
        }
    }
    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    int senderTimeout = cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000);
    long startTime = System.currentTimeMillis();
    synchronized (this) {
        while (!readyToStream && !completed) {
            try {
                this.wait(senderTimeout + 10000);
                if ((startTime + senderTimeout + 5000) < System.currentTimeMillis()) {
                    handleException("Thread " + Thread.currentThread().getName() + " is blocked longer than the send timeout when trying to send the message :" + msgContext.getMessageID() + ". Releasing thread", new AxisFault("Sender thread was not notified within send timeout"));
                }
            } catch (InterruptedException ignore) {
            }
        }
    }
    if (!completed) {
        OutputStream out = new ContentOutputStream(outputBuffer);
        try {
            if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
                writeMessageFromTempData(out);
            } else {
                if (chunked) {
                    messageFormatter.writeTo(msgContext, format, out, false);
                } else {
                    writeMessageFromTempData(out);
                }
            }
        } catch (Exception e) {
            Throwable t = e.getCause();
            if (t != null && t.getCause() != null && t.getCause() instanceof ClosedChannelException) {
                if (log.isDebugEnabled()) {
                    log.debug("Ignore closed channel exception, as the " + "SessionRequestCallback handles this exception");
                }
            } else {
                Integer errorCode = msgContext == null ? null : (Integer) msgContext.getProperty(NhttpConstants.ERROR_CODE);
                if (errorCode == null || errorCode == NhttpConstants.SEND_ABORT) {
                    if (log.isDebugEnabled()) {
                        log.debug("Remote server aborted request being sent, and responded");
                    }
                } else {
                    if (e instanceof AxisFault) {
                        throw (AxisFault) e;
                    } else {
                        handleException("Error streaming message context", e);
                    }
                }
            }
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                handleException("Error closing outgoing message stream", e);
            }
            setSendingCompleted(true);
        }
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) ClosedChannelException(java.nio.channels.ClosedChannelException) OutputStream(java.io.OutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) HttpException(org.apache.http.HttpException)

Example 2 with ContentOutputStream

use of org.apache.http.nio.entity.ContentOutputStream in project wso2-synapse by wso2.

the class SourceHandler method getOutputStream.

/**
 * Create synapse.response-source-buffer for GET and HEAD Http methods
 * @param method  Http Method
 * @param request Source Request
 * @return OutputStream
 */
public OutputStream getOutputStream(String method, SourceRequest request) {
    OutputStream os = null;
    if (HttpMethod.GET.equals(method) || HttpMethod.HEAD.equals(method)) {
        HttpContext context = request.getConnection().getContext();
        ContentOutputBuffer outputBuffer = new SimpleOutputBuffer(sourceConfiguration.getIOBufferSize(), new HeapByteBufferAllocator());
        context.setAttribute("synapse.response-source-buffer", outputBuffer);
        os = new ContentOutputStream(outputBuffer);
    }
    return os;
}
Also used : SimpleOutputBuffer(org.apache.http.nio.util.SimpleOutputBuffer) HeapByteBufferAllocator(org.apache.http.nio.util.HeapByteBufferAllocator) OutputStream(java.io.OutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) HttpContext(org.apache.http.protocol.HttpContext) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) ContentOutputBuffer(org.apache.http.nio.util.ContentOutputBuffer)

Example 3 with ContentOutputStream

use of org.apache.http.nio.entity.ContentOutputStream in project wso2-synapse by wso2.

the class PassThroughNHttpGetProcessor method process.

public void process(HttpRequest request, HttpResponse response, MessageContext msgContext, NHttpServerConnection conn, OutputStream ostream, boolean isRestDispatching) {
    String uri = request.getRequestLine().getUri();
    String serviceName = getServiceName(request);
    Map<String, String> parameters = new HashMap<String, String>();
    int pos = uri.indexOf("?");
    if (pos != -1) {
        msgContext.setTo(new EndpointReference(uri.substring(0, pos)));
        StringTokenizer st = new StringTokenizer(uri.substring(pos + 1), "&");
        while (st.hasMoreTokens()) {
            String param = st.nextToken();
            pos = param.indexOf("=");
            if (pos != -1) {
                parameters.put(param.substring(0, pos), param.substring(pos + 1));
            } else {
                parameters.put(param, null);
            }
        }
    } else {
        msgContext.setTo(new EndpointReference(uri));
    }
    SimpleOutputBuffer outputBuffer = (SimpleOutputBuffer) conn.getContext().getAttribute(PASS_THROUGH_RESPONSE_SOURCE_BUFFER);
    ContentOutputStream os = new ContentOutputStream(outputBuffer);
    if (isServiceListBlocked(uri)) {
        sendResponseAndFinish(response, HttpStatus.SC_FORBIDDEN, conn, os, msgContext);
    } else if (uri.equals("/favicon.ico")) {
        response.addHeader(LOCATION, "http://ws.apache.org/favicon.ico");
        sendResponseAndFinish(response, HttpStatus.SC_MOVED_PERMANENTLY, conn, os, msgContext);
    } else if (serviceName != null && parameters.containsKey("wsdl")) {
        generateWsdl(response, msgContext, conn, os, serviceName, parameters);
    } else if (serviceName != null && parameters.containsKey("wsdl2")) {
        generateWsdl2(response, msgContext, conn, os, serviceName);
    } else if (serviceName != null && parameters.containsKey("xsd")) {
        generateXsd(response, msgContext, conn, os, serviceName, parameters);
    } else {
        msgContext.setProperty(PassThroughConstants.REST_GET_DELETE_INVOKE, true);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) SimpleOutputBuffer(org.apache.http.nio.util.SimpleOutputBuffer) HashMap(java.util.HashMap) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 4 with ContentOutputStream

use of org.apache.http.nio.entity.ContentOutputStream in project wso2-synapse by wso2.

the class ServerHandler method requestReceived.

/**
 * Process a new incoming request
 * @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");
    if (isMessageSizeValidationEnabled) {
        context.setAttribute(NhttpConstants.MESSAGE_SIZE_VALIDATION_SUM, 0);
    }
    // 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 NhttpSharedOutputBuffer(bufferSize, conn, allocator, socketTimeout);
        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);
    }
}
Also used : ServerConnectionDebug(org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug) EvaluatorContext(org.apache.synapse.commons.evaluators.EvaluatorContext) ContentInputStream(org.apache.http.nio.entity.ContentInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) IOException(java.io.IOException) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ContentInputStream(org.apache.http.nio.entity.ContentInputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ContentOutputStream (org.apache.http.nio.entity.ContentOutputStream)4 OutputStream (java.io.OutputStream)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 SimpleOutputBuffer (org.apache.http.nio.util.SimpleOutputBuffer)2 InputStream (java.io.InputStream)1 URISyntaxException (java.net.URISyntaxException)1 ClosedChannelException (java.nio.channels.ClosedChannelException)1 Map (java.util.Map)1 StringTokenizer (java.util.StringTokenizer)1 AxisFault (org.apache.axis2.AxisFault)1 EndpointReference (org.apache.axis2.addressing.EndpointReference)1 HttpException (org.apache.http.HttpException)1 BasicHttpEntity (org.apache.http.entity.BasicHttpEntity)1 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)1 ContentInputStream (org.apache.http.nio.entity.ContentInputStream)1 ContentOutputBuffer (org.apache.http.nio.util.ContentOutputBuffer)1 HeapByteBufferAllocator (org.apache.http.nio.util.HeapByteBufferAllocator)1 HttpContext (org.apache.http.protocol.HttpContext)1 EvaluatorContext (org.apache.synapse.commons.evaluators.EvaluatorContext)1