Example usage for com.google.common.io Closer rethrow

List of usage examples for com.google.common.io Closer rethrow

Introduction

In this page you can find the example usage for com.google.common.io Closer rethrow.

Prototype

public RuntimeException rethrow(Throwable e) throws IOException 

Source Link

Document

Stores the given throwable and rethrows it.

Usage

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);/*from  ww  w  . j  a v a 2  s  . c o  m*/
    try {
        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:feign.TrustingSSLSocketFactory.java

private static KeyStore loadKeyStore(InputSupplier<InputStream> inputStreamSupplier) throws IOException {
    Closer closer = Closer.create();
    try {//from   ww  w  .j a v  a 2s.com
        InputStream inputStream = closer.register(inputStreamSupplier.getInput());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(inputStream, KEYSTORE_PASSWORD);
        return keyStore;
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.google.cloud.dataflow.sdk.util.ZipFiles.java

/**
 * Zips an entire directory specified by the path.
 *
 * @param sourceDirectory the directory to read from. This directory and all
 *     subdirectories will be added to the zip-file. The path within the zip
 *     file is relative to the directory given as parameter, not absolute.
 * @param zipFile the zip-file to write to.
 * @throws IOException the zipping failed, e.g. because the input was not
 *     readable./*from   w w  w .  j a  v a2 s.c  om*/
 */
static void zipDirectory(File sourceDirectory, File zipFile) throws IOException {
    checkNotNull(sourceDirectory);
    checkNotNull(zipFile);
    checkArgument(sourceDirectory.isDirectory(), "%s is not a valid directory",
            sourceDirectory.getAbsolutePath());
    checkArgument(!zipFile.exists(), "%s does already exist, files are not being overwritten",
            zipFile.getAbsolutePath());
    Closer closer = Closer.create();
    try {
        OutputStream outputStream = closer.register(new BufferedOutputStream(new FileOutputStream(zipFile)));
        zipDirectory(sourceDirectory, outputStream);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.j2swift.util.ProGuardUsageParser.java

public static DeadCodeMap parse(CharSource listing) throws IOException {
    LineProcessor<DeadCodeMap> processor = new LineProcessor<DeadCodeMap>() {
        DeadCodeMap.Builder dead = DeadCodeMap.builder();
        String lastClass;/*w  w  w . ja  v  a2s  . co  m*/

        @Override
        public DeadCodeMap getResult() {
            return dead.build();
        }

        private void handleClass(String line) {
            if (line.endsWith(":")) {
                // Class, but not completely dead; save to read its dead methods
                lastClass = line.substring(0, line.length() - 1);
            } else {
                dead.addDeadClass(line);
            }
        }

        private void handleMethod(String line) throws IOException {
            Matcher methodMatcher = proGuardMethodPattern.matcher(line);
            if (!methodMatcher.matches()) {
                throw new AssertionError("Line doesn't match expected ProGuard format!");
            }
            if (lastClass == null) {
                throw new IOException("Bad listing format: method not attached to a class");
            }
            String returnType = methodMatcher.group(5);
            String methodName = methodMatcher.group(6);
            String arguments = methodMatcher.group(7);
            String signature = buildMethodSignature(returnType, arguments);
            dead.addDeadMethod(lastClass, methodName, signature);
        }

        private void handleField(String line) throws IOException {
            String name = line.substring(line.lastIndexOf(" ") + 1);
            dead.addDeadField(lastClass, name);
        }

        @Override
        public boolean processLine(String line) throws IOException {
            if (line.startsWith("ProGuard, version") || line.startsWith("Reading ")) {
                // ignore output header
            } else if (!line.startsWith("    ")) {
                handleClass(line);
            } else if (line.startsWith("    ") && !line.contains("(")) {
                handleField(line);
            } else {
                handleMethod(line);
            }
            return true;
        }
    };

    // TODO(cgdecker): Just use listing.readLines(processor) once guava_jdk5 is upgraded to a newer
    // version.
    Closer closer = Closer.create();
    try {
        BufferedReader reader = closer.register(listing.openBufferedStream());
        String line;
        while ((line = reader.readLine()) != null) {
            processor.processLine(line);
        }
        return processor.getResult();
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:net.sf.diningout.app.RestaurantService.java

/**
 * Download the photo at the URL and save it to disk.
 *
 * @return ETag header value, if available
 *///  w w w . j  a  va  2 s.  c om
private static String photo(long id, final long restaurantId, String url) throws IOException {
    File file = RestaurantPhotos.file(id, restaurantId);
    if (file == null) {
        return null;
    }
    Files.createParentDirs(file);
    File part = new File(file.getParentFile(), file.getName() + DOT_PART);
    URLConnection con = HttpClient.openConnection(url);
    Closer closer = Closer.create();
    try {
        ByteStreams.copy(closer.register(con.getInputStream()), closer.register(new FileOutputStream(part)));
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
    part.renameTo(file);
    /* notify observers about new photo */
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            cr().notifyChange(ContentUris.withAppendedId(Restaurants.CONTENT_URI, restaurantId), null, false);
        }
    }, 500L); // when the file will hopefully already be flushed to disk
    context().startService(new Intent(context(), RestaurantColorService.class)
            .putExtra(RestaurantColorService.EXTRA_ID, restaurantId));
    return con.getHeaderField("ETag");
}

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

public static void zip(FileObject root, List<FileObject> files, OutputStream out) throws IOException {
    String basePath = root.getName().getPath();
    Closer closer = Closer.create();
    try {/*from  w w w  .  j  ava  2 s .c  o  m*/
        ZipOutputStream zos = new ZipOutputStream(out);
        closer.register(zos);
        for (FileObject fileToCopy : files) {
            ZipEntry zipEntry = zipEntry(basePath, fileToCopy);
            zos.putNextEntry(zipEntry);
            copyFileContents(fileToCopy, zos);
            zos.flush();
            zos.closeEntry();
        }
    } catch (IOException e) {
        throw closer.rethrow(e);
    } 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 {//  w w w.  j  a  v a 2 s .c  o  m
            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: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 {//  ww w.  java2  s  .com
        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:tachyon.util.CommonUtils.java

/**
 * Blocking operation that copies the processes stdout/stderr to this JVM's stdout/stderr.
 *///  w  w  w .  ja 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: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  ww . j av a 2s . 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, 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();
    }
}