001/*
002 * Copyright 2010-2019 The jdependency developers.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.vafer.jdependency.utils;
017
018import java.util.Iterator;
019import java.util.stream.Stream;
020import java.util.stream.StreamSupport;
021import java.util.Spliterator;
022import java.util.Spliterators;
023import java.util.jar.JarEntry;
024import java.util.jar.JarInputStream;
025import java.io.IOException;
026
027/**
028 * internal - do not use
029 */
030
031final public class StreamUtils {
032
033    // public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
034    //     return asStream(sourceIterator, false);
035    // }
036
037    // public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
038    //     Iterable<T> iterable = () -> sourceIterator;
039    //     return StreamSupport.stream(iterable.spliterator(), parallel);
040    // }
041
042    public static Stream<JarEntry> asStream( final JarInputStream pInputStream ) {
043        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
044            new Iterator<JarEntry>() {
045
046                JarEntry entry = null;
047
048                public boolean hasNext() {
049                    try {
050                        if (entry == null) {
051                            entry = pInputStream.getNextJarEntry();
052                        }
053                        return entry != null;
054                    } catch(IOException e) {
055                        throw new RuntimeException(e);
056                    }
057                }
058
059                public JarEntry next() {
060                    try {
061                        JarEntry result = entry != null
062                          ? entry
063                          : pInputStream.getNextJarEntry();
064                        entry = null;
065                        return result;
066                    } catch(IOException e) {
067                        throw new RuntimeException(e);
068                    }
069                }
070
071            }, Spliterator.IMMUTABLE), false);
072    }
073}