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:alluxio.shell.command.LoadCommand.java

/**
 * Loads a file or directory in Alluxio space, makes it resident in memory.
 *
 * @param filePath The {@link AlluxioURI} path to load into Alluxio memory
 * @throws AlluxioException when Alluxio exception occurs
 * @throws IOException when non-Alluxio exception occurs
 */// www.  j a va  2 s.  c o m
private void load(AlluxioURI filePath) throws AlluxioException, IOException {
    URIStatus status = mFileSystem.getStatus(filePath);
    if (status.isFolder()) {
        List<URIStatus> statuses = mFileSystem.listStatus(filePath);
        for (URIStatus uriStatus : statuses) {
            AlluxioURI newPath = new AlluxioURI(uriStatus.getPath());
            load(newPath);
        }
    } else {
        if (status.getInMemoryPercentage() == 100) {
            // The file has already been fully loaded into Alluxio memory.
            return;
        }
        Closer closer = Closer.create();
        try {
            OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.CACHE_PROMOTE);
            FileInStream in = closer.register(mFileSystem.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");
}

From source file:tachyon.util.io.FileUtils.java

/**
 * Blocking operation that copies the processes stdout/stderr to this JVM's stdout/stderr.
 *
 * @param process process whose stdout/stderr to copy
 * @throws IOException when operation fails
 *//*from  w  ww  .j a v a2  s  . com*/
private static void redirectIO(final Process process) throws IOException {
    Preconditions.checkNotNull(process);
    /*
     * Because chmod doesn't have a lot of error or output messages, it is 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(cc): When java 6 support is dropped switch to 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 (Exception e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.adobe.epubcheck.opf.OPFPeeker.java

public OPFData peek() throws InvalidVersionException, IOException {
    Closer closer = Closer.create();
    try {/*from  w w  w . j av a2 s  . c  o m*/
        InputStream in = resourceProvider.getInputStream(path);
        if (in == null)
            throw new IOException("Couldn't find resource " + path);
        in = closer.register(resourceProvider.getInputStream(path));
        return peek(in);
    } catch (Throwable e) {
        throw closer.rethrow(e, InvalidVersionException.class);
    } finally {
        closer.close();
    }
}

From source file:com.fullcontact.sstable.hadoop.IndexOffsetScanner.java

/**
 * Java I/O based version./*from   ww  w.ja va 2  s.  c  om*/
 *
 * @param filename File name.
 */
public IndexOffsetScanner(final String filename) {
    closer = Closer.create();
    try {
        this.input = closer.register(
                new DataInputStream(new BufferedInputStream(new FileInputStream(filename), 65536 * 10)));
    } catch (IOException e) {
        throw new IOError(e);
    }
}

From source file:com.spotify.docker.client.DefaultLogStream.java

public void attach(final OutputStream stdout, final OutputStream stderr, boolean closeAtEof)
        throws IOException {
    final Closer closer = Closer.create();
    try {/*  ww w.  j a v a 2 s. c om*/
        if (closeAtEof) {
            closer.register(stdout);
            closer.register(stderr);
        }

        while (this.hasNext()) {
            final LogMessage message = this.next();
            final ByteBuffer content = message.content();

            switch (message.stream()) {
            case STDOUT:
                writeAndFlush(content, stdout);
                break;
            case STDERR:
                writeAndFlush(content, stderr);
                break;
            case STDIN:
            default:
                break;
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:net.derquinse.common.io.BytesTransformer.java

/** Transforms a stream of bytes. */
public void transform(InputStream input, ByteSink output) throws IOException {
    checkInput(input);/*from  ww  w . java 2 s  . c  om*/
    checkOutput(output);
    final Closer closer = Closer.create();
    try {
        transform(input, closer.register(output.openStream()));
    } finally {
        closer.close();
    }
}

From source file:com.googlecode.jmxtrans.model.output.LibratoWriter2.java

@Override
public void write(@Nonnull Writer writer, @Nonnull Server server, @Nonnull Query query,
        @Nonnull Iterable<Result> results) throws IOException {
    Closer closer = Closer.create();
    try {/* w w w. java 2 s. co m*/
        JsonGenerator g = closer.register(jsonFactory.createGenerator(writer));
        g.writeStartObject();
        g.writeArrayFieldStart("counters");
        g.writeEndArray();

        String source = getSource(server);

        g.writeArrayFieldStart("gauges");
        for (Result result : results) {
            Map<String, Object> resultValues = result.getValues();
            if (resultValues != null) {
                for (Map.Entry<String, Object> values : resultValues.entrySet()) {
                    if (isNumeric(values.getValue())) {
                        g.writeStartObject();
                        g.writeStringField("name", KeyUtils.getKeyString(query, result, values, typeNames));
                        if (source != null && !source.isEmpty()) {
                            g.writeStringField("source", source);
                        }
                        g.writeNumberField("measure_time", SECONDS.convert(result.getEpoch(), MILLISECONDS));
                        Object value = values.getValue();
                        if (value instanceof Integer) {
                            g.writeNumberField("value", (Integer) value);
                        } else if (value instanceof Long) {
                            g.writeNumberField("value", (Long) value);
                        } else if (value instanceof Float) {
                            g.writeNumberField("value", (Float) value);
                        } else if (value instanceof Double) {
                            g.writeNumberField("value", (Double) value);
                        }
                        g.writeEndObject();
                    }
                }
            }
        }
        g.writeEndArray();
        g.writeEndObject();
        g.flush();
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:io.macgyver.core.CoreSystemInfo.java

protected Map<String, String> loadRevisionInfo() {
    Closer c = Closer.create();
    try {/*from  ww w.  jav a 2  s  .c  o m*/

        Resource resource = applicationContext.getResource("classpath:macgyver-core-revision.properties");
        if (resource.exists()) {

            InputStream is = resource.getInputStream();
            c.register(is);
            if (is != null) {
                Properties p = new Properties();
                p.load(is);
                Map<String, String> m = Maps.newHashMap();
                for (Map.Entry<Object, Object> entry : p.entrySet()) {
                    m.put(entry.getKey().toString(), entry.getValue().toString());
                }
                return m;
            }

        }

    } catch (Exception e) {
        logger.warn("could not load revision info", e);
    } finally {
        try {
            c.close();
        } catch (IOException e) {
            logger.warn("", e);
        }
    }
    return Maps.newHashMap();
}

From source file:net.ripe.rpki.commons.provisioning.payload.ProvisioningPayloadXmlSerializer.java

private String serializeUTF8Encoded(T payload) throws IOException {
    final String xml;
    final Closer closer = Closer.create();
    try {//from  ww  w  .  ja  v  a2s .com
        final ByteArrayOutputStream outputStream = closer.register(new ByteArrayOutputStream());
        final Writer writer = closer.register(new OutputStreamWriter(outputStream, Charsets.UTF_8));
        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        writer.write(System.getProperty("line.separator"));
        super.serialize(payload, writer);
        final String rawXml = new String(outputStream.toByteArray(), Charsets.UTF_8);
        xml = rawXml.replace("<message", "<message xmlns=\"http://www.apnic.net/specs/rescerts/up-down/\"");
    } catch (final Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
    return xml;
}

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 w w .  j  a  va  2s.c  om
        closer.register(poolable.getSocket());
        closer.register(poolable.getWriter());
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}