List of usage examples for com.google.common.io Closer register
public <C extends Closeable> C register(@Nullable C closeable)
From source file:gobblin.runtime.Task.java
private void publishTaskData() throws IOException { Closer closer = Closer.create(); try {/*from www. j a va2 s. c om*/ Class<? extends DataPublisher> dataPublisherClass = getTaskPublisherClass(); SingleTaskDataPublisher publisher = closer .register(SingleTaskDataPublisher.getInstance(dataPublisherClass, this.taskState)); LOG.info("Publishing data from task " + this.taskId); publisher.publish(this.taskState); } catch (ClassCastException e) { LOG.error(String.format("To publish data in task, the publisher class must extend %s", SingleTaskDataPublisher.class.getSimpleName()), e); this.taskState.setTaskFailureException(e); throw closer.rethrow(e); } catch (Throwable t) { this.taskState.setTaskFailureException(t); throw closer.rethrow(t); } finally { closer.close(); } }
From source file:org.apache.jackrabbit.oak.run.CheckpointsCommand.java
@Override public void execute(String... args) throws Exception { OptionParser parser = new OptionParser(); OptionSpec segmentTar = parser.accepts("segment-tar", "Use oak-segment-tar instead of oak-segment"); OptionSet options = parser.parse(args); if (options.nonOptionArguments().isEmpty()) { System.out.println(//www . ja v a2 s . co m "usage: checkpoints {<path>|<mongo-uri>} [list|rm-all|rm-unreferenced|rm <checkpoint>] [--segment-tar]"); System.exit(1); } boolean success = false; Checkpoints cps; Closer closer = Closer.create(); try { String op = "list"; if (options.nonOptionArguments().size() >= 2) { op = options.nonOptionArguments().get(1).toString(); if (!"list".equals(op) && !"rm-all".equals(op) && !"rm-unreferenced".equals(op) && !"rm".equals(op)) { failWith("Unknown command."); } } String connection = options.nonOptionArguments().get(0).toString(); if (connection.startsWith(MongoURI.MONGODB_PREFIX)) { MongoClientURI uri = new MongoClientURI(connection); MongoClient client = new MongoClient(uri); final DocumentNodeStore store = new DocumentMK.Builder().setMongoDB(client.getDB(uri.getDatabase())) .getNodeStore(); closer.register(Utils.asCloseable(store)); cps = Checkpoints.onDocumentMK(store); } else if (options.has(segmentTar)) { cps = Checkpoints.onSegmentTar(new File(connection), closer); } else { cps = Checkpoints.onSegment(new File(connection), closer); } System.out.println("Checkpoints " + connection); if ("list".equals(op)) { int cnt = 0; for (Checkpoints.CP cp : cps.list()) { System.out.printf("- %s created %s expires %s%n", cp.id, new Timestamp(cp.created), new Timestamp(cp.expires)); cnt++; } System.out.println("Found " + cnt + " checkpoints"); } else if ("rm-all".equals(op)) { long time = System.currentTimeMillis(); long cnt = cps.removeAll(); time = System.currentTimeMillis() - time; if (cnt != -1) { System.out.println("Removed " + cnt + " checkpoints in " + time + "ms."); } else { failWith("Failed to remove all checkpoints."); } } else if ("rm-unreferenced".equals(op)) { long time = System.currentTimeMillis(); long cnt = cps.removeUnreferenced(); time = System.currentTimeMillis() - time; if (cnt != -1) { System.out.println("Removed " + cnt + " checkpoints in " + time + "ms."); } else { failWith("Failed to remove unreferenced checkpoints."); } } else if ("rm".equals(op)) { if (options.nonOptionArguments().size() < 3) { failWith("Missing checkpoint id"); } else { String cp = options.nonOptionArguments().get(2).toString(); long time = System.currentTimeMillis(); int cnt = cps.remove(cp); time = System.currentTimeMillis() - time; if (cnt != 0) { if (cnt == 1) { System.out.println("Removed checkpoint " + cp + " in " + time + "ms."); } else { failWith("Failed to remove checkpoint " + cp); } } else { failWith("Checkpoint '" + cp + "' not found."); } } } success = true; } catch (Throwable t) { System.err.println(t.getMessage()); } finally { closer.close(); } if (!success) { System.exit(1); } }
From source file:com.facebook.buck.android.RealExopackageDevice.java
@Override public void installFile(final String agentCommand, final int port, 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 w w w. j ava 2s. c o m*/ 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", port); 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 && " + agentCommand + "receive-file " + port + " " + 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.ByteUtils.java
/** * Copies as many bytes as possible from {@code from} into {@code to}, * returning the total number of bytes copied. * /*from www .j a v a 2 s . c o m*/ * @param from the source to read bytes from * @param to the destination to copy bytes read from {@code from} into * @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 */ @ThreadLocalArray(8192) public static int copy(@NonNull ByteSource from, @NonNull ByteBuffer to) throws IOException { final Closer closer = Closer.create(); try { return copy(closer.register(from.openStream()), to); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
From source file:com.tinspx.util.io.ByteUtils.java
@ThreadLocalArray(8192) public static byte[] toByteArray(@NonNull File file) throws IOException { final int size = Ints.checkedCast(file.length()); Closer closer = Closer.create(); try {//from w ww . ja v a2 s .c om return toByteArray(closer.register(new FileInputStream(file)), size); } catch (Throwable t) { throw closer.rethrow(t); } 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 to} is not closed or * flushed./* w w w . j a v a2 s.c om*/ * * @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 @WillNotClose OutputStream to, long limit) throws IOException { final Closer closer = Closer.create(); try { return copy(closer.register(from.openStream()), to, limit); } 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 to} is not closed or * flushed./* w w w .j a va2 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 PrimitiveSink to, long limit) throws IOException { checkLimit(limit); final Closer closer = Closer.create(); try { return copy(closer.register(from.openStream()), to, limit); } 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. Byte processing stops on EOF * or when {@link ByteProcessor#processBytes(byte[], int, int) processBytes} * returns {@code false}./*from ww w. ja v a 2s . 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 ByteProcessor<?> to, long limit) throws IOException { checkLimit(limit); final Closer closer = Closer.create(); try { return copy(closer.register(from.openStream()), to, limit); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
From source file:com.tinspx.util.io.ByteUtils.java
/** * Used instead of {@link #toByteArray(ByteSource)} when the size of the * {@code ByteSource} is known and {@link ByteSource#size() size()} should * not be called on {@code source}.//w w w. j a va 2s. c o m */ @ThreadLocalArray(8192) public static byte[] toByteArray(ByteSource source, int expectedSize) throws IOException { final Closer closer = Closer.create(); try { return toByteArray(closer.register(source.openStream()), expectedSize); } 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 source1, @NonNull ByteSource source2) throws IOException { final Closer closer = Closer.create(); try {//from w ww .j a v a 2 s. co m return contentEquals(closer.register(source1.openStream()), closer.register(source2.openStream())); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }