List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:interactivespaces.service.audio.player.internal.jlayer.JLayerAudioTrackPlayer.java
@Override public synchronized void start(final FilePlayableAudioTrack track) { if (playing.get()) { throw new SimpleInteractiveSpacesException( (String.format("Cannot start playing audio file %s: Already playing a track", track.getFile().getAbsolutePath()))); }/*from w w w . j a va 2s. c om*/ File file = track.getFile(); if (!file.exists()) { throw new SimpleInteractiveSpacesException( (String.format("Cannot find audio file %s", file.getAbsolutePath()))); } try { final FileInputStream trackStream = new FileInputStream(file); player = new AdvancedPlayer(trackStream); player.setPlayBackListener(new PlaybackListener() { @Override public void playbackFinished(PlaybackEvent event) { playing.set(false); notifyTrackStop(track); } @Override public void playbackStarted(PlaybackEvent event) { playing.set(true); notifyTrackStart(track); } }); // The JLayer play() method runs entirely in the calling thread, // which means it blocks until the song is complete. So run in its own // thread. executorService.submit(new Runnable() { @Override public void run() { try { player.play(); } catch (JavaLayerException e) { log.error("JLayer player failed during MP3 playback", e); } finally { Closeables.closeQuietly(trackStream); } } }); } catch (Exception e) { throw new InteractiveSpacesException( (String.format("Cannot create audio player for file %s", file.getAbsolutePath())), e); } }
From source file:com.endpoint.lg.evdev.reader.EvdevReaderLoop.java
/** * Tears down the thread's file handles. */ @Override protected void cleanup() { Closeables.closeQuietly(deviceChannel); Closeables.closeQuietly(deviceStream); }
From source file:io.smartspaces.service.audio.player.internal.jlayer.JLayerAudioTrackPlayer.java
@Override public synchronized void start(final FilePlayableAudioTrack track) { if (playing.get()) { throw new SimpleSmartSpacesException( (String.format("Cannot start playing audio file %s: Already playing a track", track.getFile().getAbsolutePath()))); }/*from w w w. ja v a 2 s . c o m*/ File file = track.getFile(); if (!file.exists()) { throw new SimpleSmartSpacesException( (String.format("Cannot find audio file %s", file.getAbsolutePath()))); } try { final FileInputStream trackStream = new FileInputStream(file); player = new AdvancedPlayer(trackStream); player.setPlayBackListener(new PlaybackListener() { @Override public void playbackFinished(PlaybackEvent event) { playing.set(false); notifyTrackStop(track); } @Override public void playbackStarted(PlaybackEvent event) { playing.set(true); notifyTrackStart(track); } }); // The JLayer play() method runs entirely in the calling thread, // which means it blocks until the song is complete. So run in its own // thread. executorService.submit(new Runnable() { @Override public void run() { try { player.play(); } catch (JavaLayerException e) { log.error("JLayer player failed during MP3 playback", e); } finally { Closeables.closeQuietly(trackStream); } } }); } catch (Exception e) { throw new SmartSpacesException( (String.format("Cannot create audio player for file %s", file.getAbsolutePath())), e); } }
From source file:com.netflix.astyanax.test.EmbeddedCassandra.java
public EmbeddedCassandra(File dataDir, String clusterName, int port, int storagePort) throws IOException { LOG.info("Starting cassandra in dir " + dataDir); this.dataDir = dataDir; dataDir.mkdirs();//from ww w. j a v a2 s. c o m InputStream is = null; try { URL templateUrl = EmbeddedCassandra.class.getClassLoader().getResource("cassandra-template.yaml"); Preconditions.checkNotNull(templateUrl, "Cassandra config template is null"); String baseFile = Resources.toString(templateUrl, Charset.defaultCharset()); String newFile = baseFile.replace("$DIR$", dataDir.getPath()); newFile = newFile.replace("$PORT$", Integer.toString(port)); newFile = newFile.replace("$STORAGE_PORT$", Integer.toString(storagePort)); newFile = newFile.replace("$CLUSTER$", clusterName); File configFile = new File(dataDir, "cassandra.yaml"); Files.write(newFile, configFile, Charset.defaultCharset()); LOG.info("Cassandra config file: " + configFile.getPath()); System.setProperty("cassandra.config", "file:" + configFile.getPath()); try { cassandra = new CassandraDaemon(); cassandra.init(null); } catch (IOException e) { LOG.error("Error initializing embedded cassandra", e); throw e; } } finally { Closeables.closeQuietly(is); } LOG.info("Started cassandra deamon"); }
From source file:com.netflix.curator.x.discovery.details.ServiceDiscoveryImpl.java
@Override public void close() throws IOException { for (ServiceCache<T> cache : Lists.newArrayList(caches)) { Closeables.closeQuietly(cache); }/*www .ja va 2 s . co m*/ for (ServiceProvider<T> provider : Lists.newArrayList(providers)) { Closeables.closeQuietly(provider); } if (thisInstance.isPresent()) { try { unregisterService(thisInstance.get()); } catch (Exception e) { log.error("Could not unregister this instance", e); } } }
From source file:org.b1.pack.standard.writer.VolumeWriter.java
public void cleanup() { Closeables.closeQuietly(outputStream); }
From source file:com.nesscomputing.httpserver.log.file.FileRequestLog.java
@Override public void doStop() { final PrintWriter requestLogWriter = requestLogWriterHolder.getAndSet(null); if (requestLogWriter != null) { LOG.info("Closing request log \"%s\"", requestLogFile.getAbsolutePath()); Closeables.closeQuietly(requestLogWriter); }/* w ww . ja v a2 s .com*/ }
From source file:eu.redzoo.article.planetcassandra.reactive.EmbeddedCassandra.java
@SuppressWarnings("unchecked") protected static int prepare() throws IOException { String cassandraDirName = "target" + File.separator + "cassandra-junit-" + new Random().nextInt(1000000); File cassandraDir = new File(cassandraDirName); if (!cassandraDir.exists()) { boolean isCreated = cassandraDir.mkdirs(); if (!isCreated) { throw new RuntimeException("could not create cassandra dir " + cassandraDir.getAbsolutePath()); }//from w w w. ja v a2s. c o m } InputStream cassandraConfigurationInput = null; Writer cassandraConfigurationOutput = null; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); cassandraConfigurationInput = loader.getResourceAsStream(CASSANDRA_YAML_FILE); Yaml yaml = new Yaml(); Map<String, Object> cassandraConfiguration = (Map<String, Object>) yaml .load(cassandraConfigurationInput); int rpcPort = findUnusedLocalPort(); if (rpcPort == -1) { throw new RuntimeException("Can not start embedded cassandra: no unused local port found!"); } cassandraConfiguration.put("rpc_port", rpcPort); int storagePort = findUnusedLocalPort(); if (storagePort == -1) { throw new RuntimeException("Can not start embedded cassandra: no unused local port found!"); } cassandraConfiguration.put("storage_port", storagePort); int nativeTransportPort = findUnusedLocalPort(); if (nativeTransportPort == -1) { throw new RuntimeException("Can not start embedded cassandra: no unused local port found!"); } cassandraConfiguration.put("native_transport_port", nativeTransportPort); cassandraConfiguration.put("start_native_transport", "true"); cassandraConfigurationOutput = new OutputStreamWriter( new FileOutputStream(cassandraDirName + File.separator + CASSANDRA_YAML_FILE), Charsets.UTF_8); yaml.dump(cassandraConfiguration, cassandraConfigurationOutput); System.setProperty("cassandra.config", new File(cassandraDirName, CASSANDRA_YAML_FILE).toURI().toString()); System.setProperty("cassandra-foreground", "true"); DatabaseDescriptor.createAllDirectories(); return nativeTransportPort; } finally { Closeables.closeQuietly(cassandraConfigurationInput); Closeables.close(cassandraConfigurationOutput, true); } }
From source file:com.metamx.druid.GroupByQueryEngine.java
public Sequence<Row> process(final GroupByQuery query, StorageAdapter storageAdapter) { final List<Interval> intervals = query.getQuerySegmentSpec().getIntervals(); if (intervals.size() != 1) { throw new IAE("Should only have one interval, got[%s]", intervals); }/*from ww w. j ava 2s . com*/ final Iterable<Cursor> cursors = storageAdapter.makeCursors( Filters.convertDimensionFilters(query.getDimFilter()), intervals.get(0), query.getGranularity()); final ResourceHolder<ByteBuffer> bufferHolder = intermediateResultsBufferPool.take(); return new BaseSequence<Row, Iterator<Row>>(new BaseSequence.IteratorMaker<Row, Iterator<Row>>() { @Override public Iterator<Row> make() { return FunctionalIterator.create(cursors.iterator()) .transformCat(new Function<Cursor, Iterator<Row>>() { @Override public Iterator<Row> apply(@Nullable final Cursor cursor) { return new RowIterator(query, cursor, bufferHolder.get()); } }); } @Override public void cleanup(Iterator<Row> iterFromMake) { Closeables.closeQuietly(bufferHolder); } }); }
From source file:com.metamx.druid.index.v1.CompressedLongsIndexedSupplier.java
@Override public IndexedLongs get() { return new IndexedLongs() { int currIndex = -1; ResourceHolder<LongBuffer> holder; LongBuffer buffer;// ww w .j av a2 s. co m @Override public int size() { return totalSize; } @Override public long get(int index) { int bufferNum = index / sizePer; int bufferIndex = index % sizePer; if (bufferNum != currIndex) { loadBuffer(bufferNum); } return buffer.get(buffer.position() + bufferIndex); } @Override public void fill(int index, long[] toFill) { if (totalSize - index < toFill.length) { throw new IndexOutOfBoundsException( String.format("Cannot fill array of size[%,d] at index[%,d]. Max size[%,d]", toFill.length, index, totalSize)); } int bufferNum = index / sizePer; int bufferIndex = index % sizePer; int leftToFill = toFill.length; while (leftToFill > 0) { if (bufferNum != currIndex) { loadBuffer(bufferNum); } buffer.mark(); buffer.position(buffer.position() + bufferIndex); final int numToGet = Math.min(buffer.remaining(), leftToFill); buffer.get(toFill, toFill.length - leftToFill, numToGet); buffer.reset(); leftToFill -= numToGet; ++bufferNum; bufferIndex = 0; } } private void loadBuffer(int bufferNum) { Closeables.closeQuietly(holder); holder = baseLongBuffers.get(bufferNum); buffer = holder.get(); currIndex = bufferNum; } @Override public int binarySearch(long key) { throw new UnsupportedOperationException(); } @Override public int binarySearch(long key, int from, int to) { throw new UnsupportedOperationException(); } @Override public String toString() { return "CompressedLongsIndexedSupplier_Anonymous{" + "currIndex=" + currIndex + ", sizePer=" + sizePer + ", numChunks=" + baseLongBuffers.size() + ", totalSize=" + totalSize + '}'; } @Override public void close() throws IOException { Closeables.close(holder, false); } }; }