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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes all Closeable instances that have been added to this Closer .

Usage

From source file:com.googlecode.jmxtrans.model.output.support.pool.DatagramChannelAllocator.java

@Override
public void deallocate(DatagramChannelPoolable poolable) throws Exception {
    Closer closer = Closer.create();
    try {/*from   w w  w .j a v a  2s  . c om*/
        Writer writer = closer.register(poolable.getWriter());
        writer.flush();
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:net.derquinse.common.util.zip.ZipFileLoader.java

/**
 * Loads a zip file into memory.//from   www. j  a  v a  2  s  .  c  om
 * @param input Input data.
 * @return The loaded zip file.
 * @throws IOException if an I/O error occurs
 * @throws MaximumSizeExceededException if any of the entries exceeds the maximum size.
 */
public LoadedZipFile load(ByteSource input) throws IOException {
    checkInput(input);
    Closer closer = Closer.create();
    try {
        return load(closer.register(input.openStream()));
    } finally {
        closer.close();
    }
}

From source file:com.googlecode.jmxtrans.model.output.support.pool.SocketAllocator.java

@Override
public void deallocate(SocketPoolable poolable) throws Exception {
    Closer closer = Closer.create();
    try {//from   w ww . j a v  a  2s.  c om
        closer.register(poolable.getSocket());
        closer.register(poolable.getWriter());
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:ch.ledcom.demo.redirect.ImageServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Closer closer = Closer.create();
    try {//from  www  . j av  a 2s  . c  o m
        InputStream imageStream = closer.register(loadImage());
        ByteStreams.copy(imageStream, resp.getOutputStream());
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:org.apache.gobblin.util.limiter.MultiLimiter.java

@Override
public Closeable acquirePermits(long permits) throws InterruptedException {
    Closer closer = Closer.create();
    for (Limiter limiter : this.underlyingLimiters) {
        Closeable permit = limiter.acquirePermits(permits);
        if (permit == null) {
            try {
                closer.close();
            } catch (IOException ioe) {
                throw new RuntimeException("Could not return intermediate permits.");
            }/* w w w  .  ja v  a2s.c om*/
            return null;
        }
        closer.register(permit);
    }
    return closer;
}

From source file:alluxio.network.thrift.SocketTrackingTServerSocket.java

/**
 * Closes all socket connections that have been accepted by this server socket.
 *//*from   w  w w .  j  av  a 2s. co  m*/
private void closeClientSockets() throws IOException {
    // Possible since super constructor can call close().
    if (mSockets == null) {
        return;
    }
    Closer closer = Closer.create();
    int count = 0;
    for (Socket s : mSockets) {
        if (!s.isClosed()) {
            closer.register(s);
            count++;
        }
    }
    closer.close();
    LOG.info("Closed {} client sockets", count);
}

From source file:gobblin.util.HeapDumpForTaskUtils.java

/**
 * Generate the dumpScript, which is used when OOM error is thrown during task execution.
 * The current content dumpScript puts the .prof files to the DUMP_FOLDER within the same directory of the dumpScript.
 *
 * User needs to add the following options to the task java.opts:
 *
 * -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heapFileName.hprof -XX:OnOutOfMemoryError=./dumpScriptFileName
 *
 * @param dumpScript The path to the dumpScript, which needs to be added to the Distributed cache.
 * To use it, simply put the path of dumpScript to the gobblin config: job.hdfs.files.
 * @param fs File system//ww w.jav a2  s  .  co  m
 * @param heapFileName the name of the .prof file.
 * @param chmod chmod for the dump script. For hdfs file, e.g, "hadoop fs -chmod 755"
 * @throws IOException
 */
public static void generateDumpScript(Path dumpScript, FileSystem fs, String heapFileName, String chmod)
        throws IOException {
    if (fs.exists(dumpScript)) {
        LOG.info("Heap dump script already exists: " + dumpScript);
        return;
    }

    Closer closer = Closer.create();
    try {
        Path dumpDir = new Path(dumpScript.getParent(), DUMP_FOLDER);
        if (!fs.exists(dumpDir)) {
            fs.mkdirs(dumpDir);
        }
        BufferedWriter scriptWriter = closer.register(new BufferedWriter(
                new OutputStreamWriter(fs.create(dumpScript), ConfigurationKeys.DEFAULT_CHARSET_ENCODING)));

        scriptWriter.write("#!/bin/sh\n");
        scriptWriter.write("if [ -n \"$HADOOP_PREFIX\" ]; then\n");
        scriptWriter.write("  ${HADOOP_PREFIX}/bin/hadoop dfs -put " + heapFileName + " " + dumpDir
                + "/${PWD//\\//_}.hprof\n");
        scriptWriter.write("else\n");
        scriptWriter.write("  ${HADOOP_HOME}/bin/hadoop dfs -put " + heapFileName + " " + dumpDir
                + "/${PWD//\\//_}.hprof\n");
        scriptWriter.write("fi\n");

    } catch (IOException ioe) {
        LOG.error("Heap dump script is not generated successfully.");
        if (fs.exists(dumpScript)) {
            fs.delete(dumpScript, true);
        }
        throw ioe;
    } catch (Throwable t) {
        closer.rethrow(t);
    } finally {
        closer.close();
    }
    Runtime.getRuntime().exec(chmod + " " + dumpScript);
}

From source file:org.glowroot.agent.live.ClasspathCache.java

private static byte[] getBytesFromJarFileInsideJarFile(String name, File jarFile, String jarFileInsideJarFile)
        throws IOException {
    String path = jarFile.getPath();
    URI uri;/*  w  w w . j  a v  a 2 s.c  o  m*/
    try {
        uri = new URI("jar", "file:" + path + "!/" + jarFileInsideJarFile, "");
    } catch (URISyntaxException e) {
        // this is a programmatic error
        throw new RuntimeException(e);
    }
    Closer closer = Closer.create();
    try {
        InputStream in = closer.register(uri.toURL().openStream());
        JarInputStream jarIn = closer.register(new JarInputStream(in));
        JarEntry jarEntry;
        while ((jarEntry = jarIn.getNextJarEntry()) != null) {
            if (jarEntry.isDirectory()) {
                continue;
            }
            if (jarEntry.getName().equals(name)) {
                return ByteStreams.toByteArray(jarIn);
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
    throw new UnsupportedOperationException();
}

From source file:org.ow2.proactive.scheduler.rest.readers.TaskResultReader.java

@Override
public Serializable readFrom(Class<Serializable> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    Closer closer = Closer.create();
    try {//from   w ww .j a va  2s  .  com
        entityStream = closer.register(entityStream);
        return CharStreams.toString(new InputStreamReader(entityStream));
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}

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  w  w .ja  v a  2 s.  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);
            }
        }
    });
}