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:gobblin.yarn.Log4jConfigurationHelper.java

/**
 * Update the log4j configuration./*from  w ww .jav a 2 s  . com*/
 *
 * @param targetClass the target class used to get the original log4j configuration file as a resource
 * @param log4jPath the custom log4j configuration properties file path
 * @throws IOException if there's something wrong with updating the log4j configuration
 */
public static void updateLog4jConfiguration(Class<?> targetClass, String log4jPath) throws IOException {
    Closer closer = Closer.create();
    try {
        InputStream fileInputStream = closer.register(new FileInputStream(log4jPath));
        InputStream inputStream = closer
                .register(targetClass.getResourceAsStream("/" + LOG4J_CONFIGURATION_FILE_NAME));
        Properties customProperties = new Properties();
        customProperties.load(fileInputStream);
        Properties originalProperties = new Properties();
        originalProperties.load(inputStream);

        for (Entry<Object, Object> entry : customProperties.entrySet()) {
            originalProperties.setProperty(entry.getKey().toString(), entry.getValue().toString());
        }

        LogManager.resetConfiguration();
        PropertyConfigurator.configure(originalProperties);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:net.ripe.rpki.commons.crypto.crl.X509Crl.java

private static X509CRL makeX509CRLFromEncoded(byte[] encoded) {
    final X509CRL crl;
    if (null != encoded) {
        try {/*from   ww  w .j  a v  a  2 s.c om*/
            final Closer closer = Closer.create();
            try {
                final ByteArrayInputStream in = new ByteArrayInputStream(encoded);
                final CertificateFactory factory = CertificateFactory.getInstance("X.509");
                crl = (X509CRL) factory.generateCRL(in);
            } catch (final CertificateException e) {
                throw closer.rethrow(new IllegalArgumentException(e));
            } catch (final CRLException e) {
                throw closer.rethrow(new IllegalArgumentException(e));
            } catch (final Throwable t) {
                throw closer.rethrow(t);
            } finally {
                closer.close();
            }
        } catch (final IOException e) {
            throw new RuntimeException("Error managing CRL I/O stream", e);
        }
    } else {
        crl = null;
    }
    return crl;

}

From source file:se.sics.datamodel.util.DMKeyFactory.java

public static Key getDataKey(ByteId dbId, ByteId typeId, ByteId objNrId) throws IOException {
    Closer closer = Closer.create();
    try {/*from w  w  w .  j a va2  s .c om*/
        ByteArrayOutputStream baos = closer.register(new ByteArrayOutputStream());
        DataOutputStream w = closer.register(new DataOutputStream(baos));

        w.write(dbId.getId());
        w.writeByte(dataKF);
        w.write(typeId.getId());
        w.write(objNrId.getId());
        w.flush();

        return new Key(baos.toByteArray());
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:net.simon04.guavavfs.VirtualFiles.java

private static MappedByteBuffer map(RandomAccessFile raf, MapMode mode, long size) throws IOException {
    Closer closer = Closer.create();
    try {/* ww w . ja  v  a 2 s. c o  m*/
        FileChannel channel = closer.register(raf.getChannel());
        return channel.map(mode, 0, size);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.grouplens.lenskit.eval.ClassDirectory.java

/**
 * Get a class directory for a specific class loader.
 * @param loader The class loader.//from  w  w w  .j  a  v a 2  s .c o  m
 * @return The class directory.
 */
public static ClassDirectory forClassLoader(ClassLoader loader) {
    ImmutableSetMultimap.Builder<String, String> mapping = ImmutableSetMultimap.builder();
    try {
        Enumeration<URL> urls = loader.getResources("META-INF/classes.lst");
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Closer closer = Closer.create();
            try {
                InputStream stream = closer.register(url.openStream());
                Reader rdr = closer.register(new InputStreamReader(stream, "UTF-8"));
                BufferedReader buf = closer.register(new BufferedReader(rdr));
                String line = buf.readLine();
                while (line != null) {
                    int idx = line.lastIndexOf('.');
                    if (idx >= 0) {
                        String name = line.substring(idx + 1);
                        String pkg = line.substring(0, idx);
                        mapping.put(name, pkg);
                    }
                    line = buf.readLine();
                }
            } catch (Throwable th) {
                throw closer.rethrow(th);
            } finally {
                closer.close();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Error loading class lists", e);
    }

    return new ClassDirectory(mapping.build());
}

From source file:tachyon.client.file.FileSystemUtils.java

/**
 * Persist the given file to the under file system.
 *
 * @param fs {@link FileSystem} to carry out Tachyon operations
 * @param uri the uri of the file to persist
 * @param status the status info of the file
 * @param tachyonConf TachyonConf object
 * @return the size of the file persisted
 * @throws IOException if an I/O error occurs
 * @throws FileDoesNotExistException if the given file does not exist
 * @throws TachyonException if an unexpected Tachyon error occurs
 *//*from   w w w. j a v a2s .  c  o m*/
public static long persistFile(FileSystem fs, TachyonURI uri, URIStatus status, TachyonConf tachyonConf)
        throws IOException, FileDoesNotExistException, TachyonException {
    // TODO(manugoyal) move this logic to the worker, as it deals with the under file system
    Closer closer = Closer.create();
    long ret;
    try {
        OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
        FileInStream in = closer.register(fs.openFile(uri, options));
        TachyonURI dstPath = new TachyonURI(status.getUfsPath());
        UnderFileSystem ufs = UnderFileSystem.get(dstPath.toString(), tachyonConf);
        String parentPath = dstPath.getParent().toString();
        if (!ufs.exists(parentPath) && !ufs.mkdirs(parentPath, true)) {
            throw new IOException("Failed to create " + parentPath);
        }
        OutputStream out = closer.register(ufs.create(dstPath.getPath()));
        ret = IOUtils.copyLarge(in, out);
    } catch (Exception e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
    // Tell the master to mark the file as persisted
    fs.setAttribute(uri, SetAttributeOptions.defaults().setPersisted(true));
    return ret;
}

From source file:com.skcraft.launcher.persistence.Persistence.java

/**
 * Read an object from a byte source, without binding it.
 *
 * @param source byte source//from   ww w .ja  va2s  .  c o m
 * @param cls the class
 * @param returnNull true to return null if the object could not be loaded
 * @param <V> the type of class
 * @return an object
 */
public static <V> V read(ByteSource source, Class<V> cls, boolean returnNull) {
    V object;
    Closer closer = Closer.create();

    try {
        object = mapper.readValue(closer.register(source.openBufferedStream()), cls);
    } catch (IOException e) {
        if (!(e instanceof FileNotFoundException)) {
            log.log(Level.INFO, "Failed to load" + cls.getCanonicalName(), e);
        }

        if (returnNull) {
            return null;
        }

        try {
            object = cls.newInstance();
        } catch (InstantiationException e1) {
            throw new RuntimeException("Failed to construct object with no-arg constructor", e1);
        } catch (IllegalAccessException e1) {
            throw new RuntimeException("Failed to construct object with no-arg constructor", e1);
        }
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
        }
    }

    return object;
}

From source file:se.sics.datamodel.util.DMKeyFactory.java

private static String deserializeLexicoString(DataInputStream r) throws IOException {
    Closer closer = Closer.create();
    try {/* w w  w  .java2  s .  co m*/
        ByteArrayOutputStream baos = closer.register(new ByteArrayOutputStream());
        DataOutputStream w = closer.register(new DataOutputStream(baos));

        do {
            byte b = r.readByte();
            if (b == STRING_END) {
                break;
            }
            baos.write(b);
        } while (true);
        w.flush();

        return new String(baos.toByteArray(), "UTF8");
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:se.sics.datamodel.util.DMKeyFactory.java

private static Key getIndexKeyByte(ByteId dbId, ByteId typeId, ByteId indexId, byte[] indexValue,
        ByteId objNrId) throws IOException {
    Closer closer = Closer.create();
    try {/*from   w  w w .  ja v  a 2  s .c  o m*/
        ByteArrayOutputStream baos = closer.register(new ByteArrayOutputStream());
        DataOutputStream w = closer.register(new DataOutputStream(baos));

        w.write(dbId.getId());
        w.writeByte(indexKF);
        w.write(typeId.getId());
        w.write(indexId.getId());
        w.write(indexValue);
        w.write(objNrId.getId());
        w.flush();

        return new Key(baos.toByteArray());
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:net.simon04.guavavfs.VirtualFiles.java

/**
 * Maps a file in to memory as per/*from  w w w.  jav  a2  s. co m*/
 * {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}
 * using the requested {@link MapMode}.
 * <p>
 * <p>Files are mapped from offset 0 to {@code size}.
 * <p>
 * <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist,
 * it will be created with the requested {@code size}. Thus this method is
 * useful for creating memory mapped files which do not yet exist.
 * <p>
 * <p>This only works for files {@code <=} {@link Integer#MAX_VALUE} bytes.
 *
 * @param file the file to map
 * @param mode the mode to use when mapping {@code file}
 * @return a buffer reflecting {@code file}
 * @throws IOException if an I/O error occurs
 * @see FileChannel#map(MapMode, long, long)
 */
public static MappedByteBuffer map(String file, MapMode mode, long size)
        throws FileNotFoundException, IOException {
    checkNotNull(file);
    checkNotNull(mode);

    Closer closer = Closer.create();
    try {
        RandomAccessFile raf = closer
                .register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
        return map(raf, mode, size);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}