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

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

Introduction

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

Prototype

public static Closer create() 

Source Link

Document

Creates a new Closer .

Usage

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 ww.jav  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
 * @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:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

@Override
public Iterable<Image> listImages() {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);//from   w ww  . ja  v  a  2  s.c om
    try {
        try {
            Iterable<VirtualMachine> nodes = listNodes(instance);
            Iterable<VirtualMachine> templates = Iterables.filter(nodes, VSpherePredicate.isTemplatePredicate);
            Iterable<Image> images = Iterables.transform(templates, virtualMachineToImage);
            return FluentIterable.from(images).toList();

        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } catch (Throwable t) {
        return ImmutableSet.of();
    }
}

From source file:com.datastax.driver.core.CCMTestsSupport.java

/**
 * Hook executed before each test method.
 * <p/>//from www  . j  av a 2 s. com
 * Useful when this class is not a superclass of the test being run.
 *
 * @throws Exception
 */
public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception {
    if (isCcmEnabled(testMethod)) {
        if (closer == null)
            closer = Closer.create();
        if (testMode == PER_METHOD || erroredOut) {
            try {
                initTestContext(testInstance, testMethod);
                initTestCluster(testInstance);
                initTestSession();
                initTestKeyspace();
                initTest(testInstance);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                errorOut();
                fail(e.getMessage());
            }
        }
        assert ccmTestConfig != null;
        assert !ccmTestConfig.createCcm() || ccm != null;
    }
}

From source file:io.prestosql.operator.HashBuilderOperator.java

@Override
public void close() {
    if (state == State.CLOSED) {
        return;//from   www.java2s . c  o  m
    }
    // close() can be called in any state, due for example to query failure, and must clean resource up unconditionally

    lookupSourceSupplier = null;
    state = State.CLOSED;
    finishMemoryRevoke = finishMemoryRevoke.map(ifPresent -> () -> {
    });

    try (Closer closer = Closer.create()) {
        closer.register(index::clear);
        spiller.ifPresent(closer::register);
        closer.register(() -> localUserMemoryContext.setBytes(0));
        closer.register(() -> localRevocableMemoryContext.setBytes(0));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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.
 * /* w w  w  .j a  v a2s.  com*/
 * @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 ReadableByteChannel from, @NonNull ByteSink to, long limit)
        throws IOException {
    checkLimit(limit);
    final Closer closer = Closer.create();
    try {
        if (to instanceof ChannelSink) {
            return copy(from, closer.register(((ChannelSink) to).openChannel()), limit);
        } else {
            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:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

@Override
public VirtualMachine getNode(String vmName) {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);/*  w ww.j  av a  2  s .  c  o  m*/
    try {
        try {
            return getVM(vmName, instance.getInstance().getRootFolder());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        Throwables.propagateIfPossible(e);
    }
    return null;
}

From source file:gobblin.runtime.Task.java

private void publishTaskData() throws IOException {
    Closer closer = Closer.create();
    try {/*w  w  w.  j  a v  a  2s. co m*/
        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:alluxio.cli.fs.command.CpCommand.java

/**
 * Copies a file specified by argv from the filesystem to the local filesystem. This is the
 * utility function./*from  w ww  . j av  a2 s. c  om*/
 *
 * @param srcPath The source {@link AlluxioURI} (has to be a file)
 * @param dstPath The {@link AlluxioURI} of the destination in the local filesystem
 */
private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException {
    File dstFile = new File(dstPath.getPath());
    String randomSuffix = String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8));
    File outputFile;
    if (dstFile.isDirectory()) {
        outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName()));
    } else {
        outputFile = dstFile;
    }
    File tmpDst = new File(outputFile.getPath() + randomSuffix);

    try (Closer closer = Closer.create()) {
        OpenFileOptions options = OpenFileOptions.defaults();
        FileInStream is = closer.register(mFileSystem.openFile(srcPath, options));
        FileOutputStream out = closer.register(new FileOutputStream(tmpDst));
        byte[] buf = new byte[64 * Constants.MB];
        int t = is.read(buf);
        while (t != -1) {
            out.write(buf, 0, t);
            t = is.read(buf);
        }
        if (!tmpDst.renameTo(outputFile)) {
            throw new IOException(
                    "Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath());
        }
        System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath());
    } finally {
        tmpDst.delete();
    }
}

From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

@Override
public void destroyNode(String vmName) {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);//  w ww.ja va2 s  .  c  om
    try {
        try {
            VirtualMachine virtualMachine = getVM(vmName, instance.getInstance().getRootFolder());
            Task powerOffTask = virtualMachine.powerOffVM_Task();
            if (powerOffTask.waitForTask().equals(Task.SUCCESS))
                logger.debug(String.format("VM %s powered off", vmName));
            else
                logger.debug(String.format("VM %s could not be powered off", vmName));

            Task destroyTask = virtualMachine.destroy_Task();
            if (destroyTask.waitForTask().equals(Task.SUCCESS))
                logger.debug(String.format("VM %s destroyed", vmName));
            else
                logger.debug(String.format("VM %s could not be destroyed", vmName));
        } catch (Exception e) {
            logger.error("Can't destroy vm " + vmName, e);
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        logger.trace(e.getMessage(), e);
    }

}

From source file:alluxio.shell.command.CpCommand.java

/**
 * Copies a file specified by argv from the filesystem to the local filesystem. This is the
 * utility function./*from  w ww  . j av a 2  s .  c  o  m*/
 *
 * @param srcPath The source {@link AlluxioURI} (has to be a file)
 * @param dstPath The {@link AlluxioURI} of the destination in the local filesystem
 * @throws AlluxioException when Alluxio exception occurs
 * @throws IOException when non-Alluxio exception occurs
 */
private void copyFileToLocal(AlluxioURI srcPath, AlluxioURI dstPath) throws AlluxioException, IOException {
    File dstFile = new File(dstPath.getPath());
    String randomSuffix = String.format(".%s_copyToLocal_", RandomStringUtils.randomAlphanumeric(8));
    File outputFile;
    if (dstFile.isDirectory()) {
        outputFile = new File(PathUtils.concatPath(dstFile.getAbsolutePath(), srcPath.getName()));
    } else {
        outputFile = dstFile;
    }
    File tmpDst = new File(outputFile.getPath() + randomSuffix);

    try (Closer closer = Closer.create()) {
        OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
        FileInStream is = closer.register(mFileSystem.openFile(srcPath, options));
        FileOutputStream out = closer.register(new FileOutputStream(tmpDst));
        byte[] buf = new byte[64 * Constants.MB];
        int t = is.read(buf);
        while (t != -1) {
            out.write(buf, 0, t);
            t = is.read(buf);
        }
        if (!tmpDst.renameTo(outputFile)) {
            throw new IOException(
                    "Failed to rename " + tmpDst.getPath() + " to destination " + outputFile.getPath());
        }
        System.out.println("Copied " + srcPath + " to " + "file://" + outputFile.getPath());
    } finally {
        tmpDst.delete();
    }
}