Example usage for org.apache.commons.collections.iterators IteratorChain IteratorChain

List of usage examples for org.apache.commons.collections.iterators IteratorChain IteratorChain

Introduction

In this page you can find the example usage for org.apache.commons.collections.iterators IteratorChain IteratorChain.

Prototype

public IteratorChain(Collection iterators) 

Source Link

Document

Constructs a new IteratorChain over the collection of iterators.

Usage

From source file:flex2.compiler.util.IteratorList.java

public Iterator toIterator() {
    switch (size()) {
    case 0://ww  w  .j a va 2  s.  com
        return Collections.emptyList().iterator();
    case 1:
        return get(0);
    default:
        return new IteratorChain(this);
    }
}

From source file:name.martingeisse.webide.features.java.compiler.classpath.ClassFolderLibraryFileManager.java

/**
 * /*  w w w  .j ava2  s. com*/
 */
protected Iterable<JavaFileObject> listClassFilesInternal(final File folder, final boolean recurse)
        throws IOException {
    ParameterUtil.ensureNotNull(folder, "folder");
    File[] folderFiles = folder.listFiles();
    if (folderFiles == null) {
        return new EmptyIterable<JavaFileObject>();
    }
    final List<JavaFileObject> files = new ArrayList<JavaFileObject>();
    final List<Iterable<JavaFileObject>> iterables = new ArrayList<Iterable<JavaFileObject>>();
    for (final File file : folderFiles) {
        if (file.isFile() && file.getName().endsWith(".class")) {
            files.add(new ReadOnlyRegularJavaFileObject(file));
        } else if (file.isDirectory() && recurse) {
            iterables.add(listClassFilesInternal(file, true));
        }
    }
    if (iterables.isEmpty()) {
        return files;
    } else {
        iterables.add(files);
        return new Iterable<JavaFileObject>() {
            @Override
            public Iterator<JavaFileObject> iterator() {
                return GenericTypeUtil.unsafeCast(new IteratorChain(iterables));
            }
        };
    }
}

From source file:io.frictionlessdata.datapackage.Resource.java

public Iterator iter(boolean keyed, boolean extended, boolean cast, boolean relations) throws Exception {
    // Error for non tabular
    if (this.profile == null || !this.profile.equalsIgnoreCase(Profile.PROFILE_TABULAR_DATA_RESOURCE)) {
        throw new DataPackageException("Unsupported for non tabular data.");
    }/*ww w .  ja  v  a2s.c  om*/

    // If the path of a data file has been set.
    if (this.getPath() != null) {

        // And if it's just a one part resource (i.e. only one file path is given).
        if (this.getPath() instanceof File) {
            // then just return the interator for the data located in that file
            File file = (File) this.getPath();
            Table table = (this.schema != null) ? new Table(file, this.schema) : new Table(file);

            return table.iterator(keyed, extended, cast, relations);

        } else if (this.getPath() instanceof URL) {
            URL url = (URL) this.getPath();
            Table table = (this.schema != null) ? new Table(url, this.schema) : new Table(url);
            return table.iterator(keyed, extended, cast, relations);

        } else if (this.getPath() instanceof JSONArray) { // If multipart resource (i.e. multiple file paths are given).

            // Create an iterator for each file, chain them, and then return them as a single iterator.
            JSONArray paths = ((JSONArray) this.getPath());
            Iterator[] tableIteratorArray = new TableIterator[paths.length()];

            // Chain the iterators.
            for (int i = 0; i < paths.length(); i++) {

                String[] schemes = { "http", "https" };
                UrlValidator urlValidator = new UrlValidator(schemes);

                String thePath = paths.getString(i);

                if (urlValidator.isValid(thePath)) {
                    URL url = new URL(thePath);
                    Table table = (this.schema != null) ? new Table(url, this.schema) : new Table(url);
                    tableIteratorArray[i] = table.iterator(keyed, extended, cast, relations);

                } else {
                    File file = new File(thePath);
                    Table table = (this.schema != null) ? new Table(file, this.schema) : new Table(file);
                    tableIteratorArray[i] = table.iterator(keyed, extended, cast, relations);
                }
            }

            IteratorChain iterChain = new IteratorChain(tableIteratorArray);
            return iterChain;

        } else {
            throw new DataPackageException(
                    "Unsupported data type for Resource path. Should be String or List but was "
                            + this.getPath().getClass().getTypeName());
        }

    } else if (this.getData() != null) {

        // Data is in String, hence in CSV Format.
        if (this.getData() instanceof String && this.getFormat().equalsIgnoreCase(FORMAT_CSV)) {
            Table table = new Table((String) this.getData());
            return table.iterator();
        }
        // Data is not String, hence in JSON Array format.
        else if (this.getData() instanceof JSONArray && this.getFormat().equalsIgnoreCase(FORMAT_JSON)) {
            JSONArray dataJsonArray = (JSONArray) this.getData();
            Table table = new Table(dataJsonArray);
            return table.iterator();

        } else {
            // Data is in unexpected format. Throw exception.
            throw new DataPackageException(
                    "A resource has an invalid data format. It should be a CSV String or a JSON Array.");
        }

    } else {
        throw new DataPackageException("No data has been set.");
    }
}

From source file:org.apache.jackrabbit.core.security.principal.DefaultPrincipalProvider.java

/**
 * @see PrincipalProvider#findPrincipals(String, int)
 *///from   ww w  .  j av a 2s  .c  o m
public PrincipalIterator findPrincipals(String simpleFilter, int searchType) {
    checkInitialized();
    switch (searchType) {
    case PrincipalManager.SEARCH_TYPE_GROUP:
        return findGroupPrincipals(simpleFilter);
    case PrincipalManager.SEARCH_TYPE_NOT_GROUP:
        return findUserPrincipals(simpleFilter);
    case PrincipalManager.SEARCH_TYPE_ALL:
        PrincipalIterator[] its = new PrincipalIterator[] { findUserPrincipals(simpleFilter),
                findGroupPrincipals(simpleFilter) };
        return new PrincipalIteratorAdapter(new IteratorChain(its));
    default:
        throw new IllegalArgumentException("Invalid searchType");
    }
}

From source file:org.apache.jackrabbit.jcr2spi.state.NodeState.java

/**
 * {@inheritDoc}//from  w ww .  ja v a2 s  .c  o  m
 * @see ItemState#persisted(ChangeLog)
 */
void persisted(ChangeLog changeLog) throws IllegalStateException {
    // remember parent states that have need to adjust their uniqueID/mixintypes
    // or that got a new child entry added or existing entries removed.
    Map modParents = new HashMap();

    // process deleted states from the changelog
    for (Iterator it = changeLog.deletedStates(); it.hasNext();) {
        ItemState delState = (ItemState) it.next();
        if (Status.isTerminal(delState.getStatus())) {
            log.debug("Removal of State " + delState + " has already been completed.");
            continue;
        }
        delState.getHierarchyEntry().remove();

        // adjust parent states unless the parent is removed as well
        if (delState.getHierarchyEntry().getParent().isAvailable()) {
            try {
                NodeState parent = delState.getParent();
                if (!changeLog.containsDeletedState(parent)) {
                    modifiedParent(parent, delState, modParents);
                }
            } catch (RepositoryException e) {
                // ignore. if parent state cannot be retrieved for whatever
                // reason, it doesn't need to be adjusted
            }
        }
    }

    // process added states from the changelog. since the changlog maintains
    // LinkedHashSet for its entries, the iterator will not return a added
    // entry before its NEW parent.
    for (Iterator it = changeLog.addedStates(); it.hasNext();) {
        ItemState addedState = (ItemState) it.next();
        NodeState parent;
        try {
            parent = addedState.getParent();
        } catch (RepositoryException e) {
            // TODO: handle properly
            log.error("Internal error:", e.getMessage());
            continue;
        }
        // if parent is modified -> remember for final status reset
        if (parent.getStatus() == Status.EXISTING_MODIFIED) {
            modifiedParent(parent, addedState, modParents);
        }
        if (addedState.getStatus() == Status.EXISTING) {
            log.debug("Adding new state " + addedState + " has already been completed.");
        } else {
            // connect the new state to its overlayed state (including update
            // via merging in order to be aware of autocreated values,
            // changed definition etc.
            addedState.reload(false);
        }
    }

    for (Iterator it = changeLog.modifiedStates(); it.hasNext();) {
        ItemState modState = (ItemState) it.next();
        if (modState.getStatus() == Status.EXISTING) {
            log.debug("Modified state has already been processed");
            continue;
        }
        if (modState.isNode()) {
            if (StateUtility.isMovedState((NodeState) modState)) {
                // and mark the moved state existing
                modState.setStatus(Status.EXISTING);
            } else {
                // remember state as modified only for later processing
                if (!modParents.containsKey(modState)) {
                    modParents.put(modState, new ArrayList(2));
                }
            }
        } else {
            // peristed prop-state has status EXISTING now
            modState.setStatus(Status.EXISTING);

            // if property state defines a modified jcr:mixinTypes the parent
            // is listed as modified state and needs to be processed at the end.
            if (NameConstants.JCR_MIXINTYPES.equals(modState.getName())) {
                try {
                    modifiedParent(modState.getParent(), modState, modParents);
                } catch (RepositoryException e) {
                    // should never occur. since parent must be available otherwise
                    // the mixin could not been added/removed.
                    log.warn("Internal error:", e.getMessage());
                }
            }
        }
    }

    /* process all parent states that are marked modified and eventually
       need their uniqueID or mixin-types being adjusted because that property
       has been added, modified or removed */
    for (Iterator it = modParents.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        NodeState parent = (NodeState) entry.getKey();
        List l = (List) entry.getValue();
        adjustNodeState(parent, (PropertyState[]) l.toArray(new PropertyState[l.size()]));
    }

    /* finally check if all entries in the changelog have been processed
       and eventually force a reload in order not to have any states with
       wrong transient status floating around. */
    Iterator[] its = new Iterator[] { changeLog.addedStates(), changeLog.deletedStates(),
            changeLog.modifiedStates() };
    IteratorChain chain = new IteratorChain(its);
    while (chain.hasNext()) {
        ItemState state = (ItemState) chain.next();
        if (!(state.getStatus() == Status.EXISTING || state.getStatus() == Status.REMOVED
                || state.getStatus() == Status.INVALIDATED)) {
            log.info("State " + state + " with Status " + Status.getName(state.getStatus())
                    + " has not been processed upon ChangeLog.persisted => invalidate");
            state.setStatus(Status.EXISTING);
        }
    }
}

From source file:org.apache.jackrabbit.jcr2spi.state.TransientItemStateManager.java

/**
 * Create the change log for the tree starting at <code>target</code>. This
 * includes a  check if the ChangeLog to be created is totally 'self-contained'
 * and independent; items within the scope of this update operation (i.e.
 * below the target) must not have dependencies outside of this tree (e.g.
 * moving a node requires that the target node including both old and new
 * parents are saved).//  w w w  .  j a v  a  2 s.  c  o m
 *
 * @param target
 * @param throwOnStale Throws InvalidItemStateException if either the given
 * <code>ItemState</code> or any of its descendants is stale and the flag is true.
 * @return
 * @throws InvalidItemStateException if a stale <code>ItemState</code> is
 * encountered while traversing the state hierarchy. The <code>changeLog</code>
 * might have been populated with some transient item states. A client should
 * therefore not reuse the <code>changeLog</code> if such an exception is thrown.
 * @throws RepositoryException if <code>state</code> is a new item state.
 */
ChangeLog getChangeLog(ItemState target, boolean throwOnStale)
        throws InvalidItemStateException, ConstraintViolationException, RepositoryException {
    // fail-fast test: check status of this item's state
    if (target.getStatus() == Status.NEW) {
        String msg = "Cannot save/revert an item with status NEW (" + target + ").";
        log.debug(msg);
        throw new RepositoryException(msg);
    }
    if (throwOnStale && Status.isStale(target.getStatus())) {
        String msg = "Attempt to save/revert an item, that has been externally modified (" + target + ").";
        log.debug(msg);
        throw new InvalidItemStateException(msg);
    }

    Set<Operation> ops = new LinkedHashSet<Operation>();
    Set<ItemState> affectedStates = new LinkedHashSet<ItemState>();

    HierarchyEntry he = target.getHierarchyEntry();
    if (he.getParent() == null) {
        // the root entry -> the complete change log can be used for
        // simplicity. collecting ops, states can be omitted.
        if (throwOnStale && !staleStates.isEmpty()) {
            String msg = "Cannot save changes: States has been modified externally.";
            log.debug(msg);
            throw new InvalidItemStateException(msg);
        } else {
            affectedStates.addAll(staleStates);
        }
        ops.addAll(operations);
        affectedStates.addAll(addedStates);
        affectedStates.addAll(modifiedStates);
        affectedStates.addAll(removedStates);
    } else {
        // not root entry:
        // - check if there is a stale state in the scope (save only)
        if (throwOnStale) {
            for (ItemState state : staleStates) {
                if (containedInTree(target, state)) {
                    String msg = "Cannot save changes: States has been modified externally.";
                    log.debug(msg);
                    throw new InvalidItemStateException(msg);
                }
            }
        }
        // - collect all affected states within the scope of save/undo
        Iterator[] its = new Iterator[] { addedStates.iterator(), removedStates.iterator(),
                modifiedStates.iterator() };
        IteratorChain chain = new IteratorChain(its);
        if (!throwOnStale) {
            chain.addIterator(staleStates.iterator());
        }
        while (chain.hasNext()) {
            ItemState state = (ItemState) chain.next();
            if (containedInTree(target, state)) {
                affectedStates.add(state);
            }
        }
        // - collect the set of operations and
        //   check if the affected states listed by the operations are all
        //   listed in the modified,removed or added states collected by this
        //   changelog.
        for (Operation op : operations) {
            Collection<ItemState> opStates = op.getAffectedItemStates();
            for (ItemState state : opStates) {
                if (affectedStates.contains(state)) {
                    // operation needs to be included
                    if (!affectedStates.containsAll(opStates)) {
                        // incomplete changelog: need to save a parent as well
                        String msg = "ChangeLog is not self contained.";
                        throw new ConstraintViolationException(msg);
                    }
                    // no violation: add operation an stop iteration over
                    // all affected states present in the operation.
                    ops.add(op);
                    break;
                }
            }
        }
    }

    ChangeLog cl = new ChangeLog(target, ops, affectedStates);
    return cl;
}

From source file:org.apache.jackrabbit.spi.commons.iterator.Iterators.java

/**
 * Returns an iterator for the concatenation of all the given <code>iterators</code>.
 *
 * @param <T>/*from ww  w.j  a  va  2s.  c o m*/
 * @param iterators
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Iterator<T> iteratorChain(Iterator<? extends T>[] iterators) {
    return new IteratorChain(iterators);
}

From source file:org.apache.jackrabbit.spi.commons.iterator.Iterators.java

/**
 * Returns an iterator for the concatenation of all the given <code>iterators</code>.
 *
 * @param <T>//from ww w. j  a  v  a 2s .  c  o  m
 * @param iterators
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Iterator<T> iteratorChain(Collection<? extends T> iterators) {
    return new IteratorChain(iterators);
}

From source file:org.drools.planner.core.heuristic.selector.move.composite.UnionMoveSelector.java

public Iterator<Move> iterator() {
    if (!randomSelection) {
        List<Iterator<Move>> iteratorList = new ArrayList<Iterator<Move>>(childMoveSelectorList.size());
        for (MoveSelector moveSelector : childMoveSelectorList) {
            iteratorList.add(moveSelector.iterator());
        }//  w  w w .ja  v  a 2 s  .  c o m
        return new IteratorChain(iteratorList);
    } else {
        return new RandomUnionMoveIterator();
    }
}

From source file:org.richfaces.component.UIExtendedDataTable.java

@SuppressWarnings("unchecked")
public Iterator<UIComponent> fixedChildren() {
    IteratorChain chain = new IteratorChain(getFacets().values().iterator());
    //RF-1248 Adding facets to both dataChildren and fixed children
    //To make both supports and header/footer work
    for (Iterator<UIComponent> i = getChildren().iterator(); i.hasNext();) {
        UIComponent kid = (UIComponent) i.next();
        if (kid instanceof Column || kid instanceof UIColumn) {
            chain.addIterator(kid.getFacets().values().iterator());
        }//from  w  w  w .  jav  a  2s.c  o m
    }

    return chain;
}