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.cms.search.solr;
017
018import java.util.Iterator;
019
020import org.apache.solr.client.solrj.response.QueryResponse;
021import org.apache.solr.common.SolrDocument;
022import org.apache.solr.common.SolrDocumentList;
023
024import org.ametys.cms.content.indexing.solr.SolrFieldNames;
025
026/**
027 * Provides an iterator over the IDs of the objects in a solr {@link QueryResponse}.
028 */
029public class SolrResponseIdIterable implements Iterable<String>
030{
031    private SolrDocumentList _docList;
032    
033    /**
034     * Buid the IdIterable.
035     * @param docList The solr response document list.
036     */
037    public SolrResponseIdIterable(SolrDocumentList docList)
038    {
039        this._docList = docList;
040    }
041    
042    @Override
043    public Iterator<String> iterator()
044    {
045        // Return a forwarding iterator.
046        return new DocListIdIterator(_docList);
047    }
048    
049    /**
050     * Iterator over the IDs of the objects in a SolrDocumentList.
051     */
052    protected class DocListIdIterator implements Iterator<String>
053    {
054        private Iterator<SolrDocument> _docIterator;
055        
056        /**
057         * Build a DocListIdIterator.
058         * @param docList the solr socument list.
059         */
060        public DocListIdIterator(SolrDocumentList docList)
061        {
062            this._docIterator = docList.iterator();
063        }
064        
065        @Override
066        public boolean hasNext()
067        {
068            return _docIterator.hasNext();
069        }
070        
071        @Override
072        public String next()
073        {
074            return (String) _docIterator.next().getFieldValue(SolrFieldNames.ID);
075        }
076    }
077}