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:gobblin.metrics.reporter.util.EventUtils.java

/**
 * Parses a {@link gobblin.metrics.MetricReport} from a byte array Avro serialization.
 * @param reuse MetricReport to reuse.//from w  w  w .  j a v  a  2 s.  c  om
 * @param bytes Input bytes.
 * @return MetricReport.
 * @throws java.io.IOException
 */
public synchronized static GobblinTrackingEvent deserializeReportFromAvroSerialization(
        GobblinTrackingEvent reuse, byte[] bytes) throws IOException {
    if (!reader.isPresent()) {
        reader = Optional.of(new SpecificDatumReader<>(GobblinTrackingEvent.class));
    }

    Closer closer = Closer.create();

    try {
        DataInputStream inputStream = closer.register(new DataInputStream(new ByteArrayInputStream(bytes)));

        // Check version byte
        int versionNumber = inputStream.readInt();
        if (versionNumber != SCHEMA_VERSION) {
            throw new IOException(
                    String.format("MetricReport schema version not recognized. Found version %d, expected %d.",
                            versionNumber, SCHEMA_VERSION));
        }

        // Decode the rest
        Decoder decoder = DecoderFactory.get().binaryDecoder(inputStream, null);
        return reader.get().read(reuse, decoder);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.spotify.styx.StyxApi.java

private static AggregateStorage storage(Environment environment) {
    final Config config = environment.config();
    final Closer closer = environment.closer();

    final Connection bigTable = closer.register(createBigTableConnection(config));
    final Datastore datastore = createDatastore(config);
    return new AggregateStorage(bigTable, datastore, DEFAULT_RETRY_BASE_DELAY_BT);
}

From source file:org.glowroot.common.util.Version.java

private static @Nullable Manifest getManifest(@Nullable URL url) throws IOException {
    if (url == null) {
        return null;
    }/* w  w  w  .j a va 2 s.  c  o  m*/
    // Closer is used to simulate Java 7 try-with-resources
    Closer closer = Closer.create();
    try {
        InputStream manifestIn = closer.register(url.openStream());
        return new Manifest(manifestIn);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:org.jmattr.meta.impl.ServicesFiles.java

/**
 * Reads the set of service classes from a service file.
 *
 * @param input not {@code null}. Closed after use.
 * @return a not {@code null Set} of service class names.
 * @throws IOException//from  ww w  .  j ava 2  s.  c o m
 */
static Set<String> readServiceFile(InputStream input) throws IOException {
    HashSet<String> serviceClasses = new HashSet<String>();
    Closer closer = Closer.create();
    try {
        // TODO(gak): use CharStreams
        BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, Charsets.UTF_8)));
        String line;
        while ((line = r.readLine()) != null) {
            int commentStart = line.indexOf('#');
            if (commentStart >= 0) {
                line = line.substring(0, commentStart);
            }
            line = line.trim();
            if (!line.isEmpty()) {
                serviceClasses.add(line);
            }
        }
        return serviceClasses;
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.google.auto.service.processor.ServicesFiles.java

/**
 * Reads the set of service classes from a service file.
 *
 * @param input not {@code null}. Closed after use.
 * @return a not {@code null Set} of service class names.
 * @throws IOException//from   w w  w. j  a  v  a  2  s .com
 */
static Set<String> readServiceFile(InputStream input) throws IOException {
    HashSet<String> serviceClasses = new HashSet<String>();
    Closer closer = Closer.create();
    try {
        // TODO(gak): use CharStreams
        BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
        String line;
        while ((line = r.readLine()) != null) {
            int commentStart = line.indexOf('#');
            if (commentStart >= 0) {
                line = line.substring(0, commentStart);
            }
            line = line.trim();
            if (!line.isEmpty()) {
                serviceClasses.add(line);
            }
        }
        return serviceClasses;
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.clank.launcher.LauncherUtils.java

public static Properties loadProperties(Class<?> clazz, String name, String extraProperty) throws IOException {
    Closer closer = Closer.create();
    Properties prop = new Properties();
    try {//from  www . ja v  a 2  s . c  o  m
        InputStream in = closer.register(clazz.getResourceAsStream(name));
        prop.load(in);
        String extraPath = System.getProperty(extraProperty);
        if (extraPath != null) {
            log.info("Loading extra properties for " + clazz.getCanonicalName() + ":" + name + " from "
                    + extraPath + "...");
            in = closer.register(new BufferedInputStream(closer.register(new FileInputStream(extraPath))));
            prop.load(in);
        }
    } finally {
        closer.close();
    }

    return prop;
}

From source file:com.github.autermann.sockets.ssl.SSLUtils.java

public static PrivateKey readKey(InputSupplier<? extends InputStream> in)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Closer closer = Closer.create();
    try {//from w w  w . ja v a  2 s . c  om
        Reader reader = closer.register(CharStreams.newReaderSupplier(in, Charsets.UTF_8).getInput());
        return createPrivateKey(new PemReader(reader).readPemObject());
    } catch (IOException e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.util.VFSZipper.java

public static void unzip(InputStream is, FileObject file) throws IOException {
    Closer closer = Closer.create();
    closer.register(is);
    try {//  w ww  .  java 2s  . c  o  m
        OutputStream os = file.getContent().getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);
        closer.register(zos);
        ByteStreams.copy(is, zos);
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}

From source file:org.asoem.greyfish.utils.persistence.Persisters.java

/**
 * Create a copy of the given object {@code o} through serialization unsing the given {@code persister}.
 *
 * @param o         the object to copy//from ww  w.java 2s  . co  m
 * @param persister the persister to use for serialization and deserialization.
 * @param clazz     the class to cast the deserialized object to
 * @param <T>       the type of {@code o}
 * @return a copy of {@code o}, as implemented by the given {@code persister}
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static <T> T copy(final T o, final Persister persister, final Class<T> clazz)
        throws IOException, ClassNotFoundException {
    final Closer closer = Closer.create();

    try {
        final ByteArrayOutputStream outputStream = closer.register(new ByteArrayOutputStream());
        persister.serialize(o, outputStream);
        final ByteArrayInputStream inputStream = closer
                .register(new ByteArrayInputStream(outputStream.toByteArray()));
        return persister.deserialize(inputStream, clazz);
    } finally {
        closer.close();
    }
}

From source file:ru.runa.af.web.system.TaskHandlerClassesInformation.java

private static void init() {
    String deploymentDirPath = IoCommons.getDeploymentDirPath();
    String earFilePath = deploymentDirPath + "/" + SystemProperties.getEARFileName();
    Closer closer = Closer.create();
    try {//from   w w  w  .j a va 2 s . c o m
        ZipInputStream earInputStream = closer.register(new ZipInputStream(new FileInputStream(earFilePath)));
        ZipEntry entry;
        while ((entry = earInputStream.getNextEntry()) != null) {
            if (entry.getName().endsWith(".jar")) {
                searchInJar(entry.getName(), new JarInputStream(earInputStream));
            }
        }
        if (IoCommons.getAppServer() == AppServer.JBOSS4) {
            File deploymentDirectory = new File(deploymentDirPath);
            log.debug("Searching in deployment directory: " + deploymentDirectory);
            for (File file : IoCommons.getJarFiles(deploymentDirectory)) {
                JarInputStream jarInputStream = closer.register(new JarInputStream(new FileInputStream(file)));
                searchInJar(file.getName(), jarInputStream);
            }
        }
        File extensionDirectory = new File(IoCommons.getExtensionDirPath());
        if (extensionDirectory.exists() && extensionDirectory.isDirectory()) {
            log.debug("Searching in extension directory: " + extensionDirectory);
            for (File file : IoCommons.getJarFiles(extensionDirectory)) {
                JarInputStream jarInputStream = closer.register(new JarInputStream(new FileInputStream(file)));
                searchInJar(file.getName(), jarInputStream);
            }
        } else {
            log.debug("No extension directory found: " + extensionDirectory);
        }
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            log.warn(e);
        }
    }
}