List of usage examples for com.google.common.io Closer create
public static Closer create()
From source file:gobblin.yarn.Log4jConfigurationHelper.java
/** * Update the log4j configuration./* w w w.j a v a 2 s. c o m*/ * * @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:gobblin.metrics.MetricReportUtils.java
/** * Parses a {@link gobblin.metrics.MetricReport} from a byte array representing a json input. * @param reuse MetricReport to reuse.//from w ww. ja va 2s.c o m * @param bytes Input bytes. * @return MetricReport. * @throws java.io.IOException */ public synchronized static MetricReport deserializeReportFromJson(MetricReport reuse, byte[] bytes) throws IOException { if (!READER.isPresent()) { READER = Optional.of(new SpecificDatumReader<MetricReport>(MetricReport.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().jsonDecoder(MetricReport.SCHEMA$, inputStream); return READER.get().read(reuse, decoder); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } }
From source file:org.glowroot.common.Manifests.java
public static @Nullable Manifest getManifest(Class<?> clazz) throws IOException { URL classURL = clazz.getResource(clazz.getSimpleName() + ".class"); if (classURL == null) { logger.warn("url for class is unexpectedly null: {}", clazz); return null; }//from www. j av a 2 s .c o m String externalForm = classURL.toExternalForm(); if (!externalForm.startsWith("jar:")) { return null; } URL manifestURL = new URL( externalForm.substring(0, externalForm.lastIndexOf('!')) + "!/META-INF/MANIFEST.MF"); // Closer is used to simulate Java 7 try-with-resources Closer closer = Closer.create(); InputStream manifestIn = closer.register(manifestURL.openStream()); try { return new Manifest(manifestIn); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } }
From source file:org.apache.gobblin.aws.Log4jConfigHelper.java
/** * Update the log4j configuration.// w w w . j av a 2s. co m * * @param targetClass the target class used to get the original log4j configuration file as a resource * @param log4jFileName the custom log4j configuration properties file name * @throws IOException if there's something wrong with updating the log4j configuration */ public static void updateLog4jConfiguration(Class<?> targetClass, String log4jFileName) throws IOException { final Closer closer = Closer.create(); try { final InputStream inputStream = closer.register(targetClass.getResourceAsStream("/" + log4jFileName)); final Properties originalProperties = new Properties(); originalProperties.load(inputStream); LogManager.resetConfiguration(); PropertyConfigurator.configure(originalProperties); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } }
From source file:org.glowroot.agent.weaving.ClassLoaders.java
static void defineClassesInBootstrapClassLoader(Collection<LazyDefinedClass> lazyDefinedClasses, Instrumentation instrumentation, File generatedJarFile) throws IOException { Closer closer = Closer.create(); try {/*from ww w . ja v a 2s.co m*/ FileOutputStream out = closer.register(new FileOutputStream(generatedJarFile)); JarOutputStream jarOut = closer.register(new JarOutputStream(out)); generate(lazyDefinedClasses, jarOut); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(generatedJarFile)); // appendToBootstrapClassLoaderSearch() line above does not add to the bootstrap resource // search path, only to the bootstrap class search path (this is different from // appendToSystemClassLoaderSearch() which adds to both the system resource search path and // the system class search path) // // adding the generated jar file to the bootstrap resource search path is probably needed // more generally, but it is at least needed to support jboss 4.2.0 - 4.2.3 because // org.jboss.mx.loading.LoadMgr3.beginLoadTask() checks that the class loader has the class // as a resource before loading it, so without adding the generated jar file to the // bootstrap resource search path, jboss ends up throwing ClassNotFoundException for the // glowroot generated classes that have been added to the bootstrap class loader search path // (see issue #101 for more info on this particular jboss issue) appendToBootstrapResourcePath(generatedJarFile); }
From source file:org.stem.db.FatFileAllocator.java
public static void allocateFile(String filePath, long sizeInMB, boolean mark) throws IOException { long started = System.currentTimeMillis(); Closer closer = Closer.create(); try {// w w w .j a v a 2s .c om File file = new File(filePath); if (file.exists()) throw new IOException(String.format("File already exists: %s", filePath)); RandomAccessFile rw = closer.register(new RandomAccessFile(file, "rw")); rw.setLength(sizeInMB * 1024 * 1024); if (mark) { rw.seek(0); rw.writeByte(FatFile.MARKER_BLANK); rw.seek(rw.length() - 1); rw.writeByte(FatFile.MARKER_BLANK); } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); logger.debug("{} was allocated in {} ms", filePath, System.currentTimeMillis() - started); } }
From source file:org.apache.gobblin.util.logs.Log4jConfigurationHelper.java
/** * Update the log4j configuration.// ww w . jav a2 s . co m * * @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 * @param log4jFileName the custom log4j configuration properties file name * @throws IOException if there's something wrong with updating the log4j configuration */ public static void updateLog4jConfiguration(Class<?> targetClass, String log4jPath, String log4jFileName) throws IOException { Closer closer = Closer.create(); try { InputStream fileInputStream = closer.register(new FileInputStream(log4jPath)); InputStream inputStream = closer.register(targetClass.getResourceAsStream("/" + log4jFileName)); 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: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 av a 2s . co 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:org.asoem.greyfish.utils.persistence.Persisters.java
/** * Create a copy of the given object {@code o} by serializing it with the given {@code Persister}. What copy means * in this context, dependents fully on the {@code Persister} implementation. * * @param o the object you wish to copy * @param persister the {@code Persister} to use for the serialization process * @return a copy of {@code o}// www.ja v a 2 s . c o m * @throws Exception if some errors occur during the serialization process */ public static <T> T copyAsync(final T o, final Persister persister) throws Exception { checkNotNull(o); checkNotNull(persister); final Closer closer = Closer.create(); try { final PipedOutputStream pipedOutputStream = closer.register(new PipedOutputStream()); final PipedInputStream pipedInputStream = closer.register(new PipedInputStream(pipedOutputStream)); final Future<T> deserializeFuture = Executors.newSingleThreadExecutor().submit(new Callable<T>() { @SuppressWarnings("unchecked") // safe if persister is implemented correctly @Override public T call() throws Exception { try { return (T) persister.deserialize(pipedInputStream, o.getClass()); } catch (Exception e) { pipedInputStream.close(); throw e; } } }); try { persister.serialize(o, pipedOutputStream); } catch (Exception e) { if (!deserializeFuture.isDone()) { deserializeFuture.cancel(true); throw e; } else { // the future task had an exception and closed the stream, which caused this exception deserializeFuture.get(); // throws the exception throw new AssertionError("unreachable"); } } return deserializeFuture.get(3, TimeUnit.SECONDS); } 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/* w w w .ja va 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(); } }