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

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

Introduction

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

Prototype

public ContentOutputStream(final ContentOutputBuffer buffer) 

Source Link

Usage

From source file:marytts.server.http.AudioStreamNHttpEntity.java

/**
 * Wait for the SharedOutputBuffer to become available, write audio data to it.
 *///  w  w w . j a  v a2 s .  c  o m
public void run() {
    this.logger = MaryUtils.getLogger(Thread.currentThread().getName());
    // We must wait until produceContent() is called:
    while (out == null) {
        synchronized (mutex) {
            try {
                mutex.wait();
            } catch (InterruptedException e) {
            }
        }
    }
    assert out != null;
    ContentOutputStream outStream = new ContentOutputStream(out);
    try {
        AudioSystem.write(audio, audioType, outStream);
        outStream.flush();
        outStream.close();
        logger.info("Finished writing output");
    } catch (IOException ioe) {
        logger.info("Cannot write output, client seems to have disconnected. ", ioe);
        maryRequest.abort();
    }
}

From source file:marytts.tools.perceptiontest.AudioStreamNHttpEntity.java

/**
 * Wait for the SharedOutputBuffer to become available, write audio data to it.
 *//*  w w  w  .  j a  va2s .  c o m*/
public void run() {
    this.logger = MaryUtils.getLogger(Thread.currentThread().getName());
    // We must wait until produceContent() is called:
    while (out == null) {
        synchronized (mutex) {
            try {
                mutex.wait();
            } catch (InterruptedException e) {
            }
        }
    }
    assert out != null;
    ContentOutputStream outStream = new ContentOutputStream(out);
    try {
        AudioSystem.write(audio, audioType, outStream);
        outStream.flush();
        outStream.close();
        logger.info("Finished writing output");
    } catch (IOException ioe) {
        logger.info("Cannot write output, client seems to have disconnected. ", ioe);
        System.err.println("Cannot write output, client seems to have disconnected." + ioe);
        maryRequest.abort();
    }
}

From source file:org.apache.synapse.transport.passthru.api.PassThroughNHttpGetProcessor.java

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);
            }//  w  w w  . j a  v a2  s .c o m
        }
    } 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);
    }
}

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

/**
 * 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//from w w w  . j  ava  2s . com
 */
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);
        }
    }
}

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

/**
 * Create synapse.response-source-buffer for GET and HEAD Http methods
 * @param method  Http Method// w  w w  .  java2  s. c om
 * @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;
}

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

/**
 * Process a new incoming request/*from   w  w  w .  j a v a 2 s.co  m*/
 * @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);
    }
}

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

public void requestReceived(NHttpServerConnection conn) {
    try {//  w  ww . j  a  va 2s. c o m

        //System.out.println("============ SourceHandler : requestReceived ===============");

        HttpContext _context = conn.getContext();
        _context.setAttribute(PassThroughConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());

        if (!org.siddhiesb.transport.passthru.SourceContext.assertState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.REQUEST_READY)
                && !org.siddhiesb.transport.passthru.SourceContext.assertState(conn,
                        org.siddhiesb.transport.passthru.ProtocolState.WSDL_RESPONSE_DONE)) {
            handleInvalidState(conn, "Request received");
            return;
        }
        // we have received a message over this connection. So we must inform the pool
        sourceConfiguration.getSourceConnections().useConnection(conn);

        // at this point we have read the HTTP Headers
        org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.REQUEST_HEAD);

        SourceRequest request = new SourceRequest(sourceConfiguration, conn.getHttpRequest(), conn);

        org.siddhiesb.transport.passthru.SourceContext.setRequest(conn, request);

        request.start(conn);

        String method = request.getRequest() != null
                ? request.getRequest().getRequestLine().getMethod().toUpperCase()
                : "";
        OutputStream os = null;
        if ("GET".equals(method) || "HEAD".equals(method)) {
            HttpContext context = request.getConnection().getContext();
            ContentOutputBuffer outputBuffer = new SimpleOutputBuffer(8192, new HeapByteBufferAllocator());
            context.setAttribute("synapse.response-source-buffer", outputBuffer);
            os = new ContentOutputStream(outputBuffer);
        }

        sourceConfiguration.getWorkerPool().execute(new org.siddhiesb.transport.passthru.ServerWorker(request,
                sourceConfiguration, os, mediationEngine));
    } catch (HttpException e) {
        log.error(e.getMessage(), e);

        informReaderError(conn);

        org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn);
    } catch (IOException e) {
        logIOException(conn, e);

        informReaderError(conn);

        org.siddhiesb.transport.passthru.SourceContext.updateState(conn,
                org.siddhiesb.transport.passthru.ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn);
    }
}