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:eu.interedition.web.metadata.DublinCoreMetadata.java
public DublinCoreMetadata update(Text source) throws IOException, XMLStreamException { if (source.getType() != Text.Type.XML) { return this; }//from ww w . jav a 2s. c o m Reader textReader = null; XMLStreamReader xmlReader = null; try { textReader = source.read().getInput(); xmlReader = XML.createXMLInputFactory().createXMLStreamReader(textReader); boolean inTitleStmt = false; StringBuilder textContent = null; String localName; while (xmlReader.hasNext()) { switch (xmlReader.next()) { case XMLStreamReader.START_ELEMENT: localName = xmlReader.getLocalName(); if ("titleStmt".equals(localName)) { inTitleStmt = true; } else if (inTitleStmt && "title".equals(localName)) { textContent = new StringBuilder(); } else if (inTitleStmt && "author".equals(localName)) { textContent = new StringBuilder(); } break; case XMLStreamReader.END_ELEMENT: localName = xmlReader.getLocalName(); if ("titleStmt".equals(localName)) { return this; } else if (inTitleStmt && "title".equals(localName)) { title = textContent.toString().replaceAll("\\s+", " "); textContent = null; } else if (inTitleStmt && "author".equals(localName)) { creator = textContent.toString().replaceAll("\\s+", " "); textContent = null; } break; case XMLStreamReader.CHARACTERS: case XMLStreamReader.CDATA: if (textContent != null) { textContent.append(xmlReader.getText()); } } } return this; } finally { XML.closeQuietly(xmlReader); Closeables.close(textReader, false); } }
From source file:org.plista.kornakapi.core.training.SemanticModel.java
/** * method to load model from squence file * @throws IOException/* ww w.j av a 2 s . com*/ */ public void read() throws IOException { Path indexPath = path.suffix("/indexItem.model"); if (fs.exists(indexPath)) { indexItem = new HashMap<Integer, String>(); Reader reader = new SequenceFile.Reader(fs, indexPath, lconf); IntWritable key = new IntWritable(); Text val = new Text(); while (reader.next(key, val)) { indexItem.put(key.get(), val.toString()); } Closeables.close(reader, false); } Path itemIndexPath = path.suffix("/itemIndex.model"); if (fs.exists(itemIndexPath)) { itemIndex = new HashMap<String, Integer>(); Reader reader = new SequenceFile.Reader(fs, itemIndexPath, lconf); IntWritable val = new IntWritable(); Text key = new Text(); while (reader.next(key, val)) { itemIndex.put(key.toString(), val.get()); } Closeables.close(reader, false); } Path featurePath = path.suffix("/itemFeature.model"); if (fs.exists(featurePath)) { Reader reader = new SequenceFile.Reader(fs, featurePath, lconf); itemFeatures = new HashMap<String, Vector>(); Text key = new Text(); VectorWritable val = new VectorWritable(); while (reader.next(key, val)) { itemFeatures.put(key.toString(), val.get()); } Closeables.close(reader, false); } if (log.isInfoEnabled()) { log.info("LDA Model Read"); } }
From source file:org.apache.mahout.math.hadoop.stochasticsvd.qr.QRFirstStep.java
protected void cleanup() throws IOException { try {/*from w w w.j a va 2 s.co m*/ if (qSolver == null && yLookahead.isEmpty()) { return; } if (qSolver == null) { qSolver = new GivensThinSolver(yLookahead.size(), kp); } // grow q solver up if necessary qSolver.adjust(qSolver.getCnt() + yLookahead.size()); while (!yLookahead.isEmpty()) { qSolver.appendRow(yLookahead.remove(0)); } assert qSolver.isFull(); if (++blockCnt > 1) { flushSolver(); assert tempQw != null; closeables.remove(tempQw); Closeables.close(tempQw, false); } flushQBlocks(); } finally { IOUtils.close(closeables); } }
From source file:net.yanrc.xpring.activity.component.config.ZooKeeperConfigurationSource.java
public void close() { try {// ww w . j a v a 2s . co m Closeables.close(pathChildrenCache, true); } catch (IOException exc) { logger.error("IOException should not have been thrown.", exc); } }
From source file:org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore.java
@Override public String writeBlob(InputStream stream) throws IOException { boolean threw = true; try {/*from ww w .j a v a 2 s. c o m*/ long start = System.nanoTime(); checkNotNull(stream); DataRecord dr = writeStream(stream); String id = getBlobId(dr); threw = false; stats.uploaded(System.nanoTime() - start, TimeUnit.NANOSECONDS, dr.getLength()); stats.uploadCompleted(id); return id; } catch (DataStoreException e) { throw new IOException(e); } finally { //DataStore does not closes the stream internally //So close the stream explicitly Closeables.close(stream, threw); } }
From source file:eu.interedition.text.rdbms.RelationalTextRepository.java
@Override public Text concat(Iterable<Text> texts) throws IOException { final FileBackedOutputStream buf = createBuffer(); final OutputStreamWriter bufWriter = new OutputStreamWriter(buf, Text.CHARSET); try {//from ww w .j a v a2 s .co m for (Text text : texts) { read(new ReaderCallback<Void>(text) { @Override protected Void read(Clob content) throws SQLException, IOException { Reader reader = null; try { CharStreams.copy(reader = content.getCharacterStream(), bufWriter); } finally { Closeables.close(reader, false); } return null; } }); } } finally { Closeables.close(bufWriter, false); } Reader reader = null; try { return create(reader = new InputStreamReader(buf.getSupplier().getInput(), Text.CHARSET)); } finally { Closeables.closeQuietly(reader); buf.reset(); } }
From source file:net.sourceforge.vaticanfetcher.model.search.Searcher.java
/** Updates the cached indexes and replaces the current Lucene searcher with a new one. */ @ThreadSafe/*from w ww. j a va2 s . c o m*/ @VisibleForPackageGroup public void replaceLuceneSearcher() { writeLock.lock(); try { Closeables.close(luceneSearcher, false); setLuceneSearcher(indexRegistry.getIndexes()); } catch (IOException e) { ioException = e; // Will be thrown later } finally { writeLock.unlock(); } }
From source file:org.jclouds.examples.rackspace.DeleteAll.java
private void deleteCloudServers() throws IOException { NovaApi novaApi = ContextBuilder.newBuilder(System.getProperty("provider.cs", "rackspace-cloudservers-us")) .credentials(username, apiKey).buildApi(NovaApi.class); for (String region : novaApi.getConfiguredRegions()) { try {/*w w w. j a v a 2 s .c o m*/ System.out.format("Delete Key Pairs in %s%n", region); KeyPairApi keyPairApi = novaApi.getKeyPairApi(region).get(); for (KeyPair keyPair : keyPairApi.list()) { System.out.format(" %s%n", keyPair.getName()); keyPairApi.delete(keyPair.getName()); } System.out.format("Delete Servers in %s%n", region); VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentApi(region).get(); ServerApi serverApi = novaApi.getServerApi(region); for (Server server : serverApi.listInDetail().concat().toList()) { for (VolumeAttachment volumeAttachment : volumeAttachmentApi .listAttachmentsOnServer(server.getId())) { volumeAttachmentApi.detachVolumeFromServer(volumeAttachment.getId(), server.getId()); } System.out.format(" %s%n", server.getName()); serverApi.delete(server.getId()); } } catch (Exception e) { e.printStackTrace(); } } Closeables.close(novaApi, true); }
From source file:org.apache.mahout.classifier.df.data.Dataset.java
/** * Loads the dataset from a file//from ww w . j a va 2 s . co m * * @throws java.io.IOException */ public static Dataset load(Configuration conf, Path path) throws IOException { FileSystem fs = path.getFileSystem(conf); long bytesToRead = fs.getFileStatus(path).getLen(); byte[] buff = new byte[Long.valueOf(bytesToRead).intValue()]; FSDataInputStream input = fs.open(path); try { input.readFully(buff); } finally { Closeables.close(input, true); } String json = new String(buff, Charset.defaultCharset()); return fromJSON(json); }
From source file:com.minecave.pickaxes.util.nbt.EPNbtFactory.java
/** * Save the content of a NBT compound to a stream. * <p/>/*w ww . j av a 2 s . co m*/ * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. * * @param source - the NBT compound to save. * @param stream - the stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ public static void saveStream(NbtCompound source, OutputSupplier<? extends OutputStream> stream, StreamOptions option) throws IOException { OutputStream output = null; DataOutputStream data = null; boolean suppress = true; try { output = stream.getOutput(); data = new DataOutputStream( option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); suppress = false; } finally { if (data != null) Closeables.close(data, suppress); else if (output != null) Closeables.close(output, suppress); } }