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:com.oculusinfo.tile.CacheConfigModule.java
@Override protected void configureServlets() { // Read the ehCache property from web.xml or override-web.xml String filename = context.getInitParameter("ehcacheConfig"); try {//from w ww . j av a2 s . co m logger.info("Loading ehcache configuration:"); // Load properties InputStream inp = ResourceHelper.getStreamForPath(filename, "res:///ehcache.xml"); // Create cache manager with provided configuration CacheManager.create(inp); Closeables.close(inp, false); } catch (IOException e) { // Failed to load properties, error addError(e); } // Filter all REST calls filter("/rest/*").through(CustomPageCachingFilter.class); }
From source file:org.jclouds.examples.rackspace.cloudfiles.UploadLargeObject.java
/** * Always close your service when you're done with it. */ public void close() throws IOException { Closeables.close(blobStore.getContext(), true); }
From source file:eu.interedition.text.rdbms.RelationalTextRepository.java
public Text write(Text text, Reader content) throws IOException { final FileBackedOutputStream buf = createBuffer(); CountingWriter tempWriter = null;/*from ww w . j a va2s. co m*/ try { CharStreams.copy(content, tempWriter = new CountingWriter(new OutputStreamWriter(buf, Text.CHARSET))); } finally { Closeables.close(tempWriter, false); } Reader bufReader = null; try { return write(text, bufReader = new InputStreamReader(buf.getSupplier().getInput(), Text.CHARSET), tempWriter.length); } finally { Closeables.close(bufReader, false); } }
From source file:org.semanticweb.owlapi.io.XZFileDocumentTarget.java
@Override public void close() throws Exception { OutputStream toReturn = outputStream; outputStream = null; Closeables.close(toReturn, false); }
From source file:org.apache.tephra.persist.LocalFileTransactionStateStorage.java
@Override public void writeSnapshot(TransactionSnapshot snapshot) throws IOException { // save the snapshot to a temporary file File snapshotTmpFile = new File(snapshotDir, TMP_SNAPSHOT_FILE_PREFIX + snapshot.getTimestamp()); LOG.debug("Writing snapshot to temporary file {}", snapshotTmpFile); OutputStream out = Files.newOutputStreamSupplier(snapshotTmpFile).getOutput(); boolean threw = true; try {//from w ww. j av a2 s. c o m codecProvider.encode(out, snapshot); threw = false; } finally { Closeables.close(out, threw); } // move the temporary file into place with the correct filename File finalFile = new File(snapshotDir, SNAPSHOT_FILE_PREFIX + snapshot.getTimestamp()); if (!snapshotTmpFile.renameTo(finalFile)) { throw new IOException("Failed renaming temporary snapshot file " + snapshotTmpFile.getName() + " to " + finalFile.getName()); } LOG.debug("Completed snapshot to file {}", finalFile); }
From source file:org.kitesdk.data.filesystem.FileSystemDatasetWriter.java
@Override public void close() { if (state.equals(ReaderWriterState.OPEN)) { logger.debug("Closing pathTmp:{}", pathTmp); try {// w ww .j a v a 2 s. co m Closeables.close(dataFileWriter, false); } catch (IOException e) { throw new DatasetWriterException( "Unable to close writer:" + dataFileWriter + " to path:" + pathTmp); } logger.debug("Committing pathTmp:{} to path:{}", pathTmp, path); try { if (!fileSystem.rename(pathTmp, path)) { throw new DatasetWriterException("Failed to move " + pathTmp + " to " + path); } } catch (IOException e) { throw new DatasetWriterException("Internal error while trying to commit path:" + pathTmp, e); } state = ReaderWriterState.CLOSED; } }
From source file:org.apache.parquet.cli.commands.ToAvroCommand.java
@Override @SuppressWarnings("unchecked") public int run() throws IOException { Preconditions.checkArgument(targets != null && targets.size() == 1, "A data file is required."); String source = targets.get(0); CodecFactory codecFactory = Codecs.avroCodec(compressionCodecName); Schema schema;/* w w w. java2 s. c o m*/ if (avroSchemaFile != null) { schema = Schemas.fromAvsc(open(avroSchemaFile)); } else { schema = getAvroSchema(source); } Schema projection = filterSchema(schema, columns); Path outPath = qualifiedPath(outputPath); FileSystem outFS = outPath.getFileSystem(getConf()); if (overwrite && outFS.exists(outPath)) { console.debug("Deleting output file {} (already exists)", outPath); outFS.delete(outPath); } Iterable<Record> reader = openDataFile(source, projection); boolean threw = true; long count = 0; try { DatumWriter<Record> datumWriter = new GenericDatumWriter<>(schema); DataFileWriter<Record> w = new DataFileWriter<>(datumWriter); w.setCodec(codecFactory); try (DataFileWriter<Record> writer = w.create(projection, create(outputPath))) { for (Record record : reader) { writer.append(record); count += 1; } } threw = false; } catch (RuntimeException e) { throw new RuntimeException("Failed on record " + count, e); } finally { if (reader instanceof Closeable) { Closeables.close((Closeable) reader, threw); } } return 0; }
From source file:com.turn.ttorrent.tracker.simple.SimpleTrackerService.java
/** * Handle the incoming request on the tracker service. * * <p>/*ww w .jav a2 s. co m*/ * This makes sure the request is made to the tracker's announce URL, and * delegates handling of the request to the <em>process()</em> method after * preparing the response object. * </p> * * @param request The incoming HTTP request. * @param response The response object. */ @Override public void handle(Request request, Response response) { // LOG.info("Request: " + request); try { // Reject non-announce requests if (!TrackerUtils.DEFAULT_ANNOUNCE_URL.equals(request.getPath().toString())) { metrics.requestRejected.mark(); response.setStatus(Status.NOT_FOUND); response.close(); return; } OutputStream body = null; try { body = response.getOutputStream(); this.process(request, response, body); body.flush(); } finally { Closeables.close(body, true); } } catch (Exception e) { LOG.warn("Error while handling request", e); return; } }
From source file:se.curity.examples.oauth.OAuthOpaqueFilter.java
@Override public void destroy() { try {//from w w w . j ava 2s. c o m Closeables.close(_opaqueTokenValidator, true); } catch (IOException e) { _logger.warn("Problem closing jwk client", e); } }
From source file:com.ml.ira.algos.LogisticModelParameters.java
/** * Reads a model from a file./* w w w .j a va 2s.c o m*/ * @throws java.io.IOException If there is an error opening or closing the file. */ public static LogisticModelParameters loadFrom(File in) throws IOException { InputStream input = new FileInputStream(in); try { return loadFrom(input); } finally { Closeables.close(input, true); } }