001/*
002 *  Copyright 2010 Anyware Services
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.ametys.plugins.repository;
017
018import java.io.Closeable;
019import java.util.Spliterator;
020import java.util.Spliterators;
021import java.util.stream.Stream;
022import java.util.stream.StreamSupport;
023
024/**
025 * Allows iteration through {@link AmetysObject}s.<br>
026 * It implements {@link Iterable}, allowing foreach statements.
027 * @param <A> the actual type of {@link AmetysObject}s.
028 */
029public interface AmetysObjectIterable<A extends AmetysObject> extends Iterable<A>, Closeable
030{
031    /**
032     * Returns the number of elements in this iterable.
033     * If this information is unavailable, returns -1.
034     * @return a long
035     */
036    long getSize();
037    
038    AmetysObjectIterator<A> iterator();
039    
040    /**
041     * Close the associated resources.<br>
042     * An {@link AmetysObjectIterable} must NOT be closed if any of the contained {@link AmetysObject} is still in use.
043     */
044    void close();
045    
046    /**
047     * Returns a sequential {@code Stream} with this iterable as its source.
048     * @return a sequential {@code Stream} over the objects in this iterable.
049     */
050    default Stream<A> stream()
051    {
052        return StreamSupport.stream(spliterator(), false);
053    }
054    
055    @Override
056    default Spliterator<A> spliterator()
057    {
058        long size = getSize();
059        
060        if (size < 0)
061        {
062            // Spliterator with unknown size.
063            return Iterable.super.spliterator();
064        }
065        else
066        {
067            // Spliterator with known size.
068            return Spliterators.spliterator(iterator(), size, 0);
069        }
070    }
071}