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

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

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Return true if any Iterator in the IteratorChain has a remaining element.

Usage

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

/**
 * {@inheritDoc}//from ww w  .j av a 2s .com
 * @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)./*from w  w  w .j  a  v a  2s  .co 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.mitre.provenance.db.neo4j.Neo4JPLUSObjectFactory.java

/**
 * <p>Creates a new DAG, with configurable properties, and a full DAG fingerprint.
 * This method will call the surrogate algorithm and compute what the specified user is 
 * permitted to see of the underlying data.
 * <p>Given that the DAG can start from multiple points, there is no connectedness guarantee
 * about the result that will be returned.
 * @deprecated use TraversalSettings instead
 * @param ids an iterable set of object IDs that should be included in the DAG
 * @param user the user viewing the DAG, which will be used as part of the surrogate algorithm to compute what they are
 * permitted to see/* w  w w . jav a 2  s.c om*/
 * @param maxNodes the maximum number of nodes to include in the DAG.
 * @param maxHops the maximum number of hops away to fetch graph items.
 * @param includeNodes if true, the DAG will include nodes.  If false, it will not.
 * @param includeEdges if true, the DAG will include provenance edges.  If false, it will not.
 * @param includeNonProvenanceEdges if true, the DAG will include NPEs.  If false, it will not.
 * @param followNPIDs if true, the "spider" that discovers the graph will follow non-provenance IDs. If false, it will not.  
 * For example, if a node (A) is linked to an MD5 sum as an external identifier, and that MD5 sum is linked to some other provenance
 * object (B), then that object B may be included in the resulting DAG (subject to maxNodes) even if there is no provenance
 * relationship between A and B.
 * @return a LineageDAG object.
 * @throws PLUSException
 */
public static LineageDAG __newDAG(Iterable<String> ids, User user, int maxNodes, int maxHops,
        boolean includeNodes, boolean includeEdges, boolean includeNonProvenanceEdges, boolean followNPIDs)
        throws PLUSException {
    ArrayList<String> oids = new ArrayList<String>();

    // Some IDs are provenance, and we just add those as starting points.
    // Others may refer to other systems; we first need to look up appropriate
    // provenance IDs
    for (String o : ids) {
        if (PLUSUtils.isPLUSOID(o))
            oids.add(o);
        else
            oids.addAll(findStandinOIDsForNPID(o));
    } // End for

    LineageDAG col = new LineageDAG(user);

    if (oids.size() <= 0)
        throw new PLUSException("Cannot create a DAG from no starting points!");

    col.getFingerPrint().startTimer("DiscoverCollection");

    if (maxNodes <= 0 || maxNodes > MAX_OBJECTS) {
        log.warning("Setting maxNodes to 100 on bad setting of " + maxNodes);
        maxNodes = 100;
    }

    if (maxHops <= 0 || maxHops > MAX_PATH_LENGTH) {
        log.warning("Setting maxHops to " + USER_VIEW_PATH_LENGTH + " on bad setting of " + maxHops);
        maxHops = USER_VIEW_PATH_LENGTH;
    }

    col.getFingerPrint().startTimer("Build");
    String lastOID = null;

    col.getFingerPrint().startTimer("sumAccessTime");

    // Build a Cypher query which will get all of the relevant nodes.
    String query = buildQuery(oids, maxNodes, maxHops, true);
    ExecutionResult result = Neo4JStorage.execute(query);

    // The result of the query...
    Iterator<Node> nodes = result.columnAs("m");

    ArrayList<Node> startingPoints = new ArrayList<Node>();
    for (String id : oids) {
        Node sp = Neo4JStorage.oidExists(id);
        if (sp != null) {
            startingPoints.add(sp);
            lastOID = id; // The last starting point that got picked will be the graph focus.
        }
    }

    col.getFingerPrint().stopTimer("sumAccessTime");

    // This iterator chain holds all of the nodes we want to 
    // be in the result.  The starting points have to be added
    // because the query returns only nodes the starting points are
    // connected to, not the starting points themselves.
    IteratorChain chain = new IteratorChain();
    chain.addIterator(startingPoints.iterator());
    chain.addIterator(nodes);

    while (chain.hasNext()) {
        Node n = (Node) chain.next();

        if (includeNodes && n.hasProperty(Neo4JStorage.PROP_PLUSOBJECT_ID)) {
            PLUSObject o = Neo4JPLUSObjectFactory.newObject(n).getVersionSuitableFor(user);
            if (o != null) {
                // log.info("Added node " + o.getId());
                col.addNode(o);
            }
        }

        if (includeEdges) {
            Iterable<Relationship> rels = n.getRelationships(Neo4JStorage.CONTRIBUTED, Neo4JStorage.MARKS,
                    Neo4JStorage.UNSPECIFIED, Neo4JStorage.INPUT_TO, Neo4JStorage.GENERATED,
                    Neo4JStorage.TRIGGERED);

            for (Relationship r : rels) {
                PLUSEdge e = newPLUSEdge(r);
                //log.info("Added edge " + e);
                col.addEdge(e);
            }
        } // End if

        if (includeNonProvenanceEdges) {
            Iterable<Relationship> rels = n.getRelationships(Neo4JStorage.NPE);
            for (Relationship r : rels) {
                NonProvenanceEdge np = newNonProvenanceEdge(r);
                //log.info("Added NPE " + np);
                col.addNonProvenanceEdge(np);

                String oid = np.getFrom();
                if (!col.containsObjectID(oid)) {
                    // TODO
                    // Add this back to the collection, because we came from the NPID
                }

            }
        } // End if
    } // End while

    PLUSObject focus = LineageDAG.chooseFocus(col, lastOID);
    if (focus != null)
        col.setFocus(focus);
    col.getFingerPrint().stopTimer("Build");

    // Because of max size constraints, we will frequently load less
    // of the graph than is actually in the database.  This method loops
    // through the edges, and tags nodes as having "more" information, whenever
    // there's an edge where the other end isnt in the dag.
    // This information lets GUI displays of the graph signify that a node isn't
    // actually a dead-end in the provenance graph.
    for (PLUSEdge e : col.getEdges()) {
        if (col.contains(e.getFrom()) && !col.contains(e.getTo()))
            col.tagNode(e.getFrom(), LineageDAG.TAG_MORE_AVAILABLE, "true");
        else if (!col.contains(e.getFrom()) && col.contains(e.getTo()))
            col.tagNode(e.getTo(), LineageDAG.TAG_MORE_AVAILABLE, "true");
    } // End for

    col = LineageDAG.computeEdgeVoting(col); // Edge voting for surrogates
    col = LineageDAG.traceTaintSources(col); // Trace indirect taints from direct taints
    col = LineageDAG.drawInferrableEdges(col); // Draw inferred edges based on surrogate alg.
    col = LineageDAG.tagHeadAndFeet(col);

    List<PLUSEdge> danglers = LineageDAG.detectDanglers(col);

    if (danglers.size() > 0)
        log.warning("Collection " + col + " contains " + danglers.size() + " dangling edges.");

    col.getFingerPrint().stopTimer("DiscoverCollection");

    col.getFingerPrint().startTimer("GraphFunctions");
    col.getFingerPrint().finished(col);
    col.getFingerPrint().stopTimer("GraphFunctions");

    return col;
}

From source file:org.zaproxy.zap.extension.pscanrules.CookieHttpOnlyScanner.java

@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
    IteratorChain iterator = new IteratorChain();
    Vector<String> cookies1 = msg.getResponseHeader().getHeaders(HttpHeader.SET_COOKIE);

    if (cookies1 != null) {
        iterator.addIterator(cookies1.iterator());
    }//from   w w w.j av a 2 s  . com

    Vector<String> cookies2 = msg.getResponseHeader().getHeaders(HttpHeader.SET_COOKIE2);

    if (cookies2 != null) {
        iterator.addIterator(cookies2.iterator());
    }

    Set<String> ignoreList = CookieUtils.getCookieIgnoreList(getModel());

    while (iterator.hasNext()) {
        String headerValue = (String) iterator.next();
        if (!CookieUtils.hasAttribute(headerValue, HTTP_ONLY_COOKIE_ATTRIBUTE)) {
            if (!ignoreList.contains(CookieUtils.getCookieName(headerValue))) {
                this.raiseAlert(msg, id, headerValue);
            }
        }
    }
}

From source file:org.zaproxy.zap.extension.pscanrules.CookieSecureFlagScanner.java

@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
    if (!msg.getRequestHeader().isSecure()) {
        // If SSL isn't used then the Secure flag has not to be checked
        return;/*from   www  . j av  a 2  s  .com*/
    }

    IteratorChain iterator = new IteratorChain();
    Vector<String> cookies1 = msg.getResponseHeader().getHeaders(HttpHeader.SET_COOKIE);

    if (cookies1 != null) {
        iterator.addIterator(cookies1.iterator());
    }

    Vector<String> cookies2 = msg.getResponseHeader().getHeaders(HttpHeader.SET_COOKIE2);

    if (cookies2 != null) {
        iterator.addIterator(cookies2.iterator());
    }

    Set<String> ignoreList = CookieUtils.getCookieIgnoreList(getModel());

    while (iterator.hasNext()) {
        String headerValue = (String) iterator.next();
        if (!CookieUtils.hasAttribute(headerValue, SECURE_COOKIE_ATTRIBUTE)) {
            if (!ignoreList.contains(CookieUtils.getCookieName(headerValue))) {
                this.raiseAlert(msg, id, headerValue);
            }
        }
    }
}