View Javadoc
1   /*
2    * Copyright 2019 SPF4J.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.spf4j.base;
17  
18  import edu.umd.cs.findbugs.annotations.CleanupObligation;
19  import edu.umd.cs.findbugs.annotations.DischargesObligation;
20  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21  import java.io.Closeable;
22  import java.util.Iterator;
23  import java.util.stream.Stream;
24  import java.util.stream.StreamSupport;
25  
26  /**
27   * need to extend java.io.Closeable so that jaxrs does not interfere.
28   * @author Zoltan Farkas
29   */
30  @CleanupObligation
31  public interface CloseableIterable<T> extends Closeable, Iterable<T> {
32  
33    @DischargesObligation
34    void close();
35  
36    static <T> CloseableIterable<T> from(final CloseableIterator<T> iterator) {
37      return new CloseableIterable<T>() {
38        @Override
39        public void close() {
40          iterator.close();
41        }
42  
43        @Override
44        public Iterator<T> iterator() {
45          return iterator;
46        }
47  
48      };
49    }
50  
51    static <T> CloseableIterable<T> from(final Iterable<T> it) {
52      return from(it, () -> { });
53    }
54  
55  
56    static <T> CloseableIterable<T> from(final Iterable<T> it, final AutoCloseable close) {
57      return new CloseableIterable<T>() {
58        @Override
59        @SuppressFBWarnings("EXS_EXCEPTION_SOFTENING_NO_CHECKED")
60        public void close() {
61          try {
62            close.close();
63          } catch (RuntimeException | Error e) {
64            throw e;
65          } catch (Exception ex) {
66            throw new RuntimeException(ex);
67          }
68        }
69  
70        @Override
71        public Iterator<T> iterator() {
72          return it.iterator();
73        }
74      };
75    }
76  
77    default Stream<T> toStream() {
78      return toStream(false);
79    }
80  
81    default Stream<T> toStream(final boolean parallel) {
82      return StreamSupport.stream(spliterator(), parallel).onClose(() -> this.close());
83    }
84  
85  }