List of usage examples for com.google.common.io Closeables close
public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException
From source file:org.jclouds.abiquo.handlers.AbiquoErrorHandler.java
@Override public void handleError(final HttpCommand command, final HttpResponse response) { Exception exception = null;// www. j a v a 2 s .c o m String defaultMessage = String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); try { switch (response.getStatusCode()) { case 401: case 403: // Authorization exceptions do not return an errors DTO, so we // encapsulate a // generic exception exception = new AuthorizationException(defaultMessage, new HttpResponseException(command, response, defaultMessage)); break; case 404: exception = new ResourceNotFoundException(defaultMessage, getExceptionToPropagate(command, response, defaultMessage)); break; case 301: // Moved resources in Abiquo should be handled with the // ReturnMovedResource // exception parser to return the moved entity. exception = new HttpResponseException(command, response, defaultMessage); break; default: exception = getExceptionToPropagate(command, response, defaultMessage); break; } } finally { try { Closeables.close(response.getPayload(), true); command.setException(exception); } catch (IOException e) { throw propagate(e); } } }
From source file:ch.ledcom.maven.sitespeed.SiteSpeedSingleThreadedOrchestrator.java
public void siteSpeed() throws IOException { if (!outputDir.exists()) { outputDir.mkdirs();/*from w w w. j a va 2s .co m*/ } // crawl site to get the list of URLs to analyze crawler.crawl(new URICallback() { @Override public void submit(final URI uri) { Writer out = null; boolean threw = true; try { final URL url = uri.toURL(); log.info("Received URL to analyze [" + url.toExternalForm() + "]"); Document doc = analyzer.analyze(url); out = createReportWriter(uri); log.info("Creating report for URL [" + url.toExternalForm() + "]"); log.info("Document to report for URL [" + url.toExternalForm() + "]"); log.debug(XmlPrettyPrinter.prettyPrint(doc)); reporter.report(doc, out); threw = false; crawler.shutdown(); } catch (IOException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { Closeables.close(out, threw); } catch (IOException e) { e.printStackTrace(); } } } }); new ResourceFiles().export(outputDir); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.eclipse.epp.internal.logging.aeri.ui.utils.Json.java
public static <T> List<T> deserializeZip(File zip, Class<T> classOfT) throws IOException { List<T> res = Lists.newLinkedList(); ZipInputStream zis = null;//from w w w . j a v a2 s . co m try { InputSupplier<FileInputStream> fis = Files.newInputStreamSupplier(zip); zis = new ZipInputStream(fis.getInput()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (!entry.isDirectory()) { res.add(Json.<T>deserialize(zis, classOfT)); } } } finally { Closeables.close(zis, true); } return res; }
From source file:com.android.ide.common.process.DefaultProcessExecutor.java
/** * Get the stderr/stdout outputs of a process and return when the process is done. * Both <b>must</b> be read or the process will block on windows. * * @param process The process to get the output from. * @param output The processOutput containing where to send the output. * Note that on Windows capturing the output is not optional. If output is null * the stdout/stderr will be captured and discarded. * @return the process return code./*www . jav a2s . c o m*/ * @throws InterruptedException if {@link Process#waitFor()} was interrupted. */ private static int grabProcessOutput(@NonNull final Process process, @NonNull final ProcessOutput output) throws InterruptedException { Thread threadErr = new Thread("stderr") { @Override public void run() { InputStream stderr = process.getErrorStream(); OutputStream stream = output.getErrorOutput(); try { ByteStreams.copy(stderr, stream); stream.flush(); } catch (IOException e) { // ignore? } finally { try { Closeables.close(stderr, true /* swallowIOException */); } catch (IOException e) { // cannot happen } try { Closeables.close(stream, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } } }; Thread threadOut = new Thread("stdout") { @Override public void run() { InputStream stdout = process.getInputStream(); OutputStream stream = output.getStandardOutput(); try { ByteStreams.copy(stdout, stream); stream.flush(); } catch (IOException e) { // ignore? } finally { try { Closeables.close(stdout, true /* swallowIOException */); } catch (IOException e) { // cannot happen } try { Closeables.close(stream, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } } }; threadErr.start(); threadOut.start(); // it looks like on windows process#waitFor() can return // before the thread have filled the arrays, so we wait for both threads and the // process itself. threadErr.join(); threadOut.join(); // get the return code from the process return process.waitFor(); }
From source file:edu.rosehulman.mahout.classifier.naivebayes.NaiveBayesModel.java
public static NaiveBayesModel materialize(Path output, Configuration conf) throws IOException { FileSystem fs = output.getFileSystem(conf); Vector weightsPerLabel = null; Vector perLabelThetaNormalizer = null; Vector weightsPerFeature = null; Matrix weightsPerLabelAndFeature;//from w ww.j a v a 2 s . c o m float alphaI; FSDataInputStream in = fs.open(new Path(output, "naiveBayesModel.bin")); try { alphaI = in.readFloat(); weightsPerFeature = VectorWritable.readVector(in); weightsPerLabel = new DenseVector(VectorWritable.readVector(in)); perLabelThetaNormalizer = new DenseVector(VectorWritable.readVector(in)); weightsPerLabelAndFeature = new SparseRowMatrix(weightsPerLabel.size(), weightsPerFeature.size()); for (int label = 0; label < weightsPerLabelAndFeature.numRows(); label++) { weightsPerLabelAndFeature.assignRow(label, VectorWritable.readVector(in)); } } finally { Closeables.close(in, true); } NaiveBayesModel model = new NaiveBayesModel(weightsPerLabelAndFeature, weightsPerFeature, weightsPerLabel, perLabelThetaNormalizer, alphaI); model.validate(); return model; }
From source file:com.github.autermann.sockets.ssl.KeyStoreSSLConfiguration.java
public static SSLConfiguration load(InputStream in) throws IOException { try {/* w w w . j a v a 2s .c o m*/ Properties p = new Properties(); p.load(checkNotNull(in)); return load(p); } finally { Closeables.close(in, true); } }
From source file:org.jclouds.management.JcloudsManagement.java
/** * Parses the String into a {@link Properties} object. * The String is expected to separated key from valus using the '=' sign and key/value pairs with a new line. * @param input// w ww . ja v a2 s . c o m * @return * @throws IOException */ private static Properties stringToProperties(@Nullable String input) throws IOException { Properties properties = new Properties(); if (!Strings.isNullOrEmpty(input)) { ByteArrayInputStream bis = null; try { bis = new ByteArrayInputStream(input.getBytes(Charsets.UTF_8)); properties.load(bis); } finally { Closeables.close(bis, true); } } return properties; }
From source file:net.pterodactylus.sonitus.data.AbstractFilter.java
@Override public void close() { try {/*from ww w. j av a 2 s .c om*/ Closeables.close(outputStream, true); Closeables.close(inputStream, true); } catch (IOException e) { /* wont throw. */ } }
From source file:org.locationtech.geogig.rocksdb.RocksdbObjectDatabase.java
@Override public synchronized void close() { if (!isOpen()) { return;//from ww w . j a v a 2 s. c o m } try { super.close(); } finally { RocksdbBlobStore blobs = this.blobs; RocksdbGraphDatabase graph = this.graph; this.blobs = null; this.graph = null; try { Closeables.close(blobs, true); Closeables.close(graph, true); } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:edu.rosehulman.TFPartialVectorReducer.java
@Override protected void reduce(Text key, Iterable<StringTuple> values, Context context) throws IOException, InterruptedException { Iterator<StringTuple> it = values.iterator(); if (!it.hasNext()) { return;/* w w w. ja v a2s .c o m*/ } StringTuple value = it.next(); Vector vector = new RandomAccessSparseVector(dimension, value.length()); // guess at initial size if (maxNGramSize >= 2) { ShingleFilter sf = new ShingleFilter(new IteratorTokenStream(value.getEntries().iterator()), maxNGramSize); sf.reset(); try { do { String term = sf.getAttribute(CharTermAttribute.class).toString(); if (!term.isEmpty() && dictionary.containsKey(term)) { // ngram int termId = dictionary.get(term); vector.setQuick(termId, vector.getQuick(termId) + 1); } } while (sf.incrementToken()); sf.end(); } finally { Closeables.close(sf, true); } } else { for (String term : value.getEntries()) { if (!term.isEmpty() && dictionary.containsKey(term)) { // unigram int termId = dictionary.get(term); vector.setQuick(termId, vector.getQuick(termId) + 1); } } } if (sequentialAccess) { vector = new SequentialAccessSparseVector(vector); } if (namedVector) { vector = new NamedVector(vector, key.toString()); } // if the vector has no nonZero entries (nothing in the dictionary), let's not waste space sending it to disk. if (vector.getNumNondefaultElements() > 0) { VectorWritable vectorWritable = new VectorWritable(vector); context.write(key, vectorWritable); } else { context.getCounter("TFPartialVectorReducer", "emptyVectorCount").increment(1); } }