Example usage for java.nio.channels CompletionHandler CompletionHandler

List of usage examples for java.nio.channels CompletionHandler CompletionHandler

Introduction

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

Prototype

CompletionHandler

Source Link

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("/asynchronous.txt"),
            StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {

        @Override//from   w w  w . j  a v a  2 s . co m
        public void completed(Integer result, Object attachment) {
            System.out.println("Attachment: " + attachment + " " + result + " bytes written");
            System.out.println("CompletionHandler Thread ID: " + Thread.currentThread().getId());
        }

        @Override
        public void failed(Throwable e, Object attachment) {
            System.err.println("Attachment: " + attachment + " failed with:");
            e.printStackTrace();
        }
    };

    System.out.println("Main Thread ID: " + Thread.currentThread().getId());
    fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0, "First Write", handler);
    fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0, "Second Write", handler);

}

From source file:Test.java

public static void main(String args[]) throws Exception {
    ExecutorService pool = new ScheduledThreadPoolExecutor(3);
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("data.txt"),
            EnumSet.of(StandardOpenOption.READ), pool);
    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
        public synchronized void completed(Integer result, ByteBuffer attachment) {
            for (int i = 0; i < attachment.limit(); i++) {
                System.out.print((char) attachment.get(i));
            }/*from  w ww. ja  va  2 s.com*/
        }

        public void failed(Throwable e, ByteBuffer attachment) {
        }
    };
    final int bufferCount = 5;
    ByteBuffer buffers[] = new ByteBuffer[bufferCount];
    for (int i = 0; i < bufferCount; i++) {
        buffers[i] = ByteBuffer.allocate(10);
        fileChannel.read(buffers[i], i * 10, buffers[i], handler);
    }
    pool.awaitTermination(1, TimeUnit.SECONDS);
    for (ByteBuffer byteBuffer : buffers) {
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println((char) byteBuffer.get(i));
        }
    }
}

From source file:Test.java

public static void main(String args[]) throws Exception {
    ExecutorService pool = new ScheduledThreadPoolExecutor(3);
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("data.txt"),
            EnumSet.of(StandardOpenOption.READ), pool);
    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
        @Override/*from   w w w  .j  ava 2s .  c o m*/
        public synchronized void completed(Integer result, ByteBuffer attachment) {
            for (int i = 0; i < attachment.limit(); i++) {
                System.out.println((char) attachment.get(i));
            }
        }

        @Override
        public void failed(Throwable e, ByteBuffer attachment) {
        }
    };
    final int bufferCount = 5;
    ByteBuffer buffers[] = new ByteBuffer[bufferCount];
    for (int i = 0; i < bufferCount; i++) {
        buffers[i] = ByteBuffer.allocate(10);
        fileChannel.read(buffers[i], i * 10, buffers[i], handler);
    }
    pool.awaitTermination(1, TimeUnit.SECONDS);
    for (ByteBuffer byteBuffer : buffers) {
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.print((char) byteBuffer.get(i));
        }
    }
}

From source file:net.transmutator4j.RunTransmutator4j.java

@Override
public void run() {

    long startTime = System.currentTimeMillis();
    InetAddress localhost;//  w  w  w . j a va2 s  .  c  o m
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new IllegalStateException("can not resolve local host", e);
    }
    //socket get dynamically generated port
    SocketAddress socket = new InetSocketAddress(localhost, 0);
    AsynchronousChannelGroup group;
    try {
        group = AsynchronousChannelGroup.withFixedThreadPool(10, Executors.defaultThreadFactory());
    } catch (IOException e1) {
        throw new IllegalStateException("can not create channel group", e1);
    }

    try (

            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(socket,
                    1);

    ) {

        int numTotalTests = runUnmutatedTests();
        long unmutatedTimeEnd = System.currentTimeMillis();
        long unmutatedElapsedTime = unmutatedTimeEnd - startTime;
        listener.testInfo(numTotalTests, unmutatedElapsedTime);
        System.out.println("unmutated tests took " + unmutatedElapsedTime + " ms");
        long timeOut = computeTimeoutTime(unmutatedElapsedTime);
        InetSocketAddress inetSocketAddress = (InetSocketAddress) server.getLocalAddress();
        int port = inetSocketAddress.getPort();
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel resultChannel, Object attachment) {
                try {
                    ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(resultChannel));
                    MutationTestResult testResult = (MutationTestResult) in.readObject();

                    in.close();

                    listener.mutationResult(testResult);
                    boolean stillPassed = testResult.testsStillPassed();
                    System.out.print(stillPassed ? "P" : ".");
                    System.out.flush();
                    numberOfMutationsMade++;

                    if (stillPassed) {
                        numberOfMutationsThatStillPassedTests++;
                    }
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new RuntimeException("error getting test result ", e);
                }
                //accept a new connection
                server.accept(null, this);

            }

            @Override
            public void failed(Throwable e, Object attachment) {
                //   System.err.println(attachment + " failed with:" + e.getClass().getName());
                //    e.printStackTrace();
            }
        });

        OUTER: for (String classToMutate : new ClassPathClassRepository()) {
            boolean shouldMutate = shouldMutate(classToMutate);
            if (shouldMutate) {
                System.out.printf("mutating %s%n", classToMutate);
                boolean done = false;
                int mutationCount = 0;
                while (!done) {
                    JavaProcessBuilder builder = new JavaProcessBuilder(

                            "net.transmutator4j.Transmutator4j", classToMutate, nameOfTestSuite,
                            Integer.toString(mutationCount), Integer.toString(port));

                    try {
                        TimedProcess timedProcess = new TimedProcess(builder.getBuilder(), timeOut);
                        int exitValue = timedProcess.call();

                        TransmutatorUtil.EXIT_STATES exitState = TransmutatorUtil.EXIT_STATES
                                .getValueFor(exitValue);
                        if (exitState == TransmutatorUtil.EXIT_STATES.NO_MUTATIONS_MADE) {
                            done = true;
                            System.out.println();
                        } else if (exitState == TransmutatorUtil.EXIT_STATES.TIMED_OUT) {
                            numberOfMutationsThatTimedOut++;

                        }

                    } catch (InterruptedException e) {
                        System.err.println("detected cancellation...halting");
                        //stop iterating through all the classes
                        //by breaking out of outer for loop
                        break OUTER;
                    }

                    mutationCount++;

                }

            }
        }
        //kill any waiting connections this will cause the completionHandler's fail to get called
        group.shutdownNow();
        //group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

        long endTime = System.currentTimeMillis();
        System.out.printf("took %d ms to run %d mutations of which %d caused timeouts and %d still passed%n",
                (endTime - startTime), numberOfMutationsMade, numberOfMutationsThatTimedOut,
                numberOfMutationsThatStillPassedTests);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (listener != null) {
            try {
                listener.close();
            } catch (IOException ignored) {
                //ignore
            }
        }
        group.shutdown();
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.AsyncFSWAL.java

private void sync(final AsyncWriter writer, final long processedTxid) {
    fileLengthAtLastSync = writer.getLength();
    final long startTimeNs = System.nanoTime();
    writer.sync(new CompletionHandler<Long, Void>() {

        @Override/*from   w ww.jav  a  2 s  .  co m*/
        public void completed(Long result, Void attachment) {
            highestSyncedTxid.set(processedTxid);
            int syncCount = finishSync(true);
            for (Iterator<FSWALEntry> iter = unackedEntries.iterator(); iter.hasNext();) {
                if (iter.next().getTxid() <= processedTxid) {
                    iter.remove();
                } else {
                    break;
                }
            }
            postSync(System.nanoTime() - startTimeNs, syncCount);
            tryFinishRoll();
            if (!rollWriterLock.tryLock()) {
                return;
            }
            try {
                if (writer.getLength() >= logrollsize) {
                    requestLogRoll();
                }
            } finally {
                rollWriterLock.unlock();
            }
        }

        @Override
        public void failed(Throwable exc, Void attachment) {
            LOG.warn("sync failed", exc);
            // Here we depends on the implementation of FanOutOneBlockAsyncDFSOutput and netty.
            // When error occur, FanOutOneBlockAsyncDFSOutput will fail all pending flush requests. It
            // is execute inside EventLoop. And in DefaultPromise in netty, it will notifyListener
            // directly if it is already in the EventLoop thread. And in the listener method, it will
            // call us. So here we know that all failed flush request will call us continuously, and
            // before the last one finish, no other task can be executed in EventLoop. So here we are
            // safe to use writerBroken as a guard.
            // Do not forget to revisit this if we change the implementation of
            // FanOutOneBlockAsyncDFSOutput!
            synchronized (waitingConsumePayloads) {
                if (writerBroken) {
                    return;
                }
                // schedule a periodical task to check if log roller is exited. Otherwise the the sync
                // request maybe blocked forever since we are still waiting for a new writer to write the
                // pending data and sync it...
                logRollerExitedChecker = new LogRollerExitedChecker();
                // we are currently in the EventLoop thread, so it is safe to set the future after
                // schedule it since the task can not be executed before we release the thread.
                logRollerExitedChecker.setFuture(eventLoop.scheduleAtFixedRate(logRollerExitedChecker,
                        logRollerExitedCheckIntervalMs, logRollerExitedCheckIntervalMs, TimeUnit.MILLISECONDS));
                writerBroken = true;
            }
            for (Iterator<FSWALEntry> iter = unackedEntries.descendingIterator(); iter.hasNext();) {
                waitingAppendEntries.addFirst(iter.next());
            }
            highestUnsyncedTxid = highestSyncedTxid.get();
            if (rollPromise != null) {
                rollPromise.trySuccess(null);
                rollPromise = null;
                return;
            }
            // request a roll.
            if (!rollWriterLock.tryLock()) {
                return;
            }
            try {
                requestLogRoll();
            } finally {
                rollWriterLock.unlock();
            }
        }
    }, null);
}

From source file:ubicrypt.core.Utils.java

public static Observable<Long> write(final Path fullPath, final InputStream inputStream) {
    return Observable.create(subscriber -> {
        try {// w ww.j ava2 s  .co m
            final AtomicLong offset = new AtomicLong(0);
            final AsynchronousFileChannel afc = AsynchronousFileChannel.open(fullPath, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE);
            afc.lock(new Object(), new CompletionHandler<FileLock, Object>() {
                @Override
                public void completed(final FileLock lock, final Object attachment) {
                    //acquired lock
                    final byte[] buf = new byte[1 << 16];
                    try {
                        final int len = inputStream.read(buf);
                        if (len == -1) {
                            unsubscribe(subscriber, inputStream, lock);
                            return;
                        }
                        afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)), offset.get(), null,
                                new CompletionHandler<Integer, Object>() {
                                    @Override
                                    public void completed(final Integer result, final Object attachment) {
                                        //written chunk of bytes
                                        subscriber.onNext(offset.addAndGet(result));
                                        final byte[] buf = new byte[1 << 16];
                                        int len;
                                        try {
                                            len = inputStream.read(buf);
                                            if (len == -1) {
                                                unsubscribe(subscriber, inputStream, lock);
                                                log.debug("written:{}", fullPath);
                                                return;
                                            }
                                        } catch (final IOException e) {
                                            subscriber.onError(e);
                                            return;
                                        }
                                        if (len == -1) {
                                            unsubscribe(subscriber, inputStream, lock);
                                            log.debug("written:{}", fullPath);
                                            return;
                                        }
                                        afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)),
                                                offset.get(), null, this);
                                    }

                                    @Override
                                    public void failed(final Throwable exc, final Object attachment) {
                                        subscriber.onError(exc);
                                    }
                                });
                    } catch (final Exception e) {
                        close(inputStream, lock);
                        subscriber.onError(e);
                    }
                }

                @Override
                public void failed(final Throwable exc, final Object attachment) {
                    log.error("error on getting lock for:{}, error:{}", fullPath, exc.getMessage());
                    try {
                        inputStream.close();
                    } catch (final IOException e) {
                    }
                    subscriber.onError(exc);
                }
            });

        } catch (final Exception e) {
            log.error("error on file:{}", fullPath);
            subscriber.onError(e);
        }
    });
}

From source file:ubicrypt.core.Utils.java

public static InputStream readIs(final Path path) {
    final PipedInputStream pis = new PipedInputStream();
    final AtomicLong pos = new AtomicLong(0);
    try {//  ww  w. j  av a2  s. c  om
        final PipedOutputStream ostream = new PipedOutputStream(pis);
        final AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        final ByteBuffer buffer = ByteBuffer.allocate(1 << 16);
        channel.read(buffer, pos.get(), buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(final Integer result, final ByteBuffer buf) {
                try {
                    if (result == -1) {
                        ostream.close();
                        return;
                    }
                    final byte[] bytes = new byte[result];
                    System.arraycopy(buf.array(), 0, bytes, 0, result);
                    ostream.write(bytes);
                    ostream.flush();
                    if (result < 1 << 16) {
                        ostream.close();
                        return;
                    }
                    pos.addAndGet(result);
                    final ByteBuffer buffer = ByteBuffer.allocate(1 << 16);
                    channel.read(buffer, pos.get(), buffer, this);
                } catch (final IOException e) {
                    Throwables.propagate(e);
                }
            }

            @Override
            public void failed(final Throwable exc, final ByteBuffer attachment) {
                log.error(exc.getMessage(), exc);
            }
        });
    } catch (final IOException e) {
        if (e instanceof NoSuchFileException) {
            throw new NotFoundException(path);
        }
        Throwables.propagate(e);
    }
    return pis;
}

From source file:ubicrypt.core.Utils.java

private static void read(final AtomicLong pos, final ByteBuffer buffer, final AsynchronousFileChannel channel,
        final Subscriber<? super byte[]> subscriber) {
    channel.read(buffer, pos.get(), pos, new CompletionHandler<Integer, AtomicLong>() {
        @Override//from   w w w. j  a v a  2  s.  c  o  m
        public void completed(final Integer result, final AtomicLong attachment) {
            if (result == -1) {
                subscriber.onCompleted();
                return;
            }
            subscriber.onNext(buffer.array());
            if (result < 1 << 16) {
                subscriber.onCompleted();
                return;
            }
            pos.addAndGet(result);
            read(pos, ByteBuffer.allocate(1 << 16), channel, subscriber);
        }

        @Override
        public void failed(final Throwable exc, final AtomicLong attachment) {
            subscriber.onError(exc);
        }
    });
}