001/**
002 * Copyright 2015 DuraSpace, Inc.
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.fcrepo.kernel.impl.rdf.impl.mappings;
017
018import static com.google.common.collect.Iterators.singletonIterator;
019
020import com.google.common.collect.AbstractIterator;
021import com.google.common.collect.Iterators;
022
023import org.fcrepo.kernel.exception.RepositoryRuntimeException;
024import javax.jcr.Property;
025import javax.jcr.RepositoryException;
026import javax.jcr.Value;
027
028import java.util.Iterator;
029
030/**
031 * Iterate over all the values in a property or list of properties
032 *
033 * @author cabeer
034 */
035public class PropertyValueIterator extends AbstractIterator<Value> {
036    private final Iterator<Property> properties;
037    private Iterator<Value> currentValues;
038
039    /**
040     * Iterate through multiple properties' values
041     * @param properties the properties
042     */
043    public PropertyValueIterator(final Iterator<Property> properties) {
044        this.properties = properties;
045        this.currentValues = null;
046    }
047
048    /**
049     * Iterate through a property's values
050     * @param property the properties
051     */
052    public PropertyValueIterator(final Property property) {
053        this.properties = singletonIterator(property);
054        this.currentValues = null;
055    }
056
057    @Override
058    protected Value computeNext() {
059        try {
060            if (currentValues != null && currentValues.hasNext()) {
061                return currentValues.next();
062            }
063            if (properties.hasNext()) {
064                final Property property = properties.next();
065
066                if (property.isMultiple()) {
067                    currentValues = Iterators.forArray(property.getValues());
068                    return currentValues.next();
069                }
070                currentValues = null;
071                return property.getValue();
072            }
073
074            return endOfData();
075        } catch (final RepositoryException e) {
076            throw new RepositoryRuntimeException(e);
077        }
078    }
079}