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:tachyon.util.CommonUtils.java

/**
 * Blocking operation that copies the processes stdout/stderr to this JVM's stdout/stderr.
 *///w ww.  j  a v  a2 s.co  m
private static void redirectIO(final Process process) throws IOException {
    // Because chmod doesn't have a lot of error or output messages, its safe to process the output
    // after the process is done. As of java 7, you can have the process redirect to System.out
    // and System.err without forking a process.
    // TODO when java 6 support is dropped, switch to
    // http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#inheritIO()
    Closer closer = Closer.create();
    try {
        ByteStreams.copy(closer.register(process.getInputStream()), System.out);
        ByteStreams.copy(closer.register(process.getErrorStream()), System.err);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:se.sics.kompics.network.netty.serialization.JavaSerializer.java

@Override
public Object fromBinary(ByteBuf buf, Optional<Class> hint) {
    // Ignore hint
    try {//from   ww  w .ja v a 2  s  . c  o m
        Closer closer = Closer.create();
        try {
            ByteBufInputStream bbis = closer.register(new ByteBufInputStream(buf));
            CompactObjectInputStream cois = closer.register(new CompactObjectInputStream(bbis, resolver));
            return cois.readObject();
        } catch (Throwable e) {
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException ex) {
        Serializers.LOG.error("JavaSerializer: Could not deserialize object", ex);
        return null;
    }
}

From source file:utils.PasswordManager.java

public static Optional<String> getMasterPassword(String masterPwdLoc) {
    Closer closer = Closer.create();
    try {/*www  .j a  v  a2s .  c  o  m*/
        File file = new File(masterPwdLoc);
        if (!file.exists() || file.isDirectory()) {
            LOG.warn(masterPwdLoc + " does not exist or is not a file. Cannot decrypt any encrypted password.");
            return Optional.absent();
        }
        InputStream in = new FileInputStream(file);
        return Optional.of(new LineReader(new InputStreamReader(in, Charsets.UTF_8)).readLine());
    } catch (IOException e) {
        throw new RuntimeException("Failed to obtain master password from " + masterPwdLoc, e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            throw new RuntimeException("Failed to close inputstream for " + masterPwdLoc, e);
        }
    }
}

From source file:tachyon.shell.command.LoadCommand.java

/**
 * Loads a file or directory in Tachyon space, makes it resident in memory.
 *
 * @param filePath The {@link TachyonURI} path to load into Tachyon memory
 * @throws IOException if a non-Tachyon related exception occurs
 *///from   w  w w.j  a  va2  s . c  om
private void load(TachyonURI filePath) throws IOException {
    try {
        URIStatus status = mTfs.getStatus(filePath);
        if (status.isFolder()) {
            List<URIStatus> statuses = mTfs.listStatus(filePath);
            for (URIStatus uriStatus : statuses) {
                TachyonURI newPath = new TachyonURI(uriStatus.getPath());
                load(newPath);
            }
        } else {
            if (status.getInMemoryPercentage() == 100) {
                // The file has already been fully loaded into Tachyon memory.
                return;
            }
            Closer closer = Closer.create();
            try {
                OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.CACHE_PROMOTE);
                FileInStream in = closer.register(mTfs.openFile(filePath, options));
                byte[] buf = new byte[8 * Constants.MB];
                while (in.read(buf) != -1) {
                }
            } catch (Exception e) {
                throw closer.rethrow(e);
            } finally {
                closer.close();
            }
        }
        System.out.println(filePath + " loaded");
    } catch (TachyonException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.eclipse.m2e.core.internal.index.nexus.AetherClientResourceFetcher.java

public void retrieve(String name, File targetFile) throws IOException, FileNotFoundException {

    String url = baseUrl + "/" + name;
    Response response = aetherClient.get(url);

    Closer closer = Closer.create();
    try {/*from w w  w.ja va 2s  .  c o  m*/
        InputStream is = closer.register(response.getInputStream());
        OutputStream os = closer.register(new BufferedOutputStream(new FileOutputStream(targetFile)));
        final byte[] buffer = new byte[1024 * 1024];
        int n = 0;
        while (-1 != (n = is.read(buffer))) {
            os.write(buffer, 0, n);
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
        }
    } finally {
        closer.close();
    }
}

From source file:org.grouplens.lenskit.cli.PackRatings.java

@Override
public void execute() throws IOException {
    logger.info("packing ratings from {}", input);
    logger.debug("using delimiter {}", getDelimiter());
    EventDAO dao = input.getEventDAO();/*  w w  w . j ava2 s.  c o m*/
    EnumSet<BinaryFormatFlag> flags = EnumSet.noneOf(BinaryFormatFlag.class);
    if (useTimestamps()) {
        flags.add(BinaryFormatFlag.TIMESTAMPS);
    }
    logger.info("packing to {} with flags {}", getOutputFile(), flags);
    Closer closer = Closer.create();
    try {
        BinaryRatingPacker packer = closer.register(BinaryRatingPacker.open(getOutputFile(), flags));
        Cursor<Rating> ratings = closer.register(dao.streamEvents(Rating.class));
        packer.writeRatings(ratings);
        logger.info("packed {} ratings", packer.getRatingCount());
    } catch (Throwable th) {
        throw closer.rethrow(th);
    } finally {
        closer.close();
    }
}

From source file:org.impressivecode.depress.mr.astcompare.utils.Utils.java

private static void saveFile(InputStream is, OutputStream os) throws IOException {
    Closer closer = Closer.create();
    try {/* w  ww.  j  a v  a 2s.co m*/
        InputStream in = closer.register(is);
        OutputStream out = closer.register(os);
        ByteStreams.copy(in, out);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.facebook.buck.step.fs.ZipDirectoryWithMaxDeflateStep.java

@Override
public int execute(ExecutionContext context) {
    File inputDirectory = new File(inputDirectoryPath);
    Preconditions.checkState(inputDirectory.exists() && inputDirectory.isDirectory());

    Closer closer = Closer.create();
    try {/*from w ww . j  a v a  2  s .c o  m*/
        ImmutableMap.Builder<File, ZipEntry> zipEntriesBuilder = ImmutableMap.builder();
        addDirectoryToZipEntryList(inputDirectory, "", zipEntriesBuilder);
        ImmutableMap<File, ZipEntry> zipEntries = zipEntriesBuilder.build();

        if (!zipEntries.isEmpty()) {
            ZipOutputStream outputStream = closer.register(
                    new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputZipPath))));

            for (Map.Entry<File, ZipEntry> zipEntry : zipEntries.entrySet()) {
                outputStream.putNextEntry(zipEntry.getValue());
                ByteStreams.copy(Files.newInputStreamSupplier(zipEntry.getKey()), outputStream);
                outputStream.closeEntry();
            }
        }
    } catch (IOException e) {
        e.printStackTrace(context.getStdErr());
        return 1;
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
    return 0;
}

From source file:com.hujiang.gradle.plugin.android.aspectjx.JarMerger.java

private void addFolder(@NonNull File folder, @NonNull String path)
        throws IOException, IZipEntryFilter.ZipAbortException {

    File[] files = folder.listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.isFile()) {
                String entryPath = path + file.getName();
                if (filter == null || filter.checkEntry(entryPath)) {
                    // new entry
                    jarOutputStream.putNextEntry(new JarEntry(entryPath));

                    // put the file content
                    Closer localCloser = Closer.create();
                    try {
                        FileInputStream fis = localCloser.register(new FileInputStream(file));
                        int count;
                        while ((count = fis.read(buffer)) != -1) {
                            jarOutputStream.write(buffer, 0, count);
                        }/*from ww w . j a  v  a  2  s . com*/
                    } finally {
                        localCloser.close();
                    }

                    // close the entry
                    jarOutputStream.closeEntry();
                }
            } else if (file.isDirectory()) {
                addFolder(file, path + file.getName() + "/");
            }
        }
    }
}

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
 *///from ww w  .ja v 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();
            }
        }
    }
}