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.gradle.api.internal.tasks.cache.LocalDirectoryTaskOutputCache.java

@Override
public void store(final TaskCacheKey key, final TaskOutputWriter result) throws IOException {
    persistentCache.useCache("store task output", new Runnable() {
        @Override//w  w  w.  ja  v a  2  s.  com
        public void run() {
            File file = getFile(key.getHashCode());
            try {
                Closer closer = Closer.create();
                OutputStream output = closer.register(new FileOutputStream(file));
                try {
                    result.writeTo(output);
                } catch (Throwable ex) {
                    throw closer.rethrow(ex);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }
    });
}

From source file:org.gradle.caching.local.internal.DirectoryBuildCacheService.java

@Override
public void store(final BuildCacheKey key, final BuildCacheEntryWriter result) throws BuildCacheException {
    tempFileStore.withTempFile(key, new Action<File>() {
        @Override//from  www  .j  a v a 2 s .c om
        public void execute(@Nonnull File file) {
            try {
                Closer closer = Closer.create();
                try {
                    result.writeTo(closer.register(new FileOutputStream(file)));
                } catch (Exception e) {
                    throw closer.rethrow(e);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw UncheckedException.throwAsUncheckedException(ex);
            }

            storeLocally(key, file);
        }
    });
}

From source file:org.grouplens.lenskit.eval.graph.GraphDumper.java

/**
 * Render a graph to a file./*from   www . jav  a 2 s.c  o  m*/
 *
 * @param graph The graph to render.
 * @param graphvizFile The file to write the graph to.
 * @throws IOException
 */
public static void renderGraph(DAGNode<Component, Dependency> graph, File graphvizFile)
        throws IOException, RecommenderBuildException {
    logger.debug("graph has {} nodes", graph.getReachableNodes().size());
    logger.debug("simulating instantiation");
    RecommenderInstantiator instantiator = RecommenderInstantiator.create(graph);
    DAGNode<Component, Dependency> unshared = instantiator.simulate();
    logger.debug("unshared graph has {} nodes", unshared.getReachableNodes().size());
    Closer close = Closer.create();
    try {
        Writer writer = close.register(new FileWriter(graphvizFile));
        GraphWriter gw = close.register(new GraphWriter(writer));
        GraphDumper dumper = new GraphDumper(graph, unshared.getReachableNodes(), gw);
        logger.debug("writing root node");
        String rid = dumper.setRoot(graph);
        // process each other node & add an edge
        for (DAGEdge<Component, Dependency> e : graph.getOutgoingEdges()) {
            DAGNode<Component, Dependency> target = e.getTail();
            Component csat = target.getLabel();
            if (!satIsNull(csat.getSatisfaction())) {
                logger.debug("processing node {}", csat.getSatisfaction());
                String id = dumper.process(target);
                gw.putEdge(EdgeBuilder.create(rid, id).set("arrowhead", "vee").build());
            }
        }
        // and we're done
        dumper.finish();
    } catch (Throwable th) {
        throw close.rethrow(th);
    } finally {
        close.close();
    }
}

From source file:net.ripe.rpki.commons.crypto.util.PregeneratedKeyPairFactory.java

@Override
public synchronized KeyPair generate() {
    try {//from  w w  w .ja  v a2 s.co m
        String alias = "key_" + count;
        ++count;

        PrivateKey key = (PrivateKey) pregeneratedKeys.getKey(alias, PASSPHRASE);
        KeyPair result;
        if (key == null) {
            result = super.generate();
            pregeneratedKeys.setKeyEntry(alias, result.getPrivate(), PASSPHRASE,
                    new Certificate[] { createCertificate(result).getCertificate() });
            final Closer closer = Closer.create();
            try {
                final OutputStream output = new FileOutputStream(keyStoreFile);
                pregeneratedKeys.store(output, PASSPHRASE);
            } catch (final Throwable t) {
                throw closer.rethrow(t);
            } finally {
                closer.close();
            }
        } else {
            Certificate certificate = pregeneratedKeys.getCertificateChain(alias)[0];
            result = new KeyPair(certificate.getPublicKey(), key);
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.jmxtrans.model.output.support.HttpOutputWriter.java

private void writeResults(Server server, Query query, Iterable<Result> results,
        HttpURLConnection httpURLConnection) throws IOException {
    Closer closer = Closer.create();
    try {/*from w ww . ja  v  a2 s.  c o m*/
        OutputStreamWriter outputStream = closer
                .register(new OutputStreamWriter(httpURLConnection.getOutputStream(), charset));

        target.write(outputStream, server, query, results);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.seyren.core.service.notification.IrcCatNotificationService.java

private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException {
    Socket socket = new Socket(ircCatHost, ircCatPort);
    Closer closer = Closer.create();
    try {//from w w w.j  av  a 2 s  .  c  om
        Writer out = closer
                .register(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8")));
        out.write(format("%s %s\n", channel, message));
        out.flush();
    } catch (IOException e) {
        socket.close();
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

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

/**
 * Loads the contents of an existing source into a memory byte source.
 * @return The loaded data in a byte source.
 *///from  w w  w  .  j a  v  a  2  s .co  m
public MemoryByteSource load(ByteSource source) throws IOException {
    checkNotNull(source, "The byte source to load must be provided");
    if (transformer == null && source instanceof MemoryByteSource) {
        return transform((MemoryByteSource) source);
    }
    Closer closer = Closer.create();
    try {
        InputStream is = closer.register(source.openStream());
        return load(is);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:org.gradle.api.internal.tasks.cache.TarTaskOutputPacker.java

@Override
public void unpack(TaskOutputsInternal taskOutputs, InputStream input) throws IOException {
    Closer closer = Closer.create();
    TarInputStream tarInput = new TarInputStream(input);
    try {/*  w w  w .j a v  a  2  s  .co m*/
        unpack(taskOutputs, tarInput);
    } catch (Throwable ex) {
        throw closer.rethrow(ex);
    } finally {
        closer.close();
    }
}

From source file:org.grouplens.lenskit.cli.TrainModel.java

@Override
public void execute() throws IOException, RecommenderBuildException {
    LenskitConfiguration dataConfig = input.getConfiguration();
    LenskitRecommenderEngineBuilder builder = LenskitRecommenderEngine.newBuilder();
    for (LenskitConfiguration config : environment.loadConfigurations(getConfigFiles())) {
        builder.addConfiguration(config);
    }// ww w.  j  av a  2s .  c  om
    builder.addConfiguration(dataConfig, ModelDisposition.EXCLUDED);

    Stopwatch timer = Stopwatch.createStarted();
    LenskitRecommenderEngine engine = builder.build();
    timer.stop();
    logger.info("built model in {}", timer);
    File output = getOutputFile();
    logger.info("writing model to {}", output);
    Closer closer = Closer.create();
    try {
        OutputStream stream = closer.register(new FileOutputStream(output));
        if (LKFileUtils.isCompressed(output)) {
            stream = closer.register(new GZIPOutputStream(stream));
        }
        engine.write(stream);
    } catch (Throwable th) {
        throw closer.rethrow(th);
    } finally {
        closer.close();
    }
}

From source file:alluxio.cli.fs.command.LoadCommand.java

/**
 * Loads a file or directory in Alluxio space, makes it resident in Alluxio.
 *
 * @param filePath The {@link AlluxioURI} path to load into Alluxio
 * @param local whether to load data to local worker even when the data is already loaded remotely
 *//*from  w  w w.ja v a 2  s.c  om*/
private void load(AlluxioURI filePath, boolean local) 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, local);
        }
    } else {
        OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.CACHE_PROMOTE);
        if (local) {
            if (!FileSystemContext.INSTANCE.hasLocalWorker()) {
                System.out
                        .println("When local option is specified," + " there must be a local worker available");
                return;
            }
            options.setCacheLocationPolicy(new LocalFirstPolicy());
        } else if (status.getInAlluxioPercentage() == 100) {
            // The file has already been fully loaded into Alluxio.
            System.out.println(filePath + " already in Alluxio fully");
            return;
        }
        Closer closer = Closer.create();
        try {
            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");
}