All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.day.cq.wcm.commons.ResourceIterator Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 1997-2008 Day Management AG
 * Barfuesserplatz 6, 4001 Basel, Switzerland
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Day Management AG, ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Day.
 */
package com.day.cq.wcm.commons;

import org.apache.sling.api.resource.Resource;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Implements a generic iterator based on an iterator of resources which adapts
 * the element to the respective adapter type. Resources that cannot be adapted
 * to the specified adapter type are skipped.
 */
public class ResourceIterator implements Iterator {

    /**
     * Next element available
     */
    private T next;

    /**
     * Underlying resource iterator
     */
    private final Iterator base;

    /**
     * Adatper to
     */
    private final Class adapterType;

    /**
     * Creates a new iterator that is based on the given resource iterator.
     * @param base base iterator
     * @param adapterType adapter type
     */
    public ResourceIterator(Iterator base, Class adapterType) {
        this.base = base;
        this.adapterType = adapterType;
        seek();
    }

    /**
     * Seesk the next available resource
     * @return the previous element
     */
    private T seek() {
        T prev = next;
        next = null;
        while (base.hasNext() && next == null) {
            next = base.next().adaptTo(adapterType);
        }
        return prev;
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasNext() {
        return next != null;
    }

    /**
     * {@inheritDoc}
     */
    public T next() {
        if (next == null) {
            throw new NoSuchElementException();
        }
        return seek();
    }

    /**
     * {@inheritDoc}
     *
     * @throws UnsupportedOperationException always
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy