Example usage for java.nio.channels Pipe sink

List of usage examples for java.nio.channels Pipe sink

Introduction

In this page you can find the example usage for java.nio.channels Pipe sink.

Prototype

public abstract SinkChannel sink();

Source Link

Document

Returns this pipe's sink channel.

Usage

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    Pipe pipe = Pipe.open();
    WritableByteChannel out = pipe.sink();
    ReadableByteChannel in = pipe.source();

    NumberProducer producer = new NumberProducer(out, 200);
    NumberConsumer consumer = new NumberConsumer(in);
    producer.start();//w w  w  . j a v  a  2s  . c om
    consumer.start();
}

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

/**
 * Process a response received for the request sent out
 * @param conn the connection being processed
 *//*  w  w  w.j av a 2 s  . com*/
public void responseReceived(final NHttpClientConnection conn) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();

    try {
        Pipe responsePipe = Pipe.open();
        context.setAttribute(RESPONSE_SINK_CHANNEL, responsePipe.sink());

        BasicHttpEntity entity = new BasicHttpEntity();
        if (response.getStatusLine().getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        context.setAttribute(HttpContext.HTTP_RESPONSE, response);

        workerPool.execute(new ClientWorker(cfgCtx, Channels.newInputStream(responsePipe.source()),
                (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT)));

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    }
}

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

/**
 * Process a new incoming request//from w w w.j a va2  s .  co  m
 * @param conn the connection
 */
public void requestReceived(final NHttpServerConnection conn) {

    HttpContext context = conn.getContext();
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(HttpContext.HTTP_REQUEST, request);

    // allocate temporary buffers to process this request
    context.setAttribute(REQUEST_BUFFER, ByteBuffer.allocate(2048));
    context.setAttribute(RESPONSE_BUFFER, ByteBuffer.allocate(2048));

    try {
        Pipe requestPipe = Pipe.open(); // the pipe used to process the request
        Pipe responsePipe = Pipe.open(); // the pipe used to process the response
        context.setAttribute(REQUEST_SINK_CHANNEL, requestPipe.sink());
        context.setAttribute(RESPONSE_SOURCE_CHANNEL, responsePipe.source());

        // create the default response to this request
        HttpVersion httpVersion = request.getRequestLine().getHttpVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);
        response.setParams(this.params);

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

        // hand off processing of the request to a thread off the pool
        workerPool.execute(
                new ServerWorker(cfgCtx, conn, this, request, Channels.newInputStream(requestPipe.source()),
                        response, Channels.newOutputStream(responsePipe.sink())));

    } catch (IOException e) {
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e,
                conn);
    }
}

From source file:org.apache.axis2.transport.nhttp.util.PipeImpl.java

public PipeImpl() throws IOException {
    if (useNative) {
        Pipe pipe = Pipe.open();
        source = pipe.source();//  w  ww  .j  a va2s. c o m
        sink = pipe.sink();

    } else {
        PipedInputStream pipedIn = new PipedInputStream();
        try {
            pipedOut = new PipedOutputStream(pipedIn);
        } catch (IOException e) {
            e.printStackTrace();
        }

        source = Channels.newChannel(pipedIn);
        sink = Channels.newChannel(pipedOut);
    }
}

From source file:org.apache.hadoop.net.TestSocketIOWithTimeout.java

public void testSocketIOWithTimeout() throws IOException {

    // first open pipe:
    Pipe pipe = Pipe.open();
    Pipe.SourceChannel source = pipe.source();
    Pipe.SinkChannel sink = pipe.sink();

    try {/*from w w w  .  ja va2s . c o m*/
        InputStream in = new SocketInputStream(source, TIMEOUT);
        OutputStream out = new SocketOutputStream(sink, TIMEOUT);

        byte[] writeBytes = TEST_STRING.getBytes();
        byte[] readBytes = new byte[writeBytes.length];

        out.write(writeBytes);
        doIO(null, out);

        in.read(readBytes);
        assertTrue(Arrays.equals(writeBytes, readBytes));
        doIO(in, null);

        /*
         * Verify that it handles interrupted threads properly.
         * Use a large timeout and expect the thread to return quickly.
         */
        in = new SocketInputStream(source, 0);
        Thread thread = new Thread(new ReadRunnable(in));
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
        }

        thread.interrupt();

        try {
            thread.join();
        } catch (InterruptedException e) {
            throw new IOException("Unexpected InterruptedException : " + e);
        }

        //make sure the channels are still open
        assertTrue(source.isOpen());
        assertTrue(sink.isOpen());

        out.close();
        assertFalse(sink.isOpen());

        // close sink and expect -1 from source.read()
        assertEquals(-1, in.read());

        // make sure close() closes the underlying channel.
        in.close();
        assertFalse(source.isOpen());

    } finally {
        if (source != null) {
            source.close();
        }
        if (sink != null) {
            sink.close();
        }
    }
}

From source file:org.jboss.qa.jcontainer.util.executor.ProcessExecutor.java

public Process asyncExecute() throws IOException {
    if (processBuilder == null) {
        processBuilder = new ProcessBuilder(commands);
    }/*  ww  w.j  a va2s  .c  o m*/

    if (outputStream == null) {
        if (SystemUtils.IS_OS_HP_UX) {
            outputStream = System.out;
        } else {
            processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        }
    }
    if (errorStream == null && !redirectError) {
        if (SystemUtils.IS_OS_HP_UX) {
            outputStream = System.err;
        } else {
            processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
        }
    }
    processBuilder.redirectErrorStream(redirectError);

    final Process process = processBuilder.start();

    final ExecutorService executeService = Executors.newCachedThreadPool();
    final List<Future> futures = new ArrayList<>();

    if (outputStream != null) {
        final Pipe pipe = Pipe.open();
        futures.add(executeService
                .submit(new CopyIntoChannel(Channels.newChannel(process.getInputStream()), pipe.sink())));
        futures.add(
                executeService.submit(new CopyIntoChannel(pipe.source(), Channels.newChannel(outputStream))));
    }
    if (errorStream != null && !redirectError) {
        final Pipe pipe = Pipe.open();
        futures.add(executeService
                .submit(new CopyIntoChannel(Channels.newChannel(process.getErrorStream()), pipe.sink())));
        futures.add(
                executeService.submit(new CopyIntoChannel(pipe.source(), Channels.newChannel(errorStream))));
    }

    final Future<Integer> future = executeService.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            process.waitFor();
            for (Future f : futures) {
                f.get();
            }
            return process.exitValue();
        }
    });

    final Process proxyProcess = new ProcessWrapper(process, future);

    executeService.shutdown();
    return proxyProcess;
}