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:net.stevechaloner.intellijad.decompilers.JarExtractor.java

/**
 * Extract the given file to the target directory specified in the context.
 *
 * @param context     the context of the decompilation operation
 * @param jarFile     the name of the zip file to open
 * @param packageName the package of the class
 * @param className   the name of the class
 * @throws IOException if an error occurs during the operation
 *//*w  ww  .  jav a 2 s  .  co m*/
void extract(DecompilationContext context, JarFile jarFile, String packageName, String className)
        throws IOException {
    Pattern p = Pattern.compile(preparePackage(packageName) + className + CLASS_PATTERN + ".class");

    Enumeration<? extends JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        Matcher matcher = p.matcher(name);
        if (matcher.matches()) {
            context.getConsoleContext().addMessage(ConsoleEntryType.JAR_OPERATION, "message.extracting",
                    entry.getName());
            Closer closer = Closer.create();
            try {
                InputStream inputStream = closer.register(jarFile.getInputStream(entry));

                File outputFile = new File(context.getTargetDirectory(), justFileName(entry.getName()));
                context.getConsoleContext().addMessage(ConsoleEntryType.JAR_OPERATION,
                        "message.extracting-done", entry.getName(), outputFile.getAbsolutePath());
                outputFile.deleteOnExit();
                FileOutputStream fos = closer.register(new FileOutputStream(outputFile));
                StreamUtil.copyStreamContent(inputStream, fos);
            } finally {
                closer.close();
            }
        }
    }
}

From source file:gobblin.runtime.util.ClustersNames.java

private ClustersNames() {
    Closer closer = Closer.create();
    try {/*from  w  w w . j av a  2  s  .c om*/
        InputStream propsInput = closer.register(getClass().getResourceAsStream(URL_TO_NAME_MAP_RESOURCE_NAME));
        if (null == propsInput) {
            propsInput = closer.register(ClassLoader.getSystemResourceAsStream(URL_TO_NAME_MAP_RESOURCE_NAME));
        }
        if (null != propsInput) {
            try {
                _urlToNameMap.load(propsInput);
                LOG.info("Loaded cluster names map:" + _urlToNameMap);
            } catch (IOException e) {
                LOG.warn("Unable to load cluster names map: " + e, e);
            }
        } else {
            LOG.info("no default cluster mapping found");
        }
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            LOG.warn("unable to close resource input stream for " + URL_TO_NAME_MAP_RESOURCE_NAME + ":" + e, e);
        }
    }
}

From source file:org.gradle.caching.internal.LocalDirectoryBuildCache.java

@Override
public void store(final BuildCacheKey key, final BuildCacheEntryWriter result) throws BuildCacheException {
    persistentCache.useCache("store build cache entry", new Runnable() {
        @Override//from  w  ww  . j ava 2s.c om
        public void run() {
            File file = getFile(key.getHashCode());
            try {
                Closer closer = Closer.create();
                OutputStream output = closer.register(new FileOutputStream(file));
                try {
                    result.writeTo(output);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }
    });
}

From source file:org.gradle.caching.internal.LocalDirectoryBuildCacheService.java

@Override
public void store(final BuildCacheKey key, final BuildCacheEntryWriter result) throws BuildCacheException {
    persistentCache.useCache(new Runnable() {
        @Override//from w  w w .  j a  v a  2  s  .  co m
        public void run() {
            File file = getFile(key.getHashCode());
            try {
                Closer closer = Closer.create();
                OutputStream output = closer.register(new FileOutputStream(file));
                try {
                    result.writeTo(output);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }
    });
}

From source file:org.gradle.api.internal.tasks.cache.LocalDirectoryTaskOutputCache.java

@Override
public void store(final TaskCacheKey key, final TaskOutputWriter result) throws IOException {
    persistentCache.useCache("store task output", new Runnable() {
        @Override/*  www. j a v a  2  s  . c o m*/
        public void run() {
            File file = getFile(key.getHashCode());
            try {
                Closer closer = Closer.create();
                OutputStream output = closer.register(new FileOutputStream(file));
                try {
                    result.writeTo(output);
                } catch (Throwable ex) {
                    throw closer.rethrow(ex);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }
    });
}

From source file:eu.interedition.text.index.IndexServiceBase.java

public boolean isEmpty() {
    final Closer closer = Closer.create();
    try {/*from   w ww  .  j  a  va 2s  . c  o  m*/
        return (closer.register(reader()).numDocs() == 0);
    } catch (IOException e) {
        if (LOG.isLoggable(Level.SEVERE)) {
            LOG.log(Level.SEVERE, "I/O while checking whether index is empty; assuming it is", e);
        }
        return true;
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

}

From source file:tachyon.job.CommandLineJob.java

@Override
public boolean run() {
    try {//from w  w w.j a  va  2  s . c o m
        String outputPath = getJobConf().getOutputFilePath();
        LOG.info("Exec {} output to {}", mCommand, outputPath);
        Process p = java.lang.Runtime.getRuntime().exec(mCommand);
        String line;
        Closer closer = Closer.create();
        try {
            BufferedReader bri = closer.register(new BufferedReader(new InputStreamReader(p.getInputStream())));
            BufferedReader bre = closer.register(new BufferedReader(new InputStreamReader(p.getErrorStream())));
            File file = new File(outputPath);
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = closer.register(new BufferedWriter(fw));
            while ((line = bri.readLine()) != null) {
                bw.write(line + "\n");
            }
            while ((line = bre.readLine()) != null) {
                bw.write(line + "\n");
            }
            bw.flush();
        } finally {
            closer.close();
        }

        p.waitFor();
        LOG.info("Exec {} output to {} done.", mCommand, outputPath);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        return false;
    } catch (InterruptedException e) {
        LOG.error(e.getMessage());
        return false;
    }

    return true;
}

From source file:alluxio.job.CommandLineJob.java

@Override
public boolean run() {
    try {//from  w  ww.j a  va2 s  .  c o m
        String outputPath = getJobConf().getOutputFilePath();
        LOG.info("Exec {} output to {}", mCommand, outputPath);
        Process p = java.lang.Runtime.getRuntime().exec(mCommand);
        String line;
        Closer closer = Closer.create();
        try {
            BufferedReader bri = closer.register(new BufferedReader(new InputStreamReader(p.getInputStream())));
            BufferedReader bre = closer.register(new BufferedReader(new InputStreamReader(p.getErrorStream())));
            File file = new File(outputPath);
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = closer.register(new BufferedWriter(fw));
            while ((line = bri.readLine()) != null) {
                bw.write(line + "\n");
            }
            while ((line = bre.readLine()) != null) {
                bw.write(line + "\n");
            }
            bw.flush();
        } finally {
            closer.close();
        }

        p.waitFor();
        LOG.info("Exec {} output to {} done.", mCommand, outputPath);
    } catch (IOException | InterruptedException e) {
        LOG.error(e.getMessage());
        return false;
    }

    return true;
}

From source file:org.jclouds.vsphere.suppliers.VSphereLocationSupplier.java

private Set<? extends Location> getClusters() {
    Set<Location> hosts = Sets.newHashSet();
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);
    try {/*from   ww  w  .  java 2s .co m*/
        try {

            ManagedEntity[] clusterEntities = new InventoryNavigator(instance.getInstance().getRootFolder())
                    .searchManagedEntities("ClusterComputeResource");

            for (ManagedEntity cluster : clusterEntities) {
                Location location = new LocationImpl(LocationScope.ZONE, cluster.getName(), cluster.getName(),
                        null, ImmutableSet.of(""), Maps.<String, Object>newHashMap());
                hosts.add(location);
            }

            hosts.add(new LocationImpl(LocationScope.ZONE, "default", "default", null, ImmutableSet.of(""),
                    Maps.<String, Object>newHashMap()));

            return hosts;
        } catch (Exception e) {
            logger.error("Problem in finding a valid cluster", e);
            closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    return hosts;
}

From source file:se.sics.caracaldb.store.SizeScan.java

@Override
public StorageResponse execute(Persistence store) throws IOException {
    long size = 0;
    long keys = 0;

    Closer closer = Closer.create();
    try {/*from ww  w .jav a  2 s. c o m*/
        byte[] begin = range.begin.getArray();
        for (StoreIterator it = closer.register(store.iterator(begin)); it.hasNext(); it.next()) {
            byte[] key = it.peekKey();
            if (range.contains(key)) {
                byte[] value = it.peekRaw();
                keys++;
                size += key.length;
                size += value.length;
            } else {
                //special case (a,b) and key is a
                if (Key.compare(begin, key) != 0) {
                    break; // reached end of range
                }
            }
        }

    } catch (Throwable e) {
        closer.rethrow(e);
    } finally {
        closer.close();
    }
    return new SizeResp(this, new Diff(size, keys, true));
}