001/*
002 *  Copyright 2016 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.util.Collection;
019import java.util.Iterator;
020
021/**
022 * Implementation of an {@link AmetysObjectIterable} based on a {@link Collection} of AmetysObject IDs.
023 * The AmetysObjects are resolved when next() is called.
024 * @param <A> the actual type of {@link AmetysObject}s
025 */
026public class IdCollectionIterable<A extends AmetysObject> implements AmetysObjectIterable<A>
027{
028    AmetysObjectResolver _resolver;
029    private Collection<String> _ids;
030    
031    /**
032     * Creates a {@link IdCollectionIterable}.
033     * @param resolver The AmetysObject resolver.
034     * @param ids the {@link AmetysObject}s collection
035     */
036    public IdCollectionIterable(AmetysObjectResolver resolver, Collection<String> ids)
037    {
038        _resolver = resolver;
039        _ids = ids;
040    }
041    
042    @Override
043    public long getSize()
044    {
045        return _ids.size();
046    }
047    
048    @Override
049    public AmetysObjectIterator<A> iterator()
050    {
051        return new IdIterator(_ids.iterator(), _ids.size());
052    }
053    
054    @Override
055    public void close()
056    {
057        // Nothing to do.
058    }
059    
060    class IdIterator implements AmetysObjectIterator<A>
061    {
062        private Iterator<String> _it;
063        private int _pos;
064        private long _size;
065        
066        public IdIterator(Iterator<String> it, long size)
067        {
068            _it = it;
069            _size = size;
070        }
071        
072        @Override
073        public long getSize()
074        {
075            return _size;
076        }
077        
078        @Override
079        public long getPosition()
080        {
081            return _pos;
082        }
083        
084        @Override
085        public boolean hasNext()
086        {
087            return _it.hasNext();
088        }
089        
090        @Override
091        public A next()
092        {
093            _pos++;
094            return _resolver.resolveById(_it.next());
095        }
096        
097        @Override
098        public void remove()
099        {
100            _it.remove();
101        }
102    }
103}