Example usage for com.google.common.io Closer register

List of usage examples for com.google.common.io Closer register

Introduction

In this page you can find the example usage for com.google.common.io Closer register.

Prototype


public <C extends Closeable> C register(@Nullable C closeable) 

Source Link

Document

Registers the given closeable to be closed when this Closer is #close closed .

Usage

From source file:com.tinspx.util.io.ByteUtils.java

/**
 * Copies the entire contents of {@code from} into {@code to}.
 *
 * @param from the source to read bytes from
 * @param to the destination to copy bytes read from {@code from} into
 * @throws IOException if an IOException occurs
 * @throws NullPointerException if either {@code from} or {@code to} is null
 *///  www  . ja  v  a 2 s.  c o m
@ThreadLocalArray(8192)
public static void copy(@NonNull ByteBuffer from, @NonNull ByteSink to) throws IOException {
    final Closer closer = Closer.create();
    try {
        OutputStream out = closer.register(to.openStream());
        copy(from, out);
        out.flush();
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

/**
 * Copies the entire contents of {@code from}, starting at index {@code off}
 * (inclusive) and ending at index {@code off + len} (exclusive), into
 * {@code to}. This provides an alternative to
 * {@link ByteSink#write(byte[])}./* ww w  .j  av  a  2  s.  co  m*/
 *
 * @param from the source to read bytes from
 * @param off the offset into {@code from} to start copying
 * @param len the number of bytes to copy starting at index {@code off}
 * @param to the destination to copy bytes read from {@code from} into
 * @throws IOException if an IOException occurs
 * @throws NullPointerException if either {@code from} or {@code to} is null
 * @see ByteSink#write(byte[])
 */
public static void copy(byte[] from, int off, int len, @NonNull ByteSink to) throws IOException {
    checkPositionIndexes(off, off + len, from.length);
    final Closer closer = Closer.create();
    try {
        OutputStream out = closer.register(to.openStream());
        out.write(from, off, len);
        out.flush();
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

@ThreadLocalArray(8192)
public static boolean contentEquals(@NonNull ByteSource source1, @NonNull ByteBuffer buffer)
        throws IOException {
    final Closer closer = Closer.create();
    try {/* w w  w .ja va2 s .c  o  m*/
        return contentEquals(closer.register(source1.openStream()), buffer);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

@ThreadLocalArray(8192)
public static boolean contentEquals(@NonNull ByteSource source, @NonNull @WillNotClose InputStream in)
        throws IOException {
    final Closer closer = Closer.create();
    try {//w w  w.  j  av  a  2  s.  c om
        return contentEquals(closer.register(source.openStream()), in);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

@ThreadLocalArray(8192)
static boolean contentEqualsImpl(@NonNull ByteSource source, byte[] bytes, int off, int len)
        throws IOException {
    checkPositionIndexes(off, off + len, bytes.length);
    final Closer closer = Closer.create();
    try {/*  w w w  .j ava2s.  c  o m*/
        return contentEquals(closer.register(source.openStream()), bytes, off, len);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

/**
 * Copies at most {@code limit} bytes from {@code from} into {@code to},
 * returning the total number of bytes copied. This method <i>always</i>
 * copies {@code from} into {@code to} in chunks;
 * {@link ByteSource#copyTo(ByteSink)} or
 * {@link ByteSource#copyTo(OutputStream)} is never used.
 * //from www.  j  ava 2 s. co m
 * @param from the source to read bytes from
 * @param to the destination to copy bytes read from {@code from} into
 * @param limit the maximum number of bytes to copy
 * @return the total number of bytes copied from {@code from} to {@code to}
 * @throws IOException if an IOException occurs
 * @throws NullPointerException if either {@code from} or {@code to} is null
 * @throws IllegalArgumentException if {@code limit} is negative
 */
@ThreadLocalArray(8192)
public static long copy(@NonNull ByteSource from, @NonNull ByteSink to, long limit) throws IOException {
    checkLimit(limit);
    final Closer closer = Closer.create();
    try {
        OutputStream out = closer.register(to.openStream());
        long total = copy(closer.register(from.openStream()), out, limit);
        out.flush();
        return total;
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

/**
 * Copies at most {@code limit} bytes from {@code from} into {@code to},
 * returning the total number of bytes copied. {@code from} is not closed.
 * /*from w w  w.  j  a v a 2s .c  o  m*/
 * @param from the source to read bytes from
 * @param to the destination to copy bytes read from {@code from} into
 * @param limit the maximum number of bytes to copy
 * @return the total number of bytes copied from {@code from} to {@code to}
 * @throws IOException if an IOException occurs
 * @throws NullPointerException if either {@code from} or {@code to} is null
 * @throws IllegalArgumentException if {@code limit} is negative
 */
@ThreadLocalArray(8192)
public static long copy(@NonNull @WillNotClose InputStream from, @NonNull ByteSink to, long limit)
        throws IOException {
    checkLimit(limit);
    final Closer closer = Closer.create();
    try {
        OutputStream out = closer.register(to.openStream());
        long total = copy(from, out, limit);
        out.flush();
        return total;
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.facebook.buck.android.exopackage.RealExopackageDevice.java

@Override
public void installFile(final Path targetDevicePath, final Path source) throws Exception {
    Preconditions.checkArgument(source.isAbsolute());
    Preconditions.checkArgument(targetDevicePath.isAbsolute());
    Closer closer = Closer.create();
    CollectingOutputReceiver receiver = new CollectingOutputReceiver() {

        private boolean startedPayload = false;
        private boolean wrotePayload = false;
        @Nullable//from  ww  w.j  a va 2 s  . c  om
        private OutputStream outToDevice;

        @Override
        public void addOutput(byte[] data, int offset, int length) {
            super.addOutput(data, offset, length);
            try {
                if (!startedPayload && getOutput().length() >= AgentUtil.TEXT_SECRET_KEY_SIZE) {
                    LOG.verbose("Got key: %s", getOutput().split("[\\r\\n]", 1)[0]);
                    startedPayload = true;
                    Socket clientSocket = new Socket("localhost", agentPort);
                    closer.register(clientSocket);
                    LOG.verbose("Connected");
                    outToDevice = clientSocket.getOutputStream();
                    closer.register(outToDevice);
                    // Need to wait for client to acknowledge that we've connected.
                }
                if (outToDevice == null) {
                    throw new NullPointerException();
                }
                if (!wrotePayload && getOutput().contains("z1")) {
                    if (outToDevice == null) {
                        throw new NullPointerException("outToDevice was null when protocol says it cannot be");
                    }
                    LOG.verbose("Got z1");
                    wrotePayload = true;
                    outToDevice.write(getOutput().substring(0, AgentUtil.TEXT_SECRET_KEY_SIZE).getBytes());
                    LOG.verbose("Wrote key");
                    com.google.common.io.Files.asByteSource(source.toFile()).copyTo(outToDevice);
                    outToDevice.flush();
                    LOG.verbose("Wrote file");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };

    String targetFileName = targetDevicePath.toString();
    String command = "umask 022 && " + agent.get().getAgentCommand() + "receive-file " + agentPort + " "
            + Files.size(source) + " " + targetFileName + " ; echo -n :$?";
    LOG.debug("Executing %s", command);

    // If we fail to execute the command, stash the exception.  My experience during development
    // has been that the exception from checkReceiverOutput is more actionable.
    Exception shellException = null;
    try {
        device.executeShellCommand(command, receiver);
    } catch (Exception e) {
        shellException = e;
    }

    // Close the client socket, if we opened it.
    closer.close();

    try {
        AdbHelper.checkReceiverOutput(command, receiver);
    } catch (Exception e) {
        if (shellException != null) {
            e.addSuppressed(shellException);
        }
        throw e;
    }

    if (shellException != null) {
        throw shellException;
    }

    // The standard Java libraries on Android always create new files un-readable by other users.
    // We use the shell user or root to create these files, so we need to explicitly set the mode
    // to allow the app to read them.  Ideally, the agent would do this automatically, but
    // there's no easy way to do this in Java.  We can drop this if we drop support for the
    // Java agent.
    AdbHelper.executeCommandWithErrorChecking(device, "chmod 644 " + targetFileName);
}

From source file:com.tinspx.util.io.ChannelSource.java

@Override
public long copyTo(ByteSink sink) throws IOException {
    Closer closer = Closer.create();
    try {/*from  w ww . j  a v a  2 s . co m*/
        if (preferChannel() && sink instanceof ChannelSink && ((ChannelSink) sink).preferChannel()) {
            return copyTo(closer.register(((ChannelSink) sink).openChannel()));
        } else {
            OutputStream out = closer.register(sink.openStream());
            long total = copyTo(out);
            out.flush();
            return total;
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.tinspx.util.io.ByteUtils.java

/**
 * Wraps {@code resource} in a Closeable that will flush and close
 * {@code resource} when it is closed. This ensures that {@code resource} is
 * always flushed when closed.//w w  w  .  j a v  a 2  s. c  o  m
 *
 * @param resource the Closeable & Flushable resource to wrap
 * @return a Closeable that will close and flush {@code resource} when
 * closed
 */
public static <T extends Closeable & Flushable> Closeable flushOnClose(final @Nullable T resource) {
    return new Closeable() {
        private boolean closed;

        @Override
        @SuppressWarnings({ "BroadCatchBlock", "TooBroadCatch", "unchecked" })
        public void close() throws IOException {
            if (!closed && resource != null
                    && (!(resource instanceof Channel) || ((Channel) resource).isOpen())) {
                closed = true;
                final Closer closer = Closer.create();
                try {
                    closer.register(resource);
                    resource.flush();
                } catch (Throwable e) {
                    throw closer.rethrow(e);
                } finally {
                    closer.close();
                }
            }
        }
    };
}