Example usage for java.nio.channels Pipe source

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

Introduction

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

Prototype

public abstract SourceChannel source();

Source Link

Document

Returns this pipe's source 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  ava 2s. c  om
    consumer.start();
}

From source file:fr.gael.dhus.util.stream.ProductDownloadStreamFactory.java

@Override
public synchronized InputStream generateInputStream(ProductInfo productInfo, Source source,
        SynchronizerRules rules, long skip) {
    // generate HTTP client
    int timeout = rules.getTimeout().intValue();
    InterruptibleHttpClient client = new InterruptibleHttpClient(
            new BasicAuthHttpClientProducer(source.getUsername(), source.getPassword(), timeout));

    // generate download url
    String url = productInfo.getDownloadUrl(source.getUrl());

    // generate stream
    boolean canResume;
    String etag;//from w  w w  .ja v  a2s  .com
    HttpResponse headers;
    Thread downloadThread = null;
    try {
        headers = client.interruptibleHead(url);
        // check availability of content
        if (headers.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            return null;
        }
        // retrieve content information
        if (headers.containsHeader(HTTP_HEADER_ETAG)) {
            etag = headers.getFirstHeader(HTTP_HEADER_ETAG).getValue();
            canResume = headers.containsHeader(HTTP_HEADER_ACCEPT_RANGE);
        } else {
            etag = null;
            canResume = false;
        }

        Pipe pipe = Pipe.open();
        DownloadTask downloadTask = new DownloadTask(pipe, client, url, etag, skip, productInfo.getSize(),
                rules.getAttempts(), canResume);
        downloadThread = new Thread(downloadTask, THREAD_NAME);
        downloadThread.start();

        return Channels.newInputStream(pipe.source());
    } catch (InterruptedException | IOException e) {
        if (downloadThread != null) {
            downloadThread.interrupt();
        }
        return null;
    }
}

From source file:fr.gael.dhus.util.http.DownloadableProduct.java

@Override
public <T> T getImpl(Class<? extends T> cl) {
    if (InputStream.class.isAssignableFrom(cl)) {
        try {/*  ww w.  ja v  a 2  s.co  m*/
            Pipe pipe = Pipe.open();
            DownloadTask dltask = new DownloadTask(pipe);
            downloadThread = new Thread(dltask, "Product Download");
            downloadThread.start();

            InputStream is = Channels.newInputStream(pipe.source());
            return cl.cast(is);
        } catch (IOException ex) {
            LOGGER.error("could not create pipe", ex);
        }
    }
    return null;
}

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
 *///from w w  w  .  j a v  a  2 s  .c om
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//  w w w.  jav  a  2s.  c o 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();
        sink = pipe.sink();//www. ja va 2 s  . c om

    } 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  .j  a  v  a  2s .  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);
    }//from  ww  w  .j a  v  a2  s .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;
}