java.io.Closeable

Here are the examples of the java api class java.io.Closeable taken from open source projects.

1. StructuralTest#canStructurallyCast()

Project: totallylazy
File: StructuralTest.java
@Test
public void canStructurallyCast() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Object closeable = new Object() {

        void close() {
            called.set(true);
        }
    };
    Closeable close = Structural.cast(Closeable.class, closeable);
    close.close();
    assertThat(called.get(), is(true));
}

2. InternalUtilsTest#close_ignores_exceptions()

Project: tapestry5
File: InternalUtilsTest.java
@Test
public void close_ignores_exceptions() throws Exception {
    Closeable c = newMock(Closeable.class);
    c.close();
    setThrowable(new IOException());
    replay();
    InternalUtils.close(c);
    verify();
}

3. InternalUtilsTest#close_success()

Project: tapestry5
File: InternalUtilsTest.java
@Test
public void close_success() throws Exception {
    Closeable c = newMock(Closeable.class);
    c.close();
    replay();
    InternalUtils.close(c);
    verify();
}

4. MockIndexOutputWrapper#close()

Project: lucene-solr
File: MockIndexOutputWrapper.java
@Override
public void close() throws IOException {
    if (closed) {
        // don't mask double-close bugs
        delegate.close();
        return;
    }
    closed = true;
    try (Closeable delegate = this.delegate) {
        assert delegate != null;
        dir.maybeThrowDeterministicException();
    } finally {
        dir.removeIndexOutput(this, name);
        if (dir.trackDiskUsage) {
            // Now compute actual disk usage & track the maxUsedSize
            // in the MockDirectoryWrapper:
            long size = dir.getRecomputedActualSizeInBytes();
            if (size > dir.maxUsedSize) {
                dir.maxUsedSize = size;
            }
        }
    }
}

5. MockIndexInputWrapper#close()

Project: lucene-solr
File: MockIndexInputWrapper.java
@Override
public void close() throws IOException {
    if (closed) {
        // don't mask double-close bugs
        delegate.close();
        return;
    }
    closed = true;
    try (Closeable delegate = this.delegate) {
        // all clones get closed:
        assert delegate != null;
        if (!isClone) {
            dir.removeIndexInput(this, name);
        }
        dir.maybeThrowDeterministicException();
    }
}

6. MockDirectoryWrapper#crash()

Project: lucene-solr
File: MockDirectoryWrapper.java
/** Simulates a crash of OS or machine by overwriting
   *  unsynced files. */
public synchronized void crash() throws IOException {
    openFiles = new HashMap<>();
    openFilesForWrite = new HashSet<>();
    openFilesDeleted = new HashSet<>();
    // first force-close all files, so we can corrupt on windows etc.
    // clone the file map, as these guys want to remove themselves on close.
    Map<Closeable, Exception> m = new IdentityHashMap<>(openFileHandles);
    for (Closeable f : m.keySet()) {
        try {
            f.close();
        } catch (Exception ignored) {
        }
    }
    corruptFiles(unSyncedFiles);
    crashed = true;
    unSyncedFiles = new HashSet<>();
}

7. IOUtils#close()

Project: lucene-solr
File: IOUtils.java
/**
   * Closes all given <tt>Closeable</tt>s.
   * @see #close(Closeable...)
   */
public static void close(Iterable<? extends Closeable> objects) throws IOException {
    Throwable th = null;
    for (Closeable object : objects) {
        try {
            if (object != null) {
                object.close();
            }
        } catch (Throwable t) {
            addSuppressed(th, t);
            if (th == null) {
                th = t;
            }
        }
    }
    reThrow(th);
}

8. IOUtils#cleanup()

Project: zookeeper
File: IOUtils.java
/**
     * Close the Closeable objects and <b>ignore</b> any {@link IOException} or
     * null pointers. Must only be used for cleanup in exception handlers.
     * 
     * @param log
     *            the log to record problems to at debug level. Can be null.
     * @param closeables
     *            the objects to close
     */
public static void cleanup(Logger log, Closeable... closeables) {
    for (Closeable c : closeables) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                if (log != null) {
                    log.warn("Exception in closing " + c, e);
                }
            }
        }
    }
}

9. VoldemortBuildAndPushJob#cleanUp()

Project: voldemort
File: VoldemortBuildAndPushJob.java
private void cleanUp() {
    if (heartBeatHookFuture != null) {
        heartBeatHookFuture.cancel(true);
    }
    for (Closeable closeable : this.closeables) {
        try {
            log.info("Closing " + closeable.toString());
            closeable.close();
        } catch (Exception e) {
            log.error("Got an error while trying to close " + closeable.toString(), e);
        }
    }
    this.executorService.shutdownNow();
}

10. Utils#bestEffortclose()

Project: TomP2P
File: Utils.java
public static void bestEffortclose(Closeable... closables) {
    // best effort close;
    for (Closeable closable : closables) {
        if (closable != null) {
            try {
                closable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

11. ShuffleUtils#ioCleanup()

Project: tez
File: ShuffleUtils.java
public static void ioCleanup(Closeable... closeables) {
    for (Closeable c : closeables) {
        if (c == null)
            continue;
        try {
            c.close();
        } catch (IOException e) {
            if (LOG.isDebugEnabled())
                LOG.debug("Exception in closing " + c, e);
        }
    }
}

12. FileUtils#close()

Project: stratio-cassandra
File: FileUtils.java
public static void close(Iterable<? extends Closeable> cs) throws IOException {
    IOException e = null;
    for (Closeable c : cs) {
        try {
            if (c != null)
                c.close();
        } catch (IOException ex) {
            e = ex;
            logger.warn("Failed closing stream {}", c, ex);
        }
    }
    if (e != null)
        throw e;
}

13. CorePlugin#onShutDown()

Project: stagemonitor
File: CorePlugin.java
@Override
public void onShutDown() {
    if (aggregationReporter != null) {
        logger.info("\n####################################################\n" + "## Aggregated report for this measurement session ##\n" + "####################################################\n");
        aggregationReporter.onShutDown();
    }
    for (Closeable reporter : reporters) {
        try {
            reporter.close();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        }
    }
    getElasticsearchClient().close();
    getGrafanaClient().close();
}

14. System2Test#close_throws_exception_on_error()

Project: sonarqube
File: System2Test.java
@Test
public void close_throws_exception_on_error() {
    Closeable closeable = new Closeable() {

        @Override
        public void close() throws IOException {
            throw new IOException("expected");
        }
    };
    try {
        System2.INSTANCE.close(closeable);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e.getCause().getMessage()).isEqualTo("expected");
    }
}

15. Util#close()

Project: sling
File: Util.java
public static void close(InputSource is) {
    Closeable c = is.getByteStream();
    if (c == null) {
        c = is.getCharacterStream();
    }
    if (c != null) {
        try {
            c.close();
        } catch (IOException e) {
        }
    }
}

16. Store#unmarshal()

Project: sis
File: Store.java
/**
     * Unmarshal the object, if not already done. Note that {@link #object} may still be null
     * if an exception has been thrown at this invocation time or in previous invocation.
     *
     * @throws DataStoreException if an error occurred during the unmarshalling process.
     */
private void unmarshal() throws DataStoreException {
    final StreamSource s = source;
    final Closeable in = input(s);
    // Cleared first in case of error.
    source = null;
    if (in != null)
        try {
            try {
                object = XML.unmarshal(s, properties());
            } finally {
                in.close();
            }
        } catch (JAXBException e) {
            throw new DataStoreException(Errors.format(Errors.Keys.CanNotRead_1, name), e);
        } catch (IOException e) {
            throw new DataStoreException(Errors.format(Errors.Keys.CanNotRead_1, name), e);
        }
}

17. Main#initHttpServer()

Project: servo
File: Main.java
private static void initHttpServer() throws Exception {
    // Setup default endpoints
    final HttpServer server = HttpServer.create();
    server.createContext("/echo", new EchoHandler());
    // Hook to allow for graceful exit
    final Closeable c = () -> {
        PollScheduler.getInstance().stop();
        server.stop(5);
    };
    server.createContext("/exit", new ExitHandler(c));
    // Bind and start server
    server.bind(new InetSocketAddress(Config.getPort()), 0);
    server.start();
}

18. StreamUtility#closeQuietly()

Project: RemoteDroid
File: StreamUtility.java
public static void closeQuietly(Closeable... closeables) {
    if (closeables == null)
        return;
    for (Closeable closeable : closeables) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }
}

19. RDFServingInitListener#contextDestroyed()

Project: oryx
File: RDFServingInitListener.java
@Override
public void contextDestroyed(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    Closeable manager = (Closeable) context.getAttribute(AbstractRDFServlet.GENERATION_MANAGER_KEY);
    if (manager != null) {
        try {
            manager.close();
        } catch (IOException e) {
            log.warn("Unexpected error while closing", e);
        }
    }
}

20. KMeansServingInitListener#contextDestroyed()

Project: oryx
File: KMeansServingInitListener.java
@Override
public void contextDestroyed(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    Closeable manager = (Closeable) context.getAttribute(AbstractKMeansServlet.GENERATION_MANAGER_KEY);
    if (manager != null) {
        try {
            manager.close();
        } catch (IOException e) {
            log.warn("Unexpected error while closing", e);
        }
    }
}

21. ALSServingInitListener#contextDestroyed()

Project: oryx
File: ALSServingInitListener.java
@Override
public void contextDestroyed(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    Closeable recommender = (Closeable) context.getAttribute(AbstractALSServlet.RECOMMENDER_KEY);
    if (recommender != null) {
        try {
            recommender.close();
        } catch (IOException e) {
            log.warn("Unexpected error while closing", e);
        }
    }
}

22. MetricsServiceImpl#stop()

Project: ninja
File: MetricsServiceImpl.java
@Dispose(order = 10)
@Override
public void stop() {
    for (Closeable reporter : reporters) {
        log.debug("Stopping {}", reporter.getClass().getName());
        try {
            reporter.close();
        } catch (IOException e) {
            log.error("Failed to stop Metrics reporter", e);
        }
    }
    log.info("Ninja Metrics stopped.");
}

23. IoUtils#closeQuietly()

Project: mina-sshd
File: IoUtils.java
/**
     * Closes a bunch of resources suppressing any {@link IOException}s their
     * {@link Closeable#close()} method may have thrown
     *
     * @param closeables The {@link Closeable}s to close
     * @return The <U>first</U> {@link IOException} that occurred during closing
     * of a resource - if more than one exception occurred, they are added as
     * suppressed exceptions to the first one
     * @see Throwable#getSuppressed()
     */
public static IOException closeQuietly(Closeable... closeables) {
    IOException err = null;
    for (Closeable c : closeables) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException e) {
            GenericUtils.accumulateException(err, e);
        }
    }
    return err;
}

24. FileUtils#closeIO()

Project: KJFrameForAndroid
File: FileUtils.java
/**
     * ???
     * 
     * @param closeables
     */
public static void closeIO(Closeable... closeables) {
    if (null == closeables || closeables.length <= 0) {
        return;
    }
    for (Closeable cb : closeables) {
        try {
            if (null == cb) {
                continue;
            }
            cb.close();
        } catch (IOException e) {
            throw new RuntimeException(FileUtils.class.getClass().getName(), e);
        }
    }
}

25. QBeanSupport#close()

Project: jPOS
File: QBeanSupport.java
protected void close(Closeable... closeables) {
    LogEvent evt = null;
    for (Closeable c : closeables) {
        try {
            c.close();
        } catch (Exception e) {
            if (evt == null)
                evt = getLog().createWarn();
            evt.addMessage(e);
        }
    }
    if (evt != null)
        Logger.log(evt);
}

26. Mapper#close()

Project: johnzon
File: Mapper.java
@Override
public synchronized void close() {
    Collection<Exception> errors = null;
    for (final Closeable c : closeables) {
        try {
            c.close();
        } catch (final IOException e) {
            if (errors == null) {
                errors = new ArrayList<Exception>();
            }
            errors.add(e);
        }
    }
    closeables.clear();
    if (errors != null) {
        throw new IllegalStateException(errors.toString());
    }
}

27. Objects#nullSafeClose()

Project: jjwt
File: Objects.java
public static void nullSafeClose(Closeable... closeables) {
    if (closeables == null) {
        return;
    }
    for (Closeable closeable : closeables) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }
}

28. IOToolsTest#testClose()

Project: Java-Lang
File: IOToolsTest.java
@Test
public void testClose() {
    final int[] count = { 0 };
    Closeable c = new Closeable() {

        @Override
        public void close() throws IOException {
            count[0]++;
        }
    };
    IOTools.close(c);
    assertEquals(1, count[0]);
    IOTools.close(Arrays.asList(c, c, c));
    assertEquals(4, count[0]);
}

29. MemoryNodeStore#addObserver()

Project: jackrabbit-oak
File: MemoryNodeStore.java
@Override
public synchronized Closeable addObserver(Observer observer) {
    observer.contentChanged(getRoot(), null);
    Closeable closeable = new Closeable() {

        @Override
        public void close() throws IOException {
            synchronized (MemoryNodeStore.this) {
                observers.remove(this);
            }
        }
    };
    observers.put(closeable, observer);
    return closeable;
}

30. HierarchyValueWriter#closeStreamAndDeleteFile()

Project: incubator-carbondata
File: HierarchyValueWriter.java
private void closeStreamAndDeleteFile(File f, Closeable... streams) throws KettleException {
    boolean isDeleted = false;
    for (Closeable stream : streams) {
        if (null != stream) {
            try {
                stream.close();
            } catch (IOException e) {
                LOGGER.error(e, "unable to close the stream ");
            }
        }
    }
    // delete the file
    isDeleted = f.delete();
    if (!isDeleted) {
        LOGGER.error("Unable to delete the file " + f.getAbsolutePath());
    }
}

31. HierarchyValueWriterForCSV#closeStreamAndDeleteFile()

Project: incubator-carbondata
File: HierarchyValueWriterForCSV.java
private void closeStreamAndDeleteFile(File f, Closeable... streams) throws KettleException {
    boolean isDeleted = false;
    for (Closeable stream : streams) {
        if (null != stream) {
            try {
                stream.close();
            } catch (IOException e) {
                LOGGER.error(e, "unable to close the stream ");
            }
        }
    }
    // delete the file
    isDeleted = f.delete();
    if (!isDeleted) {
        LOGGER.error("Unable to delete the file " + f.getAbsolutePath());
    }
}

32. SysUtilsTest#testCloseIgnoringException()

Project: heron
File: SysUtilsTest.java
@Test
public void testCloseIgnoringException() throws Exception {
    Closeable closeable = new Closeable() {

        @Override
        public void close() throws IOException {
            throw new RuntimeException("Deliberate exception to be ignored.");
        }
    };
    // This invocation should not throw any exceptions
    // Otherwise, the test will automatically fail
    SysUtils.closeIgnoringExceptions(closeable);
    Assert.assertTrue(true);
}

33. FileUtils#silentlyClose()

Project: freeplane
File: FileUtils.java
/** to be used in a finally block. This method is null-safe. */
public static void silentlyClose(Closeable... streams) {
    for (Closeable stream : streams) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                LogUtils.severe(e);
            }
        }
    }
}

34. ReferenceCountingSegmentQueryRunner#run()

Project: druid
File: ReferenceCountingSegmentQueryRunner.java
@Override
public Sequence<T> run(final Query<T> query, Map<String, Object> responseContext) {
    final Closeable closeable = adapter.increment();
    if (closeable != null) {
        try {
            final Sequence<T> baseSequence = factory.createRunner(adapter).run(query, responseContext);
            return new ResourceClosingSequence<T>(baseSequence, closeable);
        } catch (RuntimeException e) {
            CloseQuietly.close(closeable);
            throw e;
        }
    } else {
        // Segment was closed before we had a chance to increment the reference count
        return new ReportTimelineMissingSegmentQueryRunner<T>(descriptor).run(query, responseContext);
    }
}

35. IOUtils#closeQuietly()

Project: directory-shared
File: IOUtils.java
/**
     * Closes a <code>Closeable</code> unconditionally.
     * <p>
     * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. This is typically used in
     * finally blocks.
     * <p>
     * Example code:
     * 
     * <pre>
     * Closeable closeable = null;
     * try {
     *     closeable = new FileReader("foo.txt");
     *     // process closeable
     *     closeable.close();
     * } catch (Exception e) {
     *     // error handling
     * } finally {
     *     IOUtils.closeQuietly(closeable);
     * }
     * </pre>
     * 
     * Closing all streams:
     * 
     * <pre>
     * try {
     *     return IOUtils.copy(inputStream, outputStream);
     * } finally {
     *     IOUtils.closeQuietly(inputStream);
     *     IOUtils.closeQuietly(outputStream);
     * }
     * </pre>
     * 
     * @param closeables the objects to close, may be null or already closed
     * @since 2.5
     */
public static void closeQuietly(Closeable... closeables) {
    if (closeables == null) {
        return;
    }
    for (Closeable closeable : closeables) {
        closeQuietly(closeable);
    }
}

36. AbstractStreamAwareProxy#release()

Project: community-edition
File: AbstractStreamAwareProxy.java
/**
     * Encapsulates the logic of releasing the captured stream or channel. It is expected that each resource object shares the same channel
     */
public void release() {
    Closeable stream = getStream();
    if ((null == stream) || !canBeClosed()) {
        return;
    }
    try {
        stream.close();
    } catch (IOException e) {
        throw new RuntimeException("Failed to close stream!", e);
    }
}

37. CustomRamProviderTest#tearDown()

Project: commons-vfs
File: CustomRamProviderTest.java
@After
public void tearDown() throws Exception {
    for (final Closeable closeable : this.closeables) {
        try {
            closeable.close();
        } catch (final Exception e) {
        }
    }
    manager.close();
}

38. IoUtils#closeQuietly()

Project: commons-imaging
File: IoUtils.java
public static void closeQuietly(final boolean mayThrow, final Closeable... closeables) throws IOException {
    IOException firstException = null;
    for (final Closeable closeable : closeables) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (final IOException ioException) {
                if (mayThrow && firstException == null) {
                    firstException = ioException;
                }
            }
        }
    }
    if (firstException != null) {
        throw firstException;
    }
}

39. CHMUseCasesTest#after()

Project: Chronicle-Map
File: CHMUseCasesTest.java
@After
public void after() {
    for (Closeable c : closeables) {
        try {
            c.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    closeables.clear();
    map2 = null;
    map1 = null;
}

40. ReplicatedChronicleMap#close()

Project: Chronicle-Map
File: ReplicatedChronicleMap.java
@Override
public synchronized void close() {
    if (closed)
        return;
    for (Closeable closeable : closeables) {
        try {
            closeable.close();
        } catch (IOException e) {
            LOG.error("", e);
        }
    }
    super.close();
}

41. DefaultProgramWorkflowRunner#runAndWait()

Project: cdap
File: DefaultProgramWorkflowRunner.java
private void runAndWait(ProgramRunner programRunner, Program program, ProgramOptions options) throws Exception {
    Closeable closeable = createCloseable(programRunner, program);
    ProgramController controller;
    try {
        controller = programRunner.run(program, options);
    } catch (Throwable t) {
        Closeables.closeQuietly(closeable);
        throw t;
    }
    blockForCompletion(closeable, controller);
    if (controller instanceof WorkflowTokenProvider) {
        updateWorkflowToken(((WorkflowTokenProvider) controller).getWorkflowToken());
    } else {
        // This shouldn't happen
        throw new IllegalStateException("No WorkflowToken available after program completed: " + program.getId());
    }
}

42. HierarchyValueWriter#closeStreamAndDeleteFile()

Project: carbondata
File: HierarchyValueWriter.java
private void closeStreamAndDeleteFile(File f, Closeable... streams) throws KettleException {
    boolean isDeleted = false;
    for (Closeable stream : streams) {
        if (null != stream) {
            try {
                stream.close();
            } catch (IOException e) {
                LOGGER.error(e, "unable to close the stream ");
            }
        }
    }
    // delete the file
    isDeleted = f.delete();
    if (!isDeleted) {
        LOGGER.error("Unable to delete the file " + f.getAbsolutePath());
    }
}

43. HierarchyValueWriterForCSV#closeStreamAndDeleteFile()

Project: carbondata
File: HierarchyValueWriterForCSV.java
private void closeStreamAndDeleteFile(File f, Closeable... streams) throws KettleException {
    boolean isDeleted = false;
    for (Closeable stream : streams) {
        if (null != stream) {
            try {
                stream.close();
            } catch (IOException e) {
                LOGGER.error(e, "unable to close the stream ");
            }
        }
    }
    // delete the file
    isDeleted = f.delete();
    if (!isDeleted) {
        LOGGER.error("Unable to delete the file " + f.getAbsolutePath());
    }
}

44. Processor#close()

Project: bnd
File: Processor.java
public void close() throws IOException {
    for (Closeable c : toBeClosed) {
        try {
            c.close();
        } catch (IOException e) {
        }
    }
    if (pluginLoader != null)
        pluginLoader.closex();
    toBeClosed.clear();
}

45. IOUtil#close()

Project: AndroidWeekly
File: IOUtil.java
public static void close(Closeable... closeables) {
    if (closeables == null) {
        return;
    }
    for (Closeable closeable : closeables) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

46. Closeables#closeAllSuppress()

Project: airlift
File: Closeables.java
public static <T extends Throwable> T closeAllSuppress(T rootCause, Closeable... closeables) {
    checkNotNull(rootCause, "rootCause is null");
    if (closeables == null) {
        return rootCause;
    }
    for (Closeable closeable : closeables) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Throwable e) {
            rootCause.addSuppressed(e);
        }
    }
    return rootCause;
}

47. Closeables#closeAllRuntimeException()

Project: airlift
File: Closeables.java
public static void closeAllRuntimeException(Closeable... closeables) {
    if (closeables == null) {
        return;
    }
    RuntimeException rootCause = null;
    for (Closeable closeable : closeables) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Throwable e) {
            if (rootCause == null) {
                rootCause = new RuntimeException(e);
            } else {
                rootCause.addSuppressed(e);
            }
        }
    }
    if (rootCause != null) {
        throw rootCause;
    }
}

48. Closeables#closeQuietly()

Project: airlift
File: Closeables.java
public static void closeQuietly(Closeable... closeables) {
    if (closeables == null) {
        return;
    }
    for (Closeable closeable : closeables) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOExceptionRuntimeException |  ignored) {
        }
    }
}

49. ReferenceCountingSegmentTest#testMultipleClose()

Project: druid
File: ReferenceCountingSegmentTest.java
@Test
public void testMultipleClose() throws Exception {
    Assert.assertFalse(segment.isClosed());
    final Closeable closeable = segment.increment();
    Assert.assertTrue(segment.getNumReferences() == 1);
    closeable.close();
    closeable.close();
    exec.submit(new Runnable() {

        @Override
        public void run() {
            try {
                closeable.close();
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    });
    Assert.assertTrue(segment.getNumReferences() == 0);
    Assert.assertFalse(segment.isClosed());
    segment.close();
    segment.close();
    exec.submit(new Runnable() {

        @Override
        public void run() {
            try {
                segment.close();
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    });
    Assert.assertTrue(segment.getNumReferences() == 0);
    Assert.assertTrue(segment.isClosed());
    segment.increment();
    segment.increment();
    segment.increment();
    Assert.assertTrue(segment.getNumReferences() == 0);
    segment.close();
    Assert.assertTrue(segment.getNumReferences() == 0);
}

50. CommitQueueTest#concurrentCommits()

Project: jackrabbit-oak
File: CommitQueueTest.java
@Test
public void concurrentCommits() throws Exception {
    final DocumentNodeStore store = builderProvider.newBuilder().getNodeStore();
    AtomicBoolean running = new AtomicBoolean(true);
    Closeable observer = store.addObserver(new Observer() {

        private RevisionVector before = new RevisionVector(new Revision(0, 0, store.getClusterId()));

        @Override
        public void contentChanged(@Nonnull NodeState root, @Nullable CommitInfo info) {
            DocumentNodeState after = (DocumentNodeState) root;
            RevisionVector r = after.getRevision();
            LOG.debug("seen: {}", r);
            if (r.compareTo(before) < 0) {
                exceptions.add(new Exception("Inconsistent revision sequence. Before: " + before + ", after: " + r));
            }
            before = r;
        }
    });
    // perform commits with multiple threads
    List<Thread> writers = new ArrayList<Thread>();
    for (int i = 0; i < NUM_WRITERS; i++) {
        final Random random = new Random(i);
        writers.add(new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < COMMITS_PER_WRITER; i++) {
                        Commit commit = store.newCommit(null, null);
                        try {
                            Thread.sleep(0, random.nextInt(1000));
                        } catch (InterruptedException e) {
                        }
                        if (random.nextInt(5) == 0) {
                            // cancel 20% of the commits
                            store.canceled(commit);
                        } else {
                            boolean isBranch = random.nextInt(5) == 0;
                            store.done(commit, isBranch, null);
                        }
                    }
                } catch (Exception e) {
                    exceptions.add(e);
                }
            }
        }));
    }
    for (Thread t : writers) {
        t.start();
    }
    for (Thread t : writers) {
        t.join();
    }
    running.set(false);
    observer.close();
    store.dispose();
    assertNoExceptions();
}

51. FinalizableReferenceQueueClassLoaderUnloadingTest#doTestUnloadableInStaticFieldIfClosed()

Project: guava
File: FinalizableReferenceQueueClassLoaderUnloadingTest.java
// If you have a FinalizableReferenceQueue that is a static field of one of the classes of your
// app (like the FrqUser class above), then the app's ClassLoader will never be gc'd. The reason
// is that we attempt to run a thread in a separate ClassLoader that will detect when the FRQ
// is no longer referenced, meaning that the app's ClassLoader has been gc'd, and when that
// happens. But the thread's supposedly separate ClassLoader actually has a reference to the app's
// ClasLoader via its AccessControlContext. It does not seem to be possible to make a
// URLClassLoader without capturing this reference, and it probably would not be desirable for
// security reasons anyway. Therefore, the FRQ.close() method provides a way to stop the thread
// explicitly. This test checks that calling that method does allow an app's ClassLoader to be
// gc'd even if there is a still a FinalizableReferenceQueue in a static field. (Setting the field
// to null would also work, but only if there are no references to the FRQ anywhere else.)
private WeakReference<ClassLoader> doTestUnloadableInStaticFieldIfClosed() throws Exception {
    final URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
    final URL[] urls = myLoader.getURLs();
    URLClassLoader sepLoader = new URLClassLoader(urls, myLoader.getParent());
    Class<?> frqC = FinalizableReferenceQueue.class;
    Class<?> sepFrqC = sepLoader.loadClass(frqC.getName());
    assertNotSame(frqC, sepFrqC);
    Class<?> sepFrqSystemLoaderC = sepLoader.loadClass(FinalizableReferenceQueue.SystemLoader.class.getName());
    Field disabled = sepFrqSystemLoaderC.getDeclaredField("disabled");
    disabled.setAccessible(true);
    disabled.set(null, true);
    Class<?> frqUserC = FrqUser.class;
    Class<?> sepFrqUserC = sepLoader.loadClass(frqUserC.getName());
    assertNotSame(frqUserC, sepFrqUserC);
    assertSame(sepLoader, sepFrqUserC.getClassLoader());
    Callable<?> sepFrqUser = (Callable<?>) sepFrqUserC.newInstance();
    WeakReference<?> finalizableWeakReference = (WeakReference<?>) sepFrqUser.call();
    GcFinalization.awaitClear(finalizableWeakReference);
    Field sepFrqUserFinalizedF = sepFrqUserC.getField("finalized");
    Semaphore finalizeCount = (Semaphore) sepFrqUserFinalizedF.get(null);
    boolean finalized = finalizeCount.tryAcquire(5, TimeUnit.SECONDS);
    assertTrue(finalized);
    Field sepFrqUserFrqF = sepFrqUserC.getField("frq");
    Closeable frq = (Closeable) sepFrqUserFrqF.get(null);
    frq.close();
    return new WeakReference<ClassLoader>(sepLoader);
}

52. DBUtilsTest#testWrapConnectionInCloseable()

Project: cqengine
File: DBUtilsTest.java
@Test
public void testWrapConnectionInCloseable() throws Exception {
    ResultSet resultSet = mock(ResultSet.class);
    Closeable closeable = DBUtils.wrapAsCloseable(resultSet);
    closeable.close();
    verify(resultSet, times(1)).close();
}

53. StreamDataFileTestBase#testLiveStream()

Project: cdap
File: StreamDataFileTestBase.java
/**
   * Test live stream reader with new partitions and/or sequence file being created over time.
   */
@Category(SlowTests.class)
@Test
public void testLiveStream() throws Exception {
    String streamName = "live";
    Id.Stream streamId = Id.Stream.from(Id.Namespace.DEFAULT, streamName);
    final String filePrefix = "prefix";
    // 5 seconds
    long partitionDuration = 5000;
    Location location = getLocationFactory().create(streamName);
    location.mkdirs();
    final StreamConfig config = new StreamConfig(streamId, partitionDuration, 10000, Long.MAX_VALUE, location, null, 1000);
    // Create a thread that will write 10 event per second
    final AtomicInteger eventsWritten = new AtomicInteger();
    final List<Closeable> closeables = Lists.newArrayList();
    Thread writerThread = new Thread() {

        @Override
        public void run() {
            try {
                while (!interrupted()) {
                    FileWriter<StreamEvent> writer = createWriter(config, filePrefix);
                    closeables.add(writer);
                    for (int i = 0; i < 10; i++) {
                        long ts = System.currentTimeMillis();
                        writer.append(StreamFileTestUtils.createEvent(ts, "Testing"));
                        eventsWritten.getAndIncrement();
                    }
                    writer.flush();
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
                throw Throwables.propagate(e);
            } catch (InterruptedException e) {
            }
        }
    };
    // Create a live reader start with one partition earlier than current time.
    long partitionStart = StreamUtils.getPartitionStartTime(System.currentTimeMillis() - config.getPartitionDuration(), config.getPartitionDuration());
    Location partitionLocation = StreamUtils.createPartitionLocation(config.getLocation(), partitionStart, config.getPartitionDuration());
    Location eventLocation = StreamUtils.createStreamLocation(partitionLocation, filePrefix, 0, StreamFileType.EVENT);
    // Creates a live stream reader that check for sequence file ever 100 millis.
    FileReader<PositionStreamEvent, StreamFileOffset> reader = new LiveStreamFileReader(config, new StreamFileOffset(eventLocation, 0L, 0), 100);
    List<StreamEvent> events = Lists.newArrayList();
    // Try to read, since the writer thread is not started, it should get nothing
    Assert.assertEquals(0, reader.read(events, 1, 2, TimeUnit.SECONDS));
    // Start the writer thread.
    writerThread.start();
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    while (stopwatch.elapsedTime(TimeUnit.SECONDS) < 10 && reader.read(events, 1, 1, TimeUnit.SECONDS) == 0) {
    // Empty
    }
    stopwatch.stop();
    // Should be able to read a event
    Assert.assertEquals(1, events.size());
    TimeUnit.MILLISECONDS.sleep(partitionDuration * 2);
    writerThread.interrupt();
    writerThread.join();
    LOG.info("Writer stopped with {} events written.", eventsWritten.get());
    stopwatch.reset();
    while (stopwatch.elapsedTime(TimeUnit.SECONDS) < 10 && events.size() != eventsWritten.get()) {
        reader.read(events, eventsWritten.get(), 0, TimeUnit.SECONDS);
    }
    // Should see all events written
    Assert.assertEquals(eventsWritten.get(), events.size());
    // Take a snapshot of the offset.
    StreamFileOffset offset = new StreamFileOffset(reader.getPosition());
    reader.close();
    for (Closeable c : closeables) {
        Closeables.closeQuietly(c);
    }
    // Now creates a new writer to write 10 more events across two partitions with a skip one partition.
    try (FileWriter<StreamEvent> writer = createWriter(config, filePrefix)) {
        for (int i = 0; i < 5; i++) {
            long ts = System.currentTimeMillis();
            writer.append(StreamFileTestUtils.createEvent(ts, "Testing " + ts));
        }
        TimeUnit.MILLISECONDS.sleep(partitionDuration * 3 / 2);
        for (int i = 0; i < 5; i++) {
            long ts = System.currentTimeMillis();
            writer.append(StreamFileTestUtils.createEvent(ts, "Testing " + ts));
        }
    }
    // Create a new reader with the previous offset
    reader = new LiveStreamFileReader(config, offset, 100);
    events.clear();
    stopwatch.reset();
    while (stopwatch.elapsedTime(TimeUnit.SECONDS) < 10 && events.size() != 10) {
        reader.read(events, 10, 0, TimeUnit.SECONDS);
    }
    Assert.assertEquals(10, events.size());
    // Try to read more, should got nothing
    reader.read(events, 10, 2, TimeUnit.SECONDS);
    reader.close();
    for (Closeable c : closeables) {
        c.close();
    }
}

54. IOUtils#closeWhileHandlingException()

Project: lucene-solr
File: IOUtils.java
/**
   * Closes all given <tt>Closeable</tt>s, suppressing all thrown exceptions.
   * @see #closeWhileHandlingException(Closeable...)
   */
public static void closeWhileHandlingException(Iterable<? extends Closeable> objects) {
    for (Closeable object : objects) {
        try {
            if (object != null) {
                object.close();
            }
        } catch (Throwable t) {
        }
    }
}

55. DumpProcessingOutputAction#close()

Project: Wikidata-Toolkit
File: DumpProcessingOutputAction.java
@Override
public void close() {
    for (Closeable closeable : this.outputStreams) {
        DumpProcessingOutputAction.close(closeable);
    }
}

56. IOUtils#closeQuietly()

Project: sshj
File: IOUtils.java
public static void closeQuietly(Closeable... closeables) {
    for (Closeable c : closeables) try {
        if (c != null)
            c.close();
    } catch (IOException logged) {
        LOG.warn("Error closing {} - {}", c, logged);
    }
}

57. BriteDatabaseTest#transactionIsCloseable()

Project: sqlbrite
File: BriteDatabaseTest.java
@Test
public void transactionIsCloseable() throws IOException {
    db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES).subscribe(o);
    o.assertCursor().hasRow("alice", "Alice Allison").hasRow("bob", "Bob Bobberson").hasRow("eve", "Eve Evenson").isExhausted();
    Transaction transaction = db.newTransaction();
    //noinspection UnnecessaryLocalVariable
    // Verify type is implemented.
    Closeable closeableTransaction = transaction;
    try {
        db.insert(TABLE_EMPLOYEE, employee("john", "John Johnson"));
        db.insert(TABLE_EMPLOYEE, employee("nick", "Nick Nickers"));
        transaction.markSuccessful();
    } finally {
        closeableTransaction.close();
    }
    o.assertCursor().hasRow("alice", "Alice Allison").hasRow("bob", "Bob Bobberson").hasRow("eve", "Eve Evenson").hasRow("john", "John Johnson").hasRow("nick", "Nick Nickers").isExhausted();
}

58. Store#close()

Project: sis
File: Store.java
/**
     * Closes this data store and releases any underlying resources.
     *
     * @throws DataStoreException if an error occurred while closing this data store.
     */
@Override
public void close() throws DataStoreException {
    object = null;
    final Closeable in = input(source);
    // Cleared first in case of failure.
    source = null;
    if (in != null)
        try {
            in.close();
        } catch (IOException e) {
            throw new DataStoreException(e);
        }
}

59. Store#input()

Project: sis
File: Store.java
/**
     * Returns the input stream or reader set in the given source, or {@code null} if none.
     */
private static Closeable input(final StreamSource source) {
    Closeable in = null;
    if (source != null) {
        in = source.getInputStream();
        if (in == null) {
            in = source.getReader();
        }
    }
    return in;
}

60. EclipseLinkHandler#iterate()

Project: querydsl
File: EclipseLinkHandler.java
@SuppressWarnings("unchecked")
@Override
public <T> CloseableIterator<T> iterate(Query query, FactoryExpression<?> projection) {
    Iterator<T> iterator = null;
    Closeable closeable = null;
    if (query instanceof JpaQuery) {
        JpaQuery<T> elQuery = (JpaQuery<T>) query;
        elQuery.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.ForwardOnly);
        elQuery.setHint(QueryHints.SCROLLABLE_CURSOR, true);
        final Cursor cursor = elQuery.getResultCursor();
        closeable = new Closeable() {

            @Override
            public void close() throws IOException {
                cursor.close();
            }
        };
        iterator = cursor;
    } else {
        iterator = query.getResultList().iterator();
    }
    if (projection != null) {
        return new TransformingIterator<T>(iterator, closeable, projection);
    } else {
        return new IteratorAdapter<T>(iterator, closeable);
    }
}

61. IOUtils#close()

Project: opensearchserver
File: IOUtils.java
public static final void close(final Collection<? extends Closeable> closeables) {
    if (closeables == null)
        return;
    for (Closeable closeable : closeables) closeQuietly(closeable);
}

62. IOUtils#close()

Project: opensearchserver
File: IOUtils.java
public static final void close(final Closeable... closeables) {
    if (closeables == null)
        return;
    for (Closeable closeable : closeables) closeQuietly(closeable);
}

63. TerminalLineSettings#close()

Project: openjdk
File: TerminalLineSettings.java
private static void close(final Closeable... closeables) {
    for (Closeable c : closeables) {
        try {
            c.close();
        } catch (Exception e) {
        }
    }
}

64. Utils#close()

Project: openjdk
File: Utils.java
static void close(Closeable... chans) {
    for (Closeable chan : chans) {
        try {
            chan.close();
        } catch (IOException e) {
        }
    }
}

65. ZipperUtil#zip()

Project: MinecraftForge
File: ZipperUtil.java
public static void zip(File directory, File zipfile) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = null;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.pop();
            for (File kid : directory.listFiles()) {
                String name = base.relativize(kid.toURI()).getPath();
                if (kid.isDirectory()) {
                    queue.push(kid);
                    name = name.endsWith("/") ? name : name + "/";
                    zout.putNextEntry(new ZipEntry(name));
                } else {
                    zout.putNextEntry(new ZipEntry(name));
                    Files.copy(kid, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        res.close();
    }
}

66. RedisClusterClient#forEachCloseable()

Project: lettuce
File: RedisClusterClient.java
protected <T extends Closeable> void forEachCloseable(Predicate<? super Closeable> selector, Consumer<T> function) {
    for (Closeable c : closeableResources) {
        if (selector.test(c)) {
            function.accept((T) c);
        }
    }
}

67. IOUtilsTest#closeQuietly()

Project: language-detector
File: IOUtilsTest.java
@Test
public void closeQuietly() throws IOException {
    Closeable stream = mock(Closeable.class);
    IOUtils.closeQuietly(stream);
    verify(stream, times(1)).close();
}

68. IOUtilsTest#closeQuietlyWhenExceptionThrown()

Project: language-detector
File: IOUtilsTest.java
@Test
public void closeQuietlyWhenExceptionThrown() throws IOException {
    Closeable stream = mock(Closeable.class);
    doThrow(new IOException()).when(stream).close();
    IOUtils.closeQuietly(stream);
}

69. ZipperUtil#zip()

Project: Kingdoms
File: ZipperUtil.java
public static void zip(File directory, File zipfile) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = null;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.pop();
            for (File kid : directory.listFiles()) {
                String name = base.relativize(kid.toURI()).getPath();
                if (kid.isDirectory()) {
                    queue.push(kid);
                    name = name.endsWith("/") ? name : name + "/";
                    zout.putNextEntry(new ZipEntry(name));
                } else {
                    zout.putNextEntry(new ZipEntry(name));
                    Files.copy(kid, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        res.close();
    }
}

70. TerminalLineSettings#close()

Project: jline2
File: TerminalLineSettings.java
private static void close(final Closeable... closeables) {
    for (Closeable c : closeables) {
        if (c != null) {
            try {
                c.close();
            } catch (Exception e) {
            }
        }
    }
}

71. CLI#close()

Project: Jenkins2
File: CLI.java
/**
     * Shuts down the channel and closes the underlying connection.
     */
public void close() throws IOException, InterruptedException {
    channel.close();
    channel.join();
    if (ownsPool)
        pool.shutdown();
    for (Closeable c : closables) c.close();
}

72. IoUtils#closeQuietly()

Project: java-buildpack-auto-reconfiguration
File: IoUtils.java
/**
     * Close a collection of {@link Closeable}s
     *
     * @param closeables the collection of {@link Closeable}s to close
     */
public static void closeQuietly(Closeable... closeables) {
    for (Closeable closeable : closeables) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException e) {
        }
    }
}

73. ObserverTracker#removedService()

Project: jackrabbit-oak
File: ObserverTracker.java
@Override
public void removedService(ServiceReference reference, Object service) {
    Closeable subscription = subscriptions.remove(reference);
    if (subscription != null) {
        Closeables.closeQuietly(subscription);
        bundleContext.ungetService(reference);
    }
}

74. HadoopIgfsInProc#closeStream()

Project: ignite
File: HadoopIgfsInProc.java
/** {@inheritDoc} */
@Override
public void closeStream(HadoopIgfsStreamDelegate desc) throws IOException {
    Closeable closeable = desc.target();
    try {
        closeable.close();
    } catch (IllegalStateException e) {
        throw new IOException("Failed to close IGFS stream because Grid is stopping.", e);
    }
}

75. CLI#close()

Project: hudson
File: CLI.java
/**
     * Shuts down the channel and closes the underlying connection.
     */
public void close() throws IOException, InterruptedException {
    channel.close();
    channel.join();
    if (ownsPool)
        pool.shutdown();
    for (Closeable c : closables) c.close();
}

76. IOUtils#closeQuietly()

Project: hivemall
File: IOUtils.java
public static void closeQuietly(final Closeable... channels) {
    for (Closeable c : channels) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                ;
            }
        }
    }
}

77. AdditionalCloseableInputStream#close()

Project: gobblin
File: AdditionalCloseableInputStream.java
@Override
public void close() throws IOException {
    super.close();
    for (Closeable closeable : this.closeables) {
        closeable.close();
    }
}

78. BaseFileBucket#free()

Project: fred
File: BaseFileBucket.java
public void free(boolean forceFree) {
    Closeable[] toClose;
    if (logMINOR)
        Logger.minor(this, "Freeing " + this, new Exception("debug"));
    synchronized (this) {
        if (freed)
            return;
        freed = true;
        toClose = streams == null ? null : streams.toArray(new Closeable[streams.size()]);
        streams = null;
    }
    if (toClose != null) {
        Logger.error(this, "Streams open free()ing " + this + " : " + Arrays.toString(toClose), new Exception("debug"));
        for (Closeable strm : toClose) {
            try {
                strm.close();
            } catch (IOException e) {
                Logger.error(this, "Caught closing stream in free(): " + e, e);
            } catch (Throwable t) {
                Logger.error(this, "Caught closing stream in free(): " + t, t);
            }
        }
    }
    File file = getFile();
    if ((deleteOnFree() || forceFree) && file.exists()) {
        Logger.debug(this, "Deleting bucket " + file, new Exception("debug"));
        deleteFile();
        if (file.exists())
            Logger.error(this, "Delete failed on bucket " + file, new Exception("debug"));
    }
}

79. ZipperUtil#zip()

Project: FML
File: ZipperUtil.java
public static void zip(File directory, File zipfile) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = null;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.pop();
            for (File kid : directory.listFiles()) {
                String name = base.relativize(kid.toURI()).getPath();
                if (kid.isDirectory()) {
                    queue.push(kid);
                    name = name.endsWith("/") ? name : name + "/";
                    zout.putNextEntry(new ZipEntry(name));
                } else {
                    zout.putNextEntry(new ZipEntry(name));
                    Files.copy(kid, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        res.close();
    }
}

80. IOHelper#close()

Project: fabric8
File: IOHelper.java
/**
     * Closes the given resources if they are available.
     *
     * @param closeables the objects to close
     */
public static void close(Closeable... closeables) {
    for (Closeable closeable : closeables) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }
}

81. IOHelpers#close()

Project: fabric8
File: IOHelpers.java
public static void close(Closeable... closeables) {
    for (Closeable c : closeables) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException e) {
        }
    }
}

82. ClassInstanceProviderTest#testReleaseCloseableInstanceThrows()

Project: ehcache3
File: ClassInstanceProviderTest.java
@Test(expected = IOException.class)
public void testReleaseCloseableInstanceThrows() throws Exception {
    ClassInstanceProvider<String, Closeable> classInstanceProvider = new ClassInstanceProvider<String, Closeable>(null, null);
    Closeable closeable = mock(Closeable.class);
    doThrow(IOException.class).when(closeable).close();
    classInstanceProvider.providedVsCount.put(closeable, new AtomicInteger(1));
    classInstanceProvider.instantiated.add(closeable);
    classInstanceProvider.releaseInstance(closeable);
}

83. ClassInstanceProviderTest#testReleaseCloseableInstance()

Project: ehcache3
File: ClassInstanceProviderTest.java
@Test
public void testReleaseCloseableInstance() throws Exception {
    ClassInstanceProvider<String, Closeable> classInstanceProvider = new ClassInstanceProvider<String, Closeable>(null, null);
    Closeable closeable = mock(Closeable.class);
    classInstanceProvider.providedVsCount.put(closeable, new AtomicInteger(1));
    classInstanceProvider.instantiated.add(closeable);
    classInstanceProvider.releaseInstance(closeable);
    verify(closeable).close();
}

84. ReferenceCountingSequence#toYielder()

Project: druid
File: ReferenceCountingSequence.java
@Override
public <OutType> Yielder<OutType> toYielder(OutType initValue, YieldingAccumulator<OutType, T> accumulator) {
    final Closeable closeable = segment.increment();
    return new ResourceClosingYielder<OutType>(baseSequence.toYielder(initValue, accumulator), closeable);
}

85. SpillingGrouper#deleteFiles()

Project: druid
File: SpillingGrouper.java
private void deleteFiles() {
    for (Closeable closeable : closeables) {
        // CloseQuietly is OK on readable streams
        CloseQuietly.close(closeable);
    }
    for (final File file : files) {
        temporaryStorage.delete(file);
    }
    files.clear();
}

86. JDBCExtractionNamespaceTest#tearDown()

Project: druid
File: JDBCExtractionNamespaceTest.java
@After
public void tearDown() throws InterruptedException, ExecutionException, TimeoutException, IOException {
    final ListenableFuture<?> tearDownFuture = setupTeardownService.submit(new Runnable() {

        @Override
        public void run() {
            try {
                closer.close();
            } catch (IOException e) {
                throw Throwables.propagate(e);
            }
        }
    });
    try (final Closeable closeable = new Closeable() {

        @Override
        public void close() throws IOException {
            setupTeardownService.shutdownNow();
            try {
                if (!setupTeardownService.awaitTermination(60, TimeUnit.SECONDS)) {
                    log.error("Tear down service didn't finish");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IOException("Interrupted", e);
            }
        }
    }) {
        tearDownFuture.get(60, TimeUnit.SECONDS);
    } finally {
        if (Thread.interrupted()) {
            log.info("Thread was interrupted. Clearing interrupt and continuing.");
        }
    }
}

87. JDBCExtractionNamespaceTest#setup()

Project: druid
File: JDBCExtractionNamespaceTest.java
@Before
public void setup() throws Exception {
    final ListenableFuture<Handle> setupFuture = setupTeardownService.submit(new Callable<Handle>() {

        @Override
        public Handle call() {
            final Handle handle = derbyConnectorRule.getConnector().getDBI().open();
            Assert.assertEquals(0, handle.createStatement(String.format("CREATE TABLE %s (%s TIMESTAMP, %s VARCHAR(64), %s VARCHAR(64))", tableName, tsColumn_, keyName, valName)).setQueryTimeout(1).execute());
            handle.createStatement(String.format("TRUNCATE TABLE %s", tableName)).setQueryTimeout(1).execute();
            handle.commit();
            closer.register(new Closeable() {

                @Override
                public void close() throws IOException {
                    handle.createStatement("DROP TABLE " + tableName).setQueryTimeout(1).execute();
                    final ListenableFuture future = setupTeardownService.submit(new Runnable() {

                        @Override
                        public void run() {
                            handle.close();
                        }
                    });
                    try (Closeable closeable = new Closeable() {

                        @Override
                        public void close() throws IOException {
                            future.cancel(true);
                        }
                    }) {
                        future.get(10, TimeUnit.SECONDS);
                    } catch (InterruptedExceptionExecutionException | TimeoutException |  e) {
                        throw new IOException("Error closing handle", e);
                    }
                }
            });
            closer.register(new Closeable() {

                @Override
                public void close() throws IOException {
                    if (extractionCacheManager == null) {
                        return;
                    }
                    final NamespaceExtractionCacheManager.NamespaceImplData implData = extractionCacheManager.implData.get(namespace);
                    if (implData != null && implData.future != null) {
                        implData.future.cancel(true);
                        Assert.assertTrue(implData.future.isDone());
                    }
                }
            });
            for (Map.Entry<String, String> entry : renames.entrySet()) {
                try {
                    insertValues(handle, entry.getKey(), entry.getValue(), "2015-01-01 00:00:00");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw Throwables.propagate(e);
                }
            }
            extractionCacheManager = new OnHeapNamespaceExtractionCacheManager(lifecycle, new NoopServiceEmitter(), ImmutableMap.<Class<? extends ExtractionNamespace>, ExtractionNamespaceCacheFactory<?>>of(JDBCExtractionNamespace.class, new JDBCExtractionNamespaceCacheFactory() {

                @Override
                public Callable<String> getCachePopulator(final String id, final JDBCExtractionNamespace namespace, final String lastVersion, final Map<String, String> cache) {
                    final Callable<String> cachePopulator = super.getCachePopulator(id, namespace, lastVersion, cache);
                    return new Callable<String>() {

                        @Override
                        public String call() throws Exception {
                            updateLock.lockInterruptibly();
                            try {
                                log.debug("Running cache populator");
                                try {
                                    return cachePopulator.call();
                                } finally {
                                    updates.incrementAndGet();
                                }
                            } finally {
                                updateLock.unlock();
                            }
                        }
                    };
                }
            }));
            try {
                lifecycle.start();
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
            closer.register(new Closeable() {

                @Override
                public void close() throws IOException {
                    final ListenableFuture future = setupTeardownService.submit(new Runnable() {

                        @Override
                        public void run() {
                            lifecycle.stop();
                        }
                    });
                    try (final Closeable closeable = new Closeable() {

                        @Override
                        public void close() throws IOException {
                            future.cancel(true);
                        }
                    }) {
                        future.get(30, TimeUnit.SECONDS);
                    } catch (InterruptedExceptionExecutionException | TimeoutException |  e) {
                        throw new IOException("Error stopping lifecycle", e);
                    }
                }
            });
            return handle;
        }
    });
    try (final Closeable closeable = new Closeable() {

        @Override
        public void close() throws IOException {
            if (!setupFuture.isDone() && !setupFuture.cancel(true) && !setupFuture.isDone()) {
                throw new IOException("Unable to stop future");
            }
        }
    }) {
        handleRef = setupFuture.get(10, TimeUnit.SECONDS);
    }
    Assert.assertNotNull(handleRef);
}

88. CombiningSequenceTest#testCombining()

Project: druid
File: CombiningSequenceTest.java
private void testCombining(List<Pair<Integer, Integer>> pairs, List<Pair<Integer, Integer>> expected, int limit) throws Exception {
    // Test that closing works too
    final CountDownLatch closed = new CountDownLatch(1);
    final Closeable closeable = new Closeable() {

        @Override
        public void close() throws IOException {
            closed.countDown();
        }
    };
    Sequence<Pair<Integer, Integer>> seq = Sequences.limit(new CombiningSequence<>(new ResourceClosingSequence<>(Sequences.simple(pairs), closeable), Ordering.natural().onResultOf(Pair.<Integer, Integer>lhsFn()), new BinaryFn<Pair<Integer, Integer>, Pair<Integer, Integer>, Pair<Integer, Integer>>() {

        @Override
        public Pair<Integer, Integer> apply(Pair<Integer, Integer> lhs, Pair<Integer, Integer> rhs) {
            if (lhs == null) {
                return rhs;
            }
            if (rhs == null) {
                return lhs;
            }
            return Pair.of(lhs.lhs, lhs.rhs + rhs.rhs);
        }
    }), limit);
    List<Pair<Integer, Integer>> merged = Sequences.toList(seq, Lists.<Pair<Integer, Integer>>newArrayList());
    Assert.assertEquals(expected, merged);
    Yielder<Pair<Integer, Integer>> yielder = seq.toYielder(null, new YieldingAccumulator<Pair<Integer, Integer>, Pair<Integer, Integer>>() {

        int count = 0;

        @Override
        public Pair<Integer, Integer> accumulate(Pair<Integer, Integer> lhs, Pair<Integer, Integer> rhs) {
            count++;
            if (count % yieldEvery == 0) {
                yield();
            }
            return rhs;
        }
    });
    Iterator<Pair<Integer, Integer>> expectedVals = Iterators.filter(expected.iterator(), new Predicate<Pair<Integer, Integer>>() {

        int count = 0;

        @Override
        public boolean apply(@Nullable Pair<Integer, Integer> input) {
            count++;
            if (count % yieldEvery == 0) {
                return true;
            }
            return false;
        }
    });
    if (expectedVals.hasNext()) {
        while (!yielder.isDone()) {
            final Pair<Integer, Integer> expectedVal = expectedVals.next();
            final Pair<Integer, Integer> actual = yielder.get();
            Assert.assertEquals(expectedVal, actual);
            yielder = yielder.next(actual);
        }
    }
    Assert.assertTrue(yielder.isDone());
    Assert.assertFalse(expectedVals.hasNext());
    yielder.close();
    Assert.assertTrue("resource closed", closed.await(10000, TimeUnit.MILLISECONDS));
}

89. IOUtils#silentlyClose()

Project: droidparts
File: IOUtils.java
public static void silentlyClose(Closeable... closeables) {
    for (Closeable cl : closeables) {
        try {
            if (cl != null) {
                cl.close();
            }
        } catch (Exception e) {
            L.d(e);
        }
    }
}

90. ClosingBase#cleanup()

Project: commons-io
File: ClosingBase.java
@After
public void cleanup() {
    for (Closeable c : toClose) {
        try {
            c.close();
        } catch (IOException ignored) {
        }
    }
}

91. IOUtils#closeQuietly()

Project: commons-io
File: IOUtils.java
/**
     * Closes a <code>Closeable</code> unconditionally.
     * <p>
     * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
     * <p>
     * This is typically used in finally blocks to ensure that the closeable is closed
     * even if an Exception was thrown before the normal close statement was reached.
     * <br>
     * <b>It should not be used to replace the close statement(s)
     * which should be present for the non-exceptional case.</b>
     * <br>
     * It is only intended to simplify tidying up where normal processing has already failed
     * and reporting close failure as well is not necessary or useful.
     * <p>
     * Example code:
     * </p>
     * <pre>
     * Closeable closeable = null;
     * try {
     *     closeable = new FileReader("foo.txt");
     *     // processing using the closeable; may throw an Exception
     *     closeable.close(); // Normal close - exceptions not ignored
     * } catch (Exception e) {
     *     // error handling
     * } finally {
     *     <b>IOUtils.closeQuietly(closeable); // In case normal close was skipped due to Exception</b>
     * }
     * </pre>
     * <p>
     * Closing all streams:
     * <br>
     * <pre>
     * try {
     *     return IOUtils.copy(inputStream, outputStream);
     * } finally {
     *     IOUtils.closeQuietly(inputStream, outputStream);
     * }
     * </pre>
     *
     * @param closeables the objects to close, may be null or already closed
     * @see #closeQuietly(Closeable)
     * @since 2.5
     *
     * @deprecated As of 2.6 removed without replacement. Please use the try-with-resources statement or handle
     * suppressed exceptions manually.
     * @see Throwable#addSuppressed(java.lang.Throwable)
     */
@Deprecated
public static void closeQuietly(final Closeable... closeables) {
    if (closeables == null) {
        return;
    }
    for (final Closeable closeable : closeables) {
        closeQuietly(closeable);
    }
}

92. SparkProgramRunner#closeAll()

Project: cdap
File: SparkProgramRunner.java
private void closeAll(Iterable<Closeable> closeables) {
    for (Closeable closeable : closeables) {
        Closeables.closeQuietly(closeable);
    }
}

93. HttpRequestHandler#channelClosed()

Project: cdap
File: HttpRequestHandler.java
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Close all event sender
    LOG.trace("Channel closed {}", ctx.getChannel());
    for (Closeable c : discoveryLookup.values()) {
        Closeables.closeQuietly(c);
    }
    channelClosed = true;
    super.channelClosed(ctx, e);
}

94. MapReduceProgramRunner#closeAllQuietly()

Project: cdap
File: MapReduceProgramRunner.java
private void closeAllQuietly(Iterable<Closeable> closeables) {
    for (Closeable c : closeables) {
        Closeables.closeQuietly(c);
    }
}

95. CloseableUtils#close()

Project: carrot2
File: CloseableUtils.java
/**
     * Close all {@link Closeable}, ignoring exceptions.
     */
public static void close(Closeable... closeables) {
    for (Closeable c : closeables) close(c);
}

96. IOHelper#close()

Project: camel
File: IOHelper.java
/**
     * Closes the given resources if they are available.
     *
     * @param closeables the objects to close
     */
public static void close(Closeable... closeables) {
    for (Closeable closeable : closeables) {
        try {
            closeable.close();
        } catch (IOException e) {
        }
    }
}

97. IOHelper#close()

Project: camel
File: IOHelper.java
/**
     * Closes the given resources if they are available.
     * 
     * @param closeables the objects to close
     */
public static void close(Closeable... closeables) {
    for (Closeable closeable : closeables) {
        close(closeable);
    }
}

98. SimpleProc#process()

Project: buck
File: SimpleProc.java
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Closeable closeable = new StringReader("example");
    Closeables.closeQuietly(closeable);
    return false;
}

99. AndroidResourceProcessor#loadResourceSymbolTable()

Project: bazel
File: AndroidResourceProcessor.java
@Nullable
public SymbolLoader loadResourceSymbolTable(List<SymbolFileProvider> libraries, String appPackageName, Path primaryRTxt, Multimap<String, SymbolLoader> libMap) throws IOException {
    // The reported availableProcessors may be higher than the actual resources
    // (on a shared system). On the other hand, a lot of the work is I/O, so it's not completely
    // CPU bound. As a compromise, divide by 2 the reported availableProcessors.
    int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
    ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numThreads));
    try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) {
        // Load the package names from the manifest files.
        Map<SymbolFileProvider, ListenableFuture<String>> packageJobs = new HashMap<>();
        for (final SymbolFileProvider lib : libraries) {
            packageJobs.put(lib, executorService.submit(new PackageParsingTask(lib.getManifest())));
        }
        Map<SymbolFileProvider, String> packageNames = new HashMap<>();
        try {
            for (Map.Entry<SymbolFileProvider, ListenableFuture<String>> entry : packageJobs.entrySet()) {
                packageNames.put(entry.getKey(), entry.getValue().get());
            }
        } catch (InterruptedExceptionExecutionException |  e) {
            throw new IOException("Failed to load package name: ", e);
        }
        // Associate the packages with symbol files.
        for (SymbolFileProvider lib : libraries) {
            String packageName = packageNames.get(lib);
            // stored in the primaryRTxt file.
            if (appPackageName.equals(packageName)) {
                continue;
            }
            File rFile = lib.getSymbolFile();
            // If the library has no resource, this file won't exist.
            if (rFile.isFile()) {
                SymbolLoader libSymbols = new SymbolLoader(rFile, stdLogger);
                libMap.put(packageName, libSymbols);
            }
        }
        // Even if there are no libraries, load fullSymbolValues, in case we only have resources
        // defined for the binary.
        File primaryRTxtFile = primaryRTxt.toFile();
        SymbolLoader fullSymbolValues = null;
        if (primaryRTxtFile.isFile()) {
            fullSymbolValues = new SymbolLoader(primaryRTxtFile, stdLogger);
        }
        // Now load the symbol files in parallel.
        List<ListenableFuture<?>> loadJobs = new ArrayList<>();
        Iterable<SymbolLoader> toLoad = fullSymbolValues != null ? Iterables.concat(libMap.values(), ImmutableList.of(fullSymbolValues)) : libMap.values();
        for (final SymbolLoader loader : toLoad) {
            loadJobs.add(executorService.submit(new SymbolLoadingTask(loader)));
        }
        try {
            Futures.allAsList(loadJobs).get();
        } catch (InterruptedExceptionExecutionException |  e) {
            throw new IOException("Failed to load SymbolFile: ", e);
        }
        return fullSymbolValues;
    }
}

100. StandaloneTestStrategy#execute()

Project: bazel
File: StandaloneTestStrategy.java
private TestResultData execute(ActionExecutionContext actionExecutionContext, Spawn spawn, TestRunnerAction action) throws ExecException, InterruptedException {
    Executor executor = actionExecutionContext.getExecutor();
    Closeable streamed = null;
    Path testLogPath = action.getTestLog().getPath();
    TestResultData.Builder builder = TestResultData.newBuilder();
    long startTime = executor.getClock().currentTimeMillis();
    SpawnActionContext spawnActionContext = executor.getSpawnActionContext(action.getMnemonic());
    try {
        try {
            if (executionOptions.testOutput.equals(TestOutputFormat.STREAMED)) {
                streamed = new StreamedTestOutput(Reporter.outErrForReporter(actionExecutionContext.getExecutor().getEventHandler()), testLogPath);
            }
            spawnActionContext.exec(spawn, actionExecutionContext);
            builder.setTestPassed(true).setStatus(BlazeTestStatus.PASSED).setCachable(true).setPassedLog(testLogPath.getPathString());
        } catch (ExecException e) {
            builder.setTestPassed(false).setStatus(e.hasTimedOut() ? BlazeTestStatus.TIMEOUT : BlazeTestStatus.FAILED).addFailedLogs(testLogPath.getPathString());
            if (spawnActionContext.shouldPropagateExecException()) {
                throw e;
            }
        } finally {
            long duration = executor.getClock().currentTimeMillis() - startTime;
            builder.addTestTimes(duration);
            builder.setRunDurationMillis(duration);
            if (streamed != null) {
                streamed.close();
            }
        }
        TestCase details = parseTestResult(action.resolve(actionExecutionContext.getExecutor().getExecRoot()).getXmlOutputPath());
        if (details != null) {
            builder.setTestCase(details);
        }
        return builder.build();
    } catch (IOException e) {
        throw new TestExecException(e.getMessage());
    }
}