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.apache.mahout.driver.MahoutDriver.java
private static Properties loadProperties(String resource) throws IOException { InputStream propsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (propsStream != null) { try {/*from w w w . j a va2 s . c om*/ Properties properties = new Properties(); properties.load(propsStream); return properties; } finally { Closeables.close(propsStream, true); } } return null; }
From source file:com.axmor.eclipse.typescript.core.internal.TypeScriptBridge.java
/** * Stops engine and corresponding console, destroy undelie NodeJS process. */// w w w. j av a 2 s . c o m public synchronized void stop() { if (!stopped) { stopped = true; transport.close(); outStream.println("TS bridge closed"); try { Closeables.close(outStream, true); Closeables.close(errorStream, true); } catch (IOException e) { // ignore exception } p.destroy(); } }
From source file:org.eclipse.andmore.integration.tests.SdkTestCase.java
@SuppressWarnings("resource") protected String readTestFile(String relativePath, boolean expectExists) throws IOException { InputStream stream = getTestResource(relativePath, expectExists); if (expectExists) { assertNotNull(relativePath + " does not exist", stream); } else if (stream == null) { return null; }/*from w ww. ja va2 s. co m*/ String xml = new String(ByteStreams.toByteArray(stream), Charsets.UTF_8); try { Closeables.close(stream, true /* swallowIOException */); } catch (IOException e) { // cannot happen } assertTrue(xml.length() > 0); // Remove any references to the project name such that we are isolated // from // that in golden file. // Appears in strings.xml etc. xml = removeSessionData(xml); return xml; }
From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java
private byte[] makeJar(VirtualFile[] files) throws IOException { JarOutputStream jarOS = null; ByteArrayOutputStream byteOS = null; try {/*from w w w.ja v a 2 s . com*/ progressIndicator.setIndeterminate(true); // build list of files to process Collection<VirtualFile> filesToProcess = new LinkedHashSet<VirtualFile>(); for (VirtualFile virtualFile : files) { filesToProcess.addAll(getFileList(virtualFile)); } progressIndicator.setIndeterminate(false); progressIndicator.setFraction(0.0D); totalCount = filesToProcess.size(); byteOS = new ByteArrayOutputStream(); jarOS = new JarOutputStream(byteOS); int counter = 0; for (VirtualFile file : filesToProcess) { if (progressIndicator.isCanceled()) { break; } counter++; progressIndicator.setFraction((double) counter / (double) totalCount * 0.5D); progressIndicator.setText("Adding " + file.getName() + " ..."); if (canImport(file)) { LOGGER.info("Adding file " + (counter + 1) + "/" + totalCount); addToJar(jarOS, file); } else { skippedCount++; } } jarOS.flush(); return progressIndicator.isCanceled() ? null : byteOS.toByteArray(); } finally { Closeables.close(jarOS, true); Closeables.close(byteOS, true); } }
From source file:com.comphenix.protocol.wrappers.nbt.NbtFactory.java
/** * Save a NBT compound to a new compressed file, overwriting any existing files in the process. * @param compound - the compound to save. * @param file - the destination file./*from w w w .ja v a 2 s . com*/ * @throws IOException Unable to save compound. */ public static void toFile(NbtCompound compound, String file) throws IOException { Preconditions.checkNotNull(compound, "compound cannot be NULL"); Preconditions.checkNotNull(file, "file cannot be NULL"); FileOutputStream stream = null; DataOutputStream output = null; boolean swallow = true; try { stream = new FileOutputStream(file); NbtBinarySerializer.DEFAULT.serialize(compound, output = new DataOutputStream(new GZIPOutputStream(stream))); swallow = false; } finally { // Note the order if (output != null) Closeables.close(output, swallow); else if (stream != null) Closeables.close(stream, swallow); } }
From source file:org.plista.kornakapi.core.training.SemanticModel.java
/** * Key is set to handle concurent writes from DocumentTopicInferenceTrainer and LDATrainer * @throws IOException/*from w ww . ja va 2s. c om*/ */ private void writeKey(String key) throws IOException { Path keyPath = path.suffix("/key.txt"); Writer w = SequenceFile.createWriter(fs, lconf, keyPath, IntWritable.class, Text.class); IntWritable id = new IntWritable(); Text val = new Text(); id.set(1); val.set(key); w.append(id, val); Closeables.close(w, false); }
From source file:org.calrissian.mango.collect.CloseableIterators.java
/** * Combines multiple closeable iterators into a single closeable iterator. The returned * closeable iterator iterates across the elements of each closeable iterator in {@code inputs}. * The input iterators are not polled until necessary. * * As each closeable iterator is exhausted, it is closed before moving onto the next closeable * iterator. A call to close on the returned closeable iterator will quietly close all of * the closeable iterators in {@code inputs} which have not been exhausted. */// w w w.java2 s . com public static <T> CloseableIterator<T> chain( final Iterator<? extends CloseableIterator<? extends T>> iterator) { checkNotNull(iterator); return new CloseableIterator<T>() { CloseableIterator<? extends T> curr = emptyIterator(); @Override public void closeQuietly() { try { Closeables.close(this, true); } catch (IOException e) { // IOException should not have been thrown } } @Override public void close() throws IOException { //Close the current one then close all the others if (curr != null) curr.closeQuietly(); while (iterator.hasNext()) iterator.next().closeQuietly(); } @Override public boolean hasNext() { //autoclose will close when the iterator is exhausted while (!curr.hasNext() && iterator.hasNext()) curr = autoClose(iterator.next()); return curr.hasNext(); } @Override public T next() { if (hasNext()) return curr.next(); throw new NoSuchElementException(); } @Override public void remove() { curr.remove(); } }; }
From source file:com.b2international.snowowl.snomed.importer.rf2.validation.AbstractSnomedValidator.java
/** * Performs any one-time initialization necessary for the validation. * //from ww w.java2s . c om * @param monitor the SubMonitor instance to report progress on * @return the seen effective times */ protected Collection<String> preValidate(final SubMonitor monitor) { monitor.beginTask(MessageFormat.format("Preparing {0}s validation", importType.getDisplayName()), 1); final Map<String, CsvListWriter> writers = newHashMap(); final Closer closer = Closer.create(); try { final InputStreamReader releaseFileReader = closer .register(new InputStreamReader(releaseUrl.openStream(), CsvConstants.IHTSDO_CHARSET)); final CsvListReader releaseFileListReader = closer .register(new CsvListReader(releaseFileReader, CsvConstants.IHTSDO_CSV_PREFERENCE)); componentStagingDirectory = createStagingDirectory(); final String[] header = releaseFileListReader.getCSVHeader(true); if (!StringUtils.equalsIgnoreCase(header, expectedHeader)) { addDefect(DefectType.HEADER_DIFFERENCES, String.format("Invalid header in '%s'", releaseFileName)); } while (true) { final List<String> row = releaseFileListReader.read(); if (null == row) { break; } final String effectiveTimeKey = getEffectiveTimeKey(row.get(1)); if (!effectiveTimes.contains(effectiveTimeKey)) { effectiveTimes.add(effectiveTimeKey); // Use the original effective time field instead of the key validateEffectiveTime(row.get(1), releaseFileListReader.getLineNumber()); final Path effectiveTimeFile = getEffectiveTimeFile(effectiveTimeKey); final BufferedWriter bw = closer.register( Files.newBufferedWriter(effectiveTimeFile, Charsets.UTF_8, StandardOpenOption.CREATE)); final CsvListWriter lw = closer .register(new CsvListWriter(bw, CsvConstants.IHTSDO_CSV_PREFERENCE)); writers.put(effectiveTimeKey, lw); } writers.get(effectiveTimeKey).write(row); } return ImmutableList.copyOf(effectiveTimes); } catch (final IOException e) { throw new ImportException( MessageFormat.format("Couldn''t read row from {0} release file.", releaseFileName), e); } finally { try { Closeables.close(closer, true); } catch (IOException e) { throw new RuntimeException(e); } monitor.worked(1); } }
From source file:com.bendb.thrifty.schema.Loader.java
private ThriftFileElement loadSingleFile(File base, String path) throws IOException { File file = new File(base, path).getAbsoluteFile(); if (!file.exists()) { return null; }//from w ww .j a va 2 s. c o m Source source = Okio.source(file); try { Location location = Location.get(base.toString(), path); String data = Okio.buffer(source).readUtf8(); return ThriftParser.parse(location, data); } catch (IOException e) { throw new IOException("Failed to load " + path + " from " + base, e); } finally { Closeables.close(source, true); } }
From source file:org.apache.mahout.math.hadoop.stochasticsvd.SSVDHelper.java
/** * @return sum of all vectors in different files specified by glob */// ww w. j a v a 2s . co m public static Vector loadAndSumUpVectors(Path glob, Configuration conf) throws IOException { SequenceFileDirValueIterator<VectorWritable> iter = new SequenceFileDirValueIterator<VectorWritable>(glob, PathType.GLOB, null, PARTITION_COMPARATOR, true, conf); try { Vector v = null; while (iter.hasNext()) { if (v == null) { v = new DenseVector(iter.next().get()); } else { v.assign(iter.next().get(), Functions.PLUS); } } return v; } finally { Closeables.close(iter, true); } }