javax.jcr.NodeIterator

Here are the examples of the java api class javax.jcr.NodeIterator taken from open source projects.

1. JcrNodeTest#shouldAllowHasNextToBeCalledMultipleTimesWithoutAdvancingOnIteratorOverNamedNodes()

Project: modeshape
File: JcrNodeTest.java
@Test
@FixFor("MODE-2126")
public void shouldAllowHasNextToBeCalledMultipleTimesWithoutAdvancingOnIteratorOverNamedNodes() throws Exception {
    Node cars = session.getNode("/Cars");
    NodeIterator iter = cars.getNodes("Hybrid");
    for (int i = 0; i != 10; ++i) {
        // there's only 1 with this name
        assertThat(iter.hasNext(), is(true));
    }
    NodeIterator iter2 = cars.getNodes("Hybrid");
    while (iter2.hasNext()) {
        Node child2 = iter2.nextNode();
        Node child1 = iter.nextNode();
        // System.out.println("Child: " + child1);
        assertThat(child1, is(sameInstance(child2)));
    }
}

2. JcrNodeTest#shouldAllowHasNextToBeCalledMultipleTimesWithoutAdvancing()

Project: modeshape
File: JcrNodeTest.java
@Test
@FixFor("MODE-2126")
public void shouldAllowHasNextToBeCalledMultipleTimesWithoutAdvancing() throws Exception {
    Node cars = session.getNode("/Cars");
    NodeIterator iter = cars.getNodes();
    for (int i = 0; i != 10; ++i) {
        // there are only 4 children
        assertThat(iter.hasNext(), is(true));
    }
    NodeIterator iter2 = cars.getNodes();
    while (iter2.hasNext()) {
        Node child2 = iter2.nextNode();
        Node child1 = iter.nextNode();
        // System.out.println("Child: " + child1);
        assertThat(child1, is(sameInstance(child2)));
    }
}

3. CNDSerializer#writeDefs()

Project: jackrabbit-filevault
File: CNDSerializer.java
private void writeDefs(Writer out, Node node) throws IOException, RepositoryException {
    NodeIterator iter = node.getNodes();
    String primary = null;
    if (node.hasProperty(JcrConstants.JCR_PRIMARYITEMNAME)) {
        primary = node.getProperty(JcrConstants.JCR_PRIMARYITEMNAME).getString();
    }
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        if (child.getPrimaryNodeType().getName().equals(JcrConstants.NT_PROPERTYDEFINITION)) {
            writePropDef(out, child, primary);
        }
    }
    iter = node.getNodes();
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        if (child.getPrimaryNodeType().getName().equals(JcrConstants.NT_CHILDNODEDEFINITION)) {
            writeNodeDef(out, child, primary);
        }
    }
}

4. AbstractQueryTest#checkResult()

Project: jackrabbit
File: AbstractQueryTest.java
/**
     * Checks if the result set contains exactly the <code>nodes</code>.
     * @param result the query result.
     * @param requiredNodes the nodes that need to be in the result set
     * 		(null if no node is required).
     * @param optionalNodes the nodes that may be in the result set
     * 		(null if no node is optional).
     */
protected void checkResult(QueryResult result, Node[] requiredNodes, Node[] optionalNodes) throws RepositoryException {
    // collect paths
    Set<String> requiredPaths = getPathSet(requiredNodes);
    Set<String> optionalPaths = getPathSet(optionalNodes);
    Set<String> resultPaths = new HashSet<String>();
    for (NodeIterator it = result.getNodes(); it.hasNext(); ) {
        resultPaths.add(it.nextNode().getPath());
    }
    // check if all required nodes are in result
    for (Iterator<String> it = requiredPaths.iterator(); it.hasNext(); ) {
        String path = it.next();
        assertTrue(path + " is not part of the result set", resultPaths.contains(path));
    }
    // check result does not contain more than expected
    for (Iterator<String> it = resultPaths.iterator(); it.hasNext(); ) {
        String path = it.next();
        if (!optionalPaths.contains(path)) {
            assertTrue(path + " is not expected to be part of the result set", requiredPaths.contains(path));
        }
    }
}

5. ShareableNodesTest#assertChildrenDoNotContain()

Project: modeshape
File: ShareableNodesTest.java
protected void assertChildrenDoNotContain(Node parent, Node expectedNonChild, String actualName) throws RepositoryException {
    if (actualName == null)
        actualName = expectedNonChild.getName();
    NodeIterator iter = parent.getNodes();
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        boolean found = child.isSame(expectedNonChild);
        assertThat("Unexpectedly found the '" + actualName + "' as a child of the '" + parent.getPath() + "' node", found, is(false));
    }
    iter = parent.getNodes(actualName);
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        boolean found = child.isSame(expectedNonChild);
        assertThat("Unexpectedly found the '" + actualName + "' as a child of the '" + parent.getPath() + "' node", found, is(false));
    }
}

6. ShareableNodesTest#assertChildrenContain()

Project: modeshape
File: ShareableNodesTest.java
protected void assertChildrenContain(Node parent, Node expectedChild, String actualName) throws RepositoryException {
    if (actualName == null)
        actualName = expectedChild.getName();
    NodeIterator iter = parent.getNodes();
    boolean found = false;
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        if (child.isSame(expectedChild))
            found = true;
    }
    assertThat("Did not find the child named '" + actualName + "' as a child of the '" + parent.getPath() + "' parent node", found, is(true));
    iter = parent.getNodes(actualName);
    found = false;
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        if (child.isSame(expectedChild))
            found = true;
    }
    assertThat("Did not find the '" + actualName + "' as a child of the '" + parent.getPath() + "' parent node", found, is(true));
}

7. ShareableNodesTest#assertSameChildren()

Project: modeshape
File: ShareableNodesTest.java
protected void assertSameChildren(Node share, Node original) throws RepositoryException {
    Set<String> originalChildNames = new HashSet<String>();
    for (NodeIterator iter = original.getNodes(); iter.hasNext(); ) {
        Node node = iter.nextNode();
        originalChildNames.add(node.getName());
    }
    for (NodeIterator iter = share.getNodes(); iter.hasNext(); ) {
        Node child = iter.nextNode();
        Node originalChild = original.getNode(child.getName());
        originalChildNames.remove(child.getName());
        // Should be the exact same child nodes
        assertThat(child.isSame(originalChild), is(true));
    }
    assertThat("Extra children in original: " + originalChildNames, originalChildNames.isEmpty(), is(true));
}

8. JcrSessionTest#queryAndExpectResults()

Project: modeshape
File: JcrSessionTest.java
private List<Node> queryAndExpectResults(String queryString, int howMany) throws RepositoryException {
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    Query query = queryManager.createQuery(queryString, Query.JCR_SQL2);
    NodeIterator nodes = query.execute().getNodes();
    List<Node> result = new ArrayList<Node>();
    while (nodes.hasNext()) {
        result.add(nodes.nextNode());
    }
    assertEquals("Invalid nodes retrieved from query: " + result, howMany, result.size());
    return result;
}

9. JcrQueryManagerTest#shouldBeAbleToExecuteExceptOperationWithJoinCriteria()

Project: modeshape
File: JcrQueryManagerTest.java
@Test
@FixFor("MODE-2247")
public void shouldBeAbleToExecuteExceptOperationWithJoinCriteria() throws RepositoryException {
    String sql = "SELECT category.[jcr:path] AS p FROM [nt:unstructured] AS category WHERE ISCHILDNODE(category,'/Cars')" + "EXCEPT " + "SELECT category.[jcr:path] AS p FROM [nt:unstructured] AS category JOIN [car:Car] AS cars ON ISCHILDNODE(cars,category) " + " WHERE cars.[jcr:name] LIKE '%Rover%' OR cars.[jcr:name] LIKE '%Toyota%'";
    Query query = session.getWorkspace().getQueryManager().createQuery(sql, Query.JCR_SQL2);
    List<String> expectedPaths = new ArrayList<>(Arrays.asList("/Cars/Sports", "/Cars/Luxury"));
    NodeIterator nodes = query.execute().getNodes();
    assertEquals(2, nodes.getSize());
    while (nodes.hasNext()) {
        String path = nodes.nextNode().getPath();
        assertTrue(path + " not found", expectedPaths.remove(path));
    }
}

10. JcrQueryManagerTest#shouldBeAbleToExecuteIntersectOperationWithSimpleCriteria()

Project: modeshape
File: JcrQueryManagerTest.java
@Test
@FixFor("MODE-2247")
public void shouldBeAbleToExecuteIntersectOperationWithSimpleCriteria() throws Exception {
    String sql1 = "SELECT car1.[jcr:path] FROM [car:Car] AS car1";
    String sql2 = "SELECT car2.[jcr:path] FROM [car:Car] AS car2 WHERE car2.[car:mpgCity] = 12";
    String queryString = sql1 + " INTERSECT " + sql2;
    List<String> expectedPaths = new ArrayList<>(Arrays.asList("/Cars/Sports/Aston Martin DB9", "/Cars/Utility/Land Rover LR3"));
    Query query = session.getWorkspace().getQueryManager().createQuery(queryString, Query.JCR_SQL2);
    NodeIterator nodes = query.execute().getNodes();
    assertEquals(2, nodes.getSize());
    while (nodes.hasNext()) {
        String path = nodes.nextNode().getPath();
        assertTrue(path + " not found", expectedPaths.remove(path));
    }
}

11. JcrMultiValuePropertyTest#shouldPropertyDereferenceReferenceProperties()

Project: modeshape
File: JcrMultiValuePropertyTest.java
@FixFor("MODE-1720")
@Test
public void shouldPropertyDereferenceReferenceProperties() throws Exception {
    prop = cars.getProperty("referenceProperty");
    Value[] vals = prop.getValues();
    for (Value value : vals) {
        String str = value.getString();
        Node node = cars.getSession().getNodeByIdentifier(str);
        assertThat(node, IsIn.isOneOf((Node) altima, (Node) aston));
    }
    Node[] nodes = prop.getAs(Node[].class);
    for (Node node : nodes) {
        assertThat(node, IsIn.isOneOf((Node) altima, (Node) aston));
    }
    NodeIterator nodeIterator = prop.getAs(NodeIterator.class);
    while (nodeIterator.hasNext()) {
        assertThat(nodeIterator.nextNode(), IsIn.isOneOf((Node) altima, (Node) aston));
    }
    assertThat(prop.getAs(Node.class, 0), IsIn.isOneOf((Node) altima, (Node) aston));
    assertThat(prop.getAs(Node.class, 1), IsIn.isOneOf((Node) altima, (Node) aston));
}

12. AuthenticationAndAuthorizationTest#assertPermissionsCheckedWhenIteratingChildren()

Project: modeshape
File: AuthenticationAndAuthorizationTest.java
private void assertPermissionsCheckedWhenIteratingChildren() throws RepositoryException {
    session = repository.login();
    Node testRoot = session.getNode("/testRoot");
    NodeIterator children = testRoot.getNodes();
    while (children.hasNext()) {
        children.nextNode();
    }
    TestSecurityProvider provider = (TestSecurityProvider) session.context().getSecurityContext();
    Map<String, String> actionsByNodePath = provider.getActionsByNodePath();
    assertTrue("READ permission not checked for node", actionsByNodePath.containsKey("/testRoot"));
    assertTrue("READ permission not checked for node", actionsByNodePath.containsKey("/testRoot/node3"));
    assertTrue("READ permission not checked for node", actionsByNodePath.containsKey("/testRoot/node2"));
    assertTrue("READ permission not checked for node", actionsByNodePath.containsKey("/testRoot/node1"));
}

13. AbstractJcrRepositoryTest#traverseChildren()

Project: modeshape
File: AbstractJcrRepositoryTest.java
protected static int traverseChildren(Node parentNode) throws Exception {
    int childCount = 0;
    NodeIterator children = parentNode.getNodes();
    while (children.hasNext()) {
        childCount++;
        childCount += traverseChildren(children.nextNode());
    }
    return childCount;
}

14. MockConnectorTest#assertExternalNodeHasChildren()

Project: modeshape
File: MockConnectorTest.java
private void assertExternalNodeHasChildren(String externalNodePath, String... children) throws Exception {
    Node externalNode = session.getNode(externalNodePath);
    NodeIterator childNodes = externalNode.getNodes();
    if (children.length == 0) {
        assertEquals(0, childNodes.getSize());
        return;
    }
    List<String> actualNodes = new ArrayList<String>((int) childNodes.getSize());
    while (childNodes.hasNext()) {
        actualNodes.add(childNodes.nextNode().getName());
    }
    assertEquals(Arrays.asList(children), actualNodes);
}

15. MockConnectorTest#shouldNavigateChildrenFromPagedConnector()

Project: modeshape
File: MockConnectorTest.java
@Test
public void shouldNavigateChildrenFromPagedConnector() throws Exception {
    federationManager.createProjection("/testRoot", SOURCE_NAME, MockConnector.PAGED_DOC_LOCATION, "federated1");
    Node doc1Federated = session.getNode("/testRoot/federated1");
    NodeIterator nodesIterator = doc1Federated.getNodes();
    assertEquals(3, nodesIterator.getSize());
    List<String> childrenNames = new ArrayList<String>(3);
    while (nodesIterator.hasNext()) {
        childrenNames.add(nodesIterator.nextNode().getName());
    }
    assertEquals(Arrays.asList("federated4", "federated5", "federated6"), childrenNames);
}

16. FileSystemConnectorTest#shouldBrowseExternalWorkspace()

Project: modeshape
File: FileSystemConnectorTest.java
@Test
public void shouldBrowseExternalWorkspace() throws Exception {
    Session session2 = session.getRepository().login("readonly-fls");
    assertTrue(session2 != null);
    Node node = session2.getNode("/");
    NodeIterator it = node.getNodes();
    ArrayList<String> dirs = new ArrayList<>();
    dirs.add("dir1");
    dirs.add("dir2");
    dirs.add("dir3");
    while (it.hasNext()) {
        dirs.remove(it.nextNode().getName());
    }
    assertEquals(0, dirs.size());
}

17. SequencingRunner#findOutputNodes()

Project: modeshape
File: SequencingRunner.java
/**
     * Finds the top nodes which have been created during the sequencing process, based on the original output node. It is
     * important that this is called before the session is saved, because it uses the new flag.
     * 
     * @param rootOutputNode the node under which the output of the sequencing process was written to.
     * @return the first level of output nodes that were created during the sequencing process; never null
     * @throws RepositoryException if there is a problem finding the output nodes
     */
private List<AbstractJcrNode> findOutputNodes(AbstractJcrNode rootOutputNode) throws RepositoryException {
    if (rootOutputNode.isNew()) {
        return Arrays.asList(rootOutputNode);
    }
    // if the node was not new, we need to find the new sequenced nodes
    List<AbstractJcrNode> nodes = new ArrayList<AbstractJcrNode>();
    NodeIterator childrenIt = rootOutputNode.getNodesInternal();
    while (childrenIt.hasNext()) {
        Node child = childrenIt.nextNode();
        if (child.isNew()) {
            nodes.add((AbstractJcrNode) child);
        }
    }
    return nodes;
}

18. JcrVersionManager#removeHistories()

Project: modeshape
File: JcrVersionManager.java
private void removeHistories(AbstractJcrNode node, SessionCache systemSession) throws RepositoryException {
    JcrVersionHistoryNode versionHistory = null;
    if (node.isNodeType(JcrMixLexicon.VERSIONABLE)) {
        if (node.isShareable()) {
            throw new UnsupportedRepositoryOperationException(JcrI18n.nodeIsShareable.text(node.getPath()));
        }
        versionHistory = getVersionHistory(node);
        if (versionHistory.getAllVersions().getSize() > 1) {
            throw new UnsupportedRepositoryOperationException(JcrI18n.versionHistoryNotEmpty.text(node.getPath()));
        }
    }
    NodeIterator nodeIterator = node.getNodesInternal();
    while (nodeIterator.hasNext()) {
        removeHistories((AbstractJcrNode) nodeIterator.nextNode(), systemSession);
    }
    if (versionHistory != null) {
        MutableCachedNode historyParent = systemSession.mutable(versionHistory.parentKey());
        historyParent.removeChild(systemSession, versionHistory.key());
        systemSession.destroy(versionHistory.key());
    }
}

19. JCRMessageMapper#findDeletedMessagesInMailbox()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findDeletedMessagesInMailbox(Mailbox<JCRId> mailbox) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.DELETED_PROPERTY + "='true'] order by @" + JCRMessage.UID_PROPERTY;
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    QueryResult result = manager.createQuery(queryString, XPATH_LANGUAGE).execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        JCRMessage member = new JCRMessage(iterator.nextNode(), mailboxSession.getLog());
        list.add(member);
    }
    return list;
}

20. JCRMessageMapper#findDeletedMessagesInMailboxBetweenUIDs()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findDeletedMessagesInMailboxBetweenUIDs(Mailbox<JCRId> mailbox, long from, long to) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.UID_PROPERTY + ">=" + from + " and @" + JCRMessage.UID_PROPERTY + "<=" + to + " and @" + JCRMessage.DELETED_PROPERTY + "='true'] order by @" + JCRMessage.UID_PROPERTY;
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    QueryResult result = manager.createQuery(queryString, XPATH_LANGUAGE).execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        list.add(new JCRMessage(iterator.nextNode(), mailboxSession.getLog()));
    }
    return list;
}

21. JCRMessageMapper#findDeletedMessageInMailboxWithUID()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findDeletedMessageInMailboxWithUID(Mailbox<JCRId> mailbox, long uid) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.UID_PROPERTY + "=" + uid + " and @" + JCRMessage.DELETED_PROPERTY + "='true']";
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    Query query = manager.createQuery(queryString, XPATH_LANGUAGE);
    query.setLimit(1);
    QueryResult result = query.execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        JCRMessage member = new JCRMessage(iterator.nextNode(), mailboxSession.getLog());
        list.add(member);
    }
    return list;
}

22. JCRMessageMapper#findDeletedMessagesInMailboxAfterUID()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findDeletedMessagesInMailboxAfterUID(Mailbox<JCRId> mailbox, long uid) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.UID_PROPERTY + ">=" + uid + " and @" + JCRMessage.DELETED_PROPERTY + "='true'] order by @" + JCRMessage.UID_PROPERTY;
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    QueryResult result = manager.createQuery(queryString, XPATH_LANGUAGE).execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        list.add(new JCRMessage(iterator.nextNode(), mailboxSession.getLog()));
    }
    return list;
}

23. JCRMessageMapper#findMessagesInMailbox()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findMessagesInMailbox(Mailbox<JCRId> mailbox, int batchSize) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message) order by @" + JCRMessage.UID_PROPERTY;
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    Query query = manager.createQuery(queryString, XPATH_LANGUAGE);
    if (batchSize > 0)
        query.setLimit(batchSize);
    QueryResult result = query.execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        list.add(new JCRMessage(iterator.nextNode(), mailboxSession.getLog()));
    }
    return list;
}

24. JCRMessageMapper#findMessagesInMailboxBetweenUIDs()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findMessagesInMailboxBetweenUIDs(Mailbox<JCRId> mailbox, long from, long to, int batchSize) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.UID_PROPERTY + ">=" + from + " and @" + JCRMessage.UID_PROPERTY + "<=" + to + "] order by @" + JCRMessage.UID_PROPERTY;
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    Query query = manager.createQuery(queryString, XPATH_LANGUAGE);
    if (batchSize > 0)
        query.setLimit(batchSize);
    QueryResult result = query.execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        list.add(new JCRMessage(iterator.nextNode(), mailboxSession.getLog()));
    }
    return list;
}

25. JCRMessageMapper#findMessageInMailboxWithUID()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findMessageInMailboxWithUID(Mailbox<JCRId> mailbox, long uid) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.UID_PROPERTY + "=" + uid + "]";
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    Query query = manager.createQuery(queryString, XPATH_LANGUAGE);
    query.setLimit(1);
    QueryResult result = query.execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        list.add(new JCRMessage(iterator.nextNode(), mailboxSession.getLog()));
    }
    return list;
}

26. JCRMessageMapper#findMessagesInMailboxAfterUID()

Project: james-mailbox
File: JCRMessageMapper.java
private List<Message<JCRId>> findMessagesInMailboxAfterUID(Mailbox<JCRId> mailbox, long uid, int batchSize) throws RepositoryException {
    List<Message<JCRId>> list = new ArrayList<Message<JCRId>>();
    String queryString = "/jcr:root" + getMailboxPath(mailbox) + "//element(*,jamesMailbox:message)[@" + JCRMessage.UID_PROPERTY + ">=" + uid + "] order by @" + JCRMessage.UID_PROPERTY;
    QueryManager manager = getSession().getWorkspace().getQueryManager();
    Query query = manager.createQuery(queryString, XPATH_LANGUAGE);
    if (batchSize > 0)
        query.setLimit(batchSize);
    QueryResult result = query.execute();
    NodeIterator iterator = result.getNodes();
    while (iterator.hasNext()) {
        list.add(new JCRMessage(iterator.nextNode(), mailboxSession.getLog()));
    }
    return list;
}

27. NTCollectionConverterImpl#deleteCollectionItems()

Project: jackrabbit-ocm
File: NTCollectionConverterImpl.java
private void deleteCollectionItems(Session session, Node parentNode, String itemNodeType) throws VersionException, LockException, ConstraintViolationException, PathNotFoundException, ValueFormatException, RepositoryException {
    NodeIterator nodes = this.getCollectionNodes(session, parentNode, itemNodeType);
    if (nodes == null || nodes.getSize() == 0)
        return;
    while (nodes.hasNext()) {
        Node node = (Node) nodes.next();
        node.remove();
    }
}

28. QueryFulltextTest#testNativeMatchAll()

Project: jackrabbit-oak
File: QueryFulltextTest.java
public void testNativeMatchAll() throws Exception {
    Session session = superuser;
    QueryManager qm = session.getWorkspace().getQueryManager();
    String sql2 = "select [jcr:path] as [path] from [nt:base] " + "where native('solr', '*:*')";
    Query q = qm.createQuery(sql2, Query.JCR_SQL2);
    QueryResult result = q.execute();
    NodeIterator nodes = result.getNodes();
    while (nodes.hasNext()) {
        Node node = nodes.nextNode();
        assertNotNull(node);
    }
}

29. UserManagementTest#testFindAuthorizables()

Project: jackrabbit-oak
File: UserManagementTest.java
/**
     * @see <a href="https://issues.apache.org/jira/browse/JCR-3412">JCR-3412 :
     *      UserManager.findAuthorizables() does not work, if session does not have
     *      read access to common root of all user and groups. </a>
     */
@Test
public void testFindAuthorizables() throws Exception {
    String home = Text.getRelativeParent(UserConstants.DEFAULT_USER_PATH, 1);
    deny(home, privilegesFromName(PrivilegeConstants.JCR_READ));
    allow(getUserManager(superuser).getAuthorizable(testSession.getUserID()).getPath(), privilegesFromName(PrivilegeConstants.JCR_ALL));
    UserManager testUserMgr = getUserManager(testSession);
    Iterator<Authorizable> result = testUserMgr.findAuthorizables(UserConstants.REP_PRINCIPAL_NAME, null, UserManager.SEARCH_TYPE_USER);
    Set<String> ids = new HashSet<String>();
    while (result.hasNext()) {
        ids.add(result.next().getID());
    }
    assertFalse(ids.isEmpty());
    NodeIterator nodeIterator = testSession.getWorkspace().getQueryManager().createQuery("/jcr:root//element(*,rep:User)", Query.XPATH).execute().getNodes();
    assertTrue(nodeIterator.hasNext());
    while (nodeIterator.hasNext()) {
        String userId = nodeIterator.nextNode().getProperty(UserConstants.REP_AUTHORIZABLE_ID).getString();
        if (!ids.remove(userId)) {
            fail("UserId " + userId + " missing in result set.");
        }
    }
    assertTrue("Result mismatch", ids.isEmpty());
}

30. ReadTest#testChildNodesWithAccessCheck()

Project: jackrabbit-oak
File: ReadTest.java
@Test
public void testChildNodesWithAccessCheck() throws Exception {
    Node nodeToDeny = superuser.getNode(path).addNode("nodeToDeny");
    superuser.save();
    //Deny access to one of the child node
    deny(nodeToDeny.getPath(), privilegesFromName(PrivilegeConstants.JCR_READ));
    NodeIterator it = testSession.getNode(path).getNodes();
    Set<String> childNodeNames = new HashSet<String>();
    while (it.hasNext()) {
        Node n = it.nextNode();
        childNodeNames.add(n.getName());
    }
    //Denied node should not show up in the child node names list
    assertFalse(childNodeNames.contains("nodeToDeny"));
}

31. SameNameSiblingTest#iterateSiblings()

Project: jackrabbit-oak
File: SameNameSiblingTest.java
@Test
public void iterateSiblings() throws RepositoryException {
    Set<String> expected = newHashSet(SIBLINGS);
    expected.add(SIBLING);
    expected.remove(SIBLINGS[0]);
    NodeIterator siblings = sns.getNodes();
    while (siblings.hasNext()) {
        Node sib = siblings.nextNode();
        assertTrue("Unexpected node: " + sib.getPath(), expected.remove(sib.getName()));
    }
    assertTrue("Missing nodes: " + expected, expected.isEmpty());
}

32. RemappingTest#testQuery4()

Project: jackrabbit-oak
File: RemappingTest.java
public void testQuery4() throws Exception {
    String statement = "/jcr:root/myRep:security/myRep:authorizables//" + "element(*,myRep:Authorizable)[@my:property='value']";
    QueryManager qm = session.getWorkspace().getQueryManager();
    Query q = qm.createQuery(statement, "xpath");
    q.getBindVariableNames();
    QueryResult qr = q.execute();
    NodeIterator ni = qr.getNodes();
    while (ni.hasNext()) {
        ni.next();
    }
}

33. QueryTest#getNodeList()

Project: jackrabbit-oak
File: QueryTest.java
private static String getNodeList(Session session, String query, String language) throws RepositoryException {
    QueryResult r = session.getWorkspace().getQueryManager().createQuery(query, language).execute();
    NodeIterator it = r.getNodes();
    StringBuilder buff = new StringBuilder();
    while (it.hasNext()) {
        if (buff.length() > 0) {
            buff.append(", ");
        }
        buff.append(it.nextNode().getPath());
    }
    return buff.toString();
}

34. NodeTypeDefinitionTest#testIndexedPropertyDefinition()

Project: jackrabbit-oak
File: NodeTypeDefinitionTest.java
public void testIndexedPropertyDefinition() throws Exception {
    String ntPath = NodeTypeConstants.NODE_TYPES_PATH + '/' + NodeTypeConstants.NT_VERSION;
    assertTrue(superuser.nodeExists(ntPath + "/jcr:propertyDefinition"));
    assertTrue(superuser.nodeExists(ntPath + "/jcr:propertyDefinition[1]"));
    Node pdNode = superuser.getNode(ntPath + "/jcr:propertyDefinition[1]");
    assertEquals(ntPath + "/jcr:propertyDefinition", pdNode.getPath());
    List<String> defNames = new ArrayList();
    NodeType nt = superuser.getWorkspace().getNodeTypeManager().getNodeType(NodeTypeConstants.NT_VERSION);
    for (PropertyDefinition nd : nt.getDeclaredPropertyDefinitions()) {
        defNames.add(nd.getName());
    }
    Node ntNode = superuser.getNode(ntPath);
    NodeIterator it = ntNode.getNodes("jcr:propertyDefinition*");
    while (it.hasNext()) {
        Node def = it.nextNode();
        int index = getIndex(def);
        String name = (def.hasProperty(NodeTypeConstants.JCR_NAME)) ? def.getProperty(NodeTypeConstants.JCR_NAME).getString() : NodeTypeConstants.RESIDUAL_NAME;
        assertEquals(name, defNames.get(index - 1));
    }
}

35. NodeTypeDefinitionTest#testIndexedChildDefinition()

Project: jackrabbit-oak
File: NodeTypeDefinitionTest.java
public void testIndexedChildDefinition() throws Exception {
    String ntPath = NodeTypeConstants.NODE_TYPES_PATH + '/' + NodeTypeConstants.NT_VERSIONHISTORY;
    assertTrue(superuser.nodeExists(ntPath + "/jcr:childNodeDefinition"));
    assertTrue(superuser.nodeExists(ntPath + "/jcr:childNodeDefinition[1]"));
    Node cdNode = superuser.getNode(ntPath + "/jcr:childNodeDefinition[1]");
    assertEquals(ntPath + "/jcr:childNodeDefinition", cdNode.getPath());
    List<String> defNames = new ArrayList();
    NodeType nt = superuser.getWorkspace().getNodeTypeManager().getNodeType(NodeTypeConstants.NT_VERSIONHISTORY);
    for (NodeDefinition nd : nt.getDeclaredChildNodeDefinitions()) {
        defNames.add(nd.getName());
    }
    Node ntNode = superuser.getNode(ntPath);
    NodeIterator it = ntNode.getNodes("jcr:childNodeDefinition*");
    while (it.hasNext()) {
        Node def = it.nextNode();
        int index = getIndex(def);
        String name = (def.hasProperty(NodeTypeConstants.JCR_NAME)) ? def.getProperty(NodeTypeConstants.JCR_NAME).getString() : NodeTypeConstants.RESIDUAL_NAME;
        assertEquals(name, defNames.get(index - 1));
    }
}

36. L6_AccessControlContentTest#testAceContent()

Project: jackrabbit-oak
File: L6_AccessControlContentTest.java
public void testAceContent() throws RepositoryException {
    acl.addAccessControlEntry(testPrincipal, testPrivileges);
    acl.addEntry(EveryonePrincipal.getInstance(), testPrivileges, false);
    acMgr.setPolicy(testRoot, acl);
    // EXERCISE
    String policyPath = null;
    Node aclNode = superuser.getNode(policyPath);
    NodeIterator aclChildren = aclNode.getNodes();
    // EXERCISE
    int expectedSize = -1;
    assertEquals(expectedSize, aclChildren.getSize());
    // EXERCISE: define the type of the first child node.
    String expectedPrimaryTypeName = null;
    while (aclChildren.hasNext()) {
        Node ace = aclChildren.nextNode();
        assertEquals(expectedPrimaryTypeName, ace.getPrimaryNodeType().getName());
        // EXERCISE: define the type of the next item.
        expectedPrimaryTypeName = null;
    }
    Node ace = aclNode.getNodes().nextNode();
// EXERCISE: retrieve all mandatory ac-related properties of this node and verify the expected value.
}

37. TestPackageInstall#testChildNodeOrder2()

Project: jackrabbit-filevault
File: TestPackageInstall.java
/**
     * installs a package that contains a node with childnode ordering and full-coverage sub nodes.
     * see JCRVLT-44
     */
@Test
public void testChildNodeOrder2() throws IOException, RepositoryException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("testpackages/test_childnodeorder2.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());
    assertNodeExists("/tmp/test/en");
    NodeIterator iter = admin.getNode("/tmp/test/en").getNodes();
    StringBuilder names = new StringBuilder();
    while (iter.hasNext()) {
        names.append(iter.nextNode().getName()).append(",");
    }
    assertEquals("child order", "jcr:content,toolbar,products,services,company,events,support,community,blog,", names.toString());
}

38. TestPackageInstall#testChildNodeOrder()

Project: jackrabbit-filevault
File: TestPackageInstall.java
/**
     * installs a package that contains a node with childnode ordering and full-coverage sub nodes.
     * see JCRVLT-24
     */
@Test
public void testChildNodeOrder() throws IOException, RepositoryException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("testpackages/test_childnodeorder.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());
    assertNodeExists("/tmp/ordertest/test/rail/items/modes/items");
    NodeIterator iter = admin.getNode("/tmp/ordertest/test/rail/items/modes/items").getNodes();
    StringBuilder names = new StringBuilder();
    while (iter.hasNext()) {
        names.append(iter.nextNode().getName()).append(",");
    }
    assertEquals("child order", "a,d,b,c,", names.toString());
}

39. RepositoryCopier#trackTree()

Project: jackrabbit-filevault
File: RepositoryCopier.java
private void trackTree(Node node, boolean isNew) throws RepositoryException {
    NodeIterator iter = node.getNodes();
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        if (isNew) {
            track(child.getPath(), "%06d A", ++totalNodes);
        } else {
            track(child.getPath(), "%06d U", ++totalNodes);
        }
        trackTree(child, isNew);
    }
}

40. JcrExporter#scan()

Project: jackrabbit-filevault
File: JcrExporter.java
private void scan(Node dir) throws RepositoryException {
    NodeIterator iter = dir.getNodes();
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        String name = child.getName();
        if (name.equals(".svn") || name.equals(".vlt")) {
            continue;
        }
        if (child.isNodeType(JcrConstants.NT_FOLDER)) {
            exportInfo.update(ExportInfo.Type.RMDIR, child.getPath());
            scan(child);
        } else if (child.isNodeType(JcrConstants.NT_FILE)) {
            exportInfo.update(ExportInfo.Type.DELETE, child.getPath());
        }
    }
}

41. Dump#dump()

Project: jackrabbit
File: Dump.java
/**
     * Dumps the given <code>Node</code> to the given <code>PrintWriter</code>
     * @param out
     *        the <code>PrintWriter</code>
     * @param n
     *        the <code>Node</code>
     * @throws RepositoryException
     */
public void dump(PrintWriter out, Node n) throws RepositoryException {
    out.println(n.getPath());
    PropertyIterator pit = n.getProperties();
    while (pit.hasNext()) {
        Property p = pit.nextProperty();
        out.print(p.getPath() + "=");
        if (p.getDefinition().isMultiple()) {
            Value[] values = p.getValues();
            for (int i = 0; i < values.length; i++) {
                if (i > 0)
                    out.println(",");
                out.println(values[i].getString());
            }
        } else {
            out.print(p.getString());
        }
        out.println();
    }
    NodeIterator nit = n.getNodes();
    while (nit.hasNext()) {
        Node cn = nit.nextNode();
        dump(out, cn);
    }
}

42. ExportFileSystem#addFolder()

Project: jackrabbit
File: ExportFileSystem.java
/**
     * Exports a nt:folder and all its children to the file system
     * @param node
     *        the <code>Node</code>
     * @param file
     *        <code>File</code>
     * @throws CommandException
     *         if the <code>File</code> can't be created
     * @throws RepositoryException
     *         if the current working <code>Repository</code> throws an
     *         <code>Exception</code>
     * @throws IOException
     *         if an IOException occurs
     */
private void addFolder(Node node, File file) throws CommandException, RepositoryException, IOException {
    boolean created = file.mkdir();
    if (!created) {
        throw new CommandException("exception.folder.not.created", new String[] { file.getPath() });
    }
    NodeIterator iter = node.getNodes();
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        // File
        if (child.isNodeType("nt:file")) {
            File childFile = new File(file, child.getName());
            createFile(child, childFile);
        } else if (child.isNodeType("nt:folder")) {
            File childFolder = new File(file, child.getName());
            addFolder(child, childFolder);
        }
    }
}

43. SNSIndexTest#testGetNodesByName()

Project: jackrabbit
File: SNSIndexTest.java
/**
     * Test if accessing the created nodes by name really returns all nodes.
     */
public void testGetNodesByName() throws RepositoryException {
    NodeIterator it = parent.getNodes(snsName);
    long size = it.getSize();
    if (size != -1) {
        assertTrue("4 SNSs have been added -> but iterator size is " + size + ".", size == 4);
    }
    int expectedIndex = 1;
    while (it.hasNext()) {
        Node sns = it.nextNode();
        checkIndex(sns, expectedIndex);
        expectedIndex++;
    }
    assertTrue("4 SNSs have been added -> but iterator size is " + size + ".", size == 4);
}

44. ReorderTest#testOrder()

Project: jackrabbit
File: ReorderTest.java
protected static void testOrder(Node parent, Node[] children) throws RepositoryException {
    NodeIterator it = parent.getNodes();
    int i = 0;
    while (it.hasNext()) {
        Node child = it.nextNode();
        if (i >= children.length) {
            fail("Reorder added a child node.");
        }
        assertTrue("Wrong order of children: " + child + " is not the same as " + children[i], child.isSame(children[i]));
        i++;
    }
    if (i < children.length - 1) {
        fail("Reorder removed a child node.");
    }
}

45. ReorderTest#setUp()

Project: jackrabbit
File: ReorderTest.java
@Override
protected void setUp() throws Exception {
    super.setUp();
    if (!testRootNode.getPrimaryNodeType().hasOrderableChildNodes()) {
        throw new NotExecutableException("Test node does not have orderable children.");
    }
    NodeIterator it = testRootNode.getNodes();
    if (it.hasNext()) {
        throw new NotExecutableException("Test node already contains child nodes");
    }
    createOrderableChildren();
}

46. ReorderNewTest#testRevertReorderToEnd()

Project: jackrabbit
File: ReorderNewTest.java
@Override
public void testRevertReorderToEnd() throws RepositoryException {
    testRootNode.orderBefore(getRelPath(child1), null);
    testOrder(testRootNode, new Node[] { child2, child3, child4, child1 });
    // NEW child nodes -> must be removed upon refresh
    testRootNode.refresh(false);
    NodeIterator it = testRootNode.getNodes();
    if (it.hasNext()) {
        fail("Reverting creation and reordering of new children must remove the children again.");
    }
}

47. ReorderNewTest#testRevertReorder()

Project: jackrabbit
File: ReorderNewTest.java
@Override
public void testRevertReorder() throws RepositoryException {
    testRootNode.orderBefore(getRelPath(child4), getRelPath(child2));
    testOrder(testRootNode, new Node[] { child1, child4, child2, child3 });
    // NEW child nodes -> must be removed upon refresh
    testRootNode.refresh(false);
    NodeIterator it = testRootNode.getNodes();
    if (it.hasNext()) {
        fail("Reverting creation and reordering of new children must remove the children again.");
    }
}

48. ReorderNewSNSTest#testRevertReorderToEnd()

Project: jackrabbit
File: ReorderNewSNSTest.java
@Override
public void testRevertReorderToEnd() throws RepositoryException {
    testRootNode.orderBefore(getRelPath(child1), null);
    testOrder(testRootNode, new Node[] { child2, child3, child4, child1 });
    // NEW child nodes -> must be removed upon refresh
    testRootNode.refresh(false);
    NodeIterator it = testRootNode.getNodes(nodeName2);
    if (it.hasNext()) {
        fail("Reverting creation and reordering of new SNSs must remove the children again.");
    }
}

49. ReorderNewSNSTest#testRevertReorder()

Project: jackrabbit
File: ReorderNewSNSTest.java
@Override
public void testRevertReorder() throws RepositoryException {
    testRootNode.orderBefore(getRelPath(child4), getRelPath(child2));
    testOrder(testRootNode, new Node[] { child1, child4, child2, child3 });
    // NEW child nodes -> must be removed upon refresh
    testRootNode.refresh(false);
    NodeIterator it = testRootNode.getNodes(nodeName2);
    if (it.hasNext()) {
        fail("Reverting creation and reordering of new SNSs must remove the children again.");
    }
}

50. MoveTest#testAccessMovedNodeByOldPath2()

Project: jackrabbit
File: MoveTest.java
/**
     * Same as {@link #testAccessMovedNodeByOldPath()} but calls save() prior to
     * the test.
     */
public void testAccessMovedNodeByOldPath2() throws RepositoryException, NotExecutableException {
    NodeIterator it = srcParentNode.getNodes(moveNode.getName());
    int cnt = 0;
    while (it.hasNext()) {
        it.nextNode();
        cnt++;
    }
    if (cnt > 1) {
        throw new NotExecutableException("Move source parent has multiple child nodes with name " + moveNode.getName());
    }
    String oldPath = moveNode.getPath();
    //move the node
    doMove(oldPath, destinationPath);
    superuser.save();
    try {
        superuser.getItem(oldPath);
        fail("A moved node must not be accessible by its old path any more.");
    } catch (PathNotFoundException e) {
    }
}

51. MoveTest#testAccessMovedNodeByOldPath()

Project: jackrabbit
File: MoveTest.java
/**
     * Test if a moved node is not accessible by its old path any more
     */
public void testAccessMovedNodeByOldPath() throws RepositoryException, NotExecutableException {
    NodeIterator it = srcParentNode.getNodes(moveNode.getName());
    int cnt = 0;
    while (it.hasNext()) {
        it.nextNode();
        cnt++;
    }
    if (cnt > 1) {
        throw new NotExecutableException("Move source parent has multiple child nodes with name " + moveNode.getName());
    }
    String oldPath = moveNode.getPath();
    //move the node
    doMove(oldPath, destinationPath);
    try {
        superuser.getItem(oldPath);
        fail("A moved node must not be accessible by its old path any more.");
    } catch (PathNotFoundException e) {
    }
}

52. HierarchyNodeTest#dump()

Project: jackrabbit
File: HierarchyNodeTest.java
/** Recursively outputs the contents of the given node. */
private void dump(Node node) throws RepositoryException {
    // Then output the properties
    PropertyIterator properties = node.getProperties();
    Set<String> set = new HashSet<String>();
    while (properties.hasNext()) {
        Property property = properties.nextProperty();
        set.add(property.getName());
    }
    if (node.getPrimaryNodeType().getName().equals(ntFolder)) {
        assertTrue(hierarchyNodeProps.size() == set.size() && hierarchyNodeProps.containsAll(set));
    } else if (node.getPrimaryNodeType().getName().equals(ntFile)) {
        assertTrue(hierarchyNodeProps.size() == set.size() && hierarchyNodeProps.containsAll(set));
    } else if (node.getPrimaryNodeType().getName().equals(ntResource)) {
        assertTrue(resourceProps.size() == set.size() && resourceProps.containsAll(set));
    }
    // Finally output all the child nodes recursively
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        dump(nodes.nextNode());
    }
}

53. WorkspaceMoveSameNameSibsTest#testMoveNodesOrderingSupportedByParent()

Project: jackrabbit
File: WorkspaceMoveSameNameSibsTest.java
/**
     * If ordering is supported by the node type of the parent node of the new
     * location, then the newly moved node is appended to the end of the child
     * node list.
     */
public void testMoveNodesOrderingSupportedByParent() throws RepositoryException {
    // test assumes that repositry supports Orderable Child Node Support (optional)
    String[] orderList = { nodeName1, nodeName2, nodeName3 };
    // create a new node to move nodes
    Node newNode = testRootNode.addNode(nodeName2, testNodeType);
    testRootNode.getSession().save();
    // copy node three times below a node and check the order
    for (int i = 0; i < orderList.length; i++) {
        workspace.copy(node1.getPath(), newNode.getPath() + "/" + orderList[i]);
    }
    // check regarding orderList with the counter if nodes are added at the end
    int cnt = 0;
    NodeIterator iter = node2.getNodes();
    while (iter.hasNext()) {
        Node n = iter.nextNode();
        assertTrue(n.getName().equals(orderList[cnt]));
        cnt++;
    }
}

54. WorkspaceCopySameNameSibsTest#testCopyNodesOrderingSupportedByParent()

Project: jackrabbit
File: WorkspaceCopySameNameSibsTest.java
/**
     * If ordering is supported by the node type of the parent node of the new
     * location, then the newly moved node is appended to the end of the child
     * node list.
     */
public void testCopyNodesOrderingSupportedByParent() throws RepositoryException {
    // test assumes that repositry supports Orderable Child Node Support (optional)
    String[] orderList = { nodeName1, nodeName2, nodeName3 };
    // copy node three times below a node and check the order
    for (int i = 0; i < orderList.length; i++) {
        workspace.copy(node1.getPath(), node2.getPath() + "/" + orderList[i]);
    }
    // check regarding orderList if nodes are added at the end
    int cnt = 0;
    NodeIterator iter = node2.getNodes();
    while (iter.hasNext()) {
        Node n = iter.nextNode();
        assertTrue(n.getName().equals(orderList[cnt]));
        cnt++;
    }
}

55. WorkspaceCopyBetweenWorkspacesSameNameSibsTest#testCopyNodesOrderingSupportedByParent()

Project: jackrabbit
File: WorkspaceCopyBetweenWorkspacesSameNameSibsTest.java
/**
     * If ordering is supported by the node type of the parent node of the new
     * location, then the newly moved node is appended to the end of the child
     * node list.
     */
public void testCopyNodesOrderingSupportedByParent() throws RepositoryException {
    // test assumes that repositry supports Orderable Child Node Support (optional)
    String[] orderList = { nodeName1, nodeName2, nodeName3 };
    // copy node three times below a node and check the order
    for (int i = 0; i < orderList.length; i++) {
        workspaceW2.copy(workspace.getName(), node1.getPath(), node2.getPath() + "/" + orderList[i]);
    }
    // check regarding orderList if nodes are added at the end
    int cnt = 0;
    NodeIterator iter = node2.getNodes();
    while (iter.hasNext()) {
        Node n = iter.nextNode();
        assertTrue(n.getName().equals(orderList[cnt]));
        cnt++;
    }
}

56. WorkspaceCloneSameNameSibsTest#testCloneNodesOrderingSupportedByParent()

Project: jackrabbit
File: WorkspaceCloneSameNameSibsTest.java
/**
     * If ordering is supported by the node type of the parent node of the new
     * location, then the newly moved node is appended to the end of the child
     * node list.
     */
public void testCloneNodesOrderingSupportedByParent() throws RepositoryException {
    // test assumes that repositry supports Orderable Child Node Support (optional)
    String[] orderList = { nodeName1, nodeName2, nodeName3 };
    // copy node three times below a node and check the order
    for (int i = 0; i < orderList.length; i++) {
        workspaceW2.clone(workspace.getName(), node1.getPath(), node2.getPath() + "/" + orderList[i], true);
    }
    // check regarding orderList with the counter if nodes are added at the end
    int cnt = 0;
    NodeIterator iter = node2.getNodes();
    while (iter.hasNext()) {
        Node n = iter.nextNode();
        assertTrue(n.getName().equals(orderList[cnt]));
        cnt++;
    }
}

57. MergeShallowTest#testMergeShallow()

Project: jackrabbit
File: MergeShallowTest.java
public void testMergeShallow() throws RepositoryException {
    String oldP2 = nodeToMerge.getProperty(nodeName2 + "/" + propertyName1).getString();
    VersionManager vm2 = testRootNodeW2.getSession().getWorkspace().getVersionManager();
    NodeIterator iter = vm2.merge(nodeToMerge.getPath(), superuser.getWorkspace().getName(), true, true);
    if (iter.hasNext()) {
        StringBuffer failed = new StringBuffer();
        while (iter.hasNext()) {
            failed.append(iter.nextNode().getPath());
            failed.append(", ");
        }
        fail("Merge must not fail. failed nodes: " + failed);
        return;
    }
    String p1 = nodeToMerge.getProperty(propertyName1).getString();
    String p2 = nodeToMerge.getProperty(nodeName2 + "/" + propertyName1).getString();
    assertEquals("Shallow merge did not restore property on level 1.", newValue, p1);
    assertEquals("Shallow merge did restore property on level 2.", oldP2, p2);
}

58. MergeShallowTest#testMergeRecursive()

Project: jackrabbit
File: MergeShallowTest.java
public void testMergeRecursive() throws RepositoryException {
    VersionManager vm2 = testRootNodeW2.getSession().getWorkspace().getVersionManager();
    NodeIterator iter = vm2.merge(nodeToMerge.getPath(), superuser.getWorkspace().getName(), true, false);
    if (iter.hasNext()) {
        StringBuffer failed = new StringBuffer();
        while (iter.hasNext()) {
            failed.append(iter.nextNode().getPath());
            failed.append(", ");
        }
        fail("Merge must not fail. failed nodes: " + failed);
        return;
    }
    String p1 = nodeToMerge.getProperty(propertyName1).getString();
    String p2 = nodeToMerge.getProperty(nodeName2 + "/" + propertyName1).getString();
    assertEquals("Recursive merge did not restore property on level 1.", newValue, p1);
    assertEquals("Recursive merge did not restore property on level 2.", newValue, p2);
}

59. MergeActivityTest#testMergeActivity()

Project: jackrabbit
File: MergeActivityTest.java
public void testMergeActivity() throws RepositoryException {
    String p1 = testRootNodeW2.getProperty(nodeName1 + "/" + propertyName1).getString();
    String p2 = testRootNodeW2.getProperty(nodeName2 + "/" + propertyName1).getString();
    assertEquals("Cloned node has wrong property on node 1.", nodeName1, p1);
    assertEquals("Cloned node has wrong property on node 2.", nodeName2, p2);
    VersionManager vm2 = testRootNodeW2.getSession().getWorkspace().getVersionManager();
    NodeIterator iter = vm2.merge(activityNode);
    if (iter.hasNext()) {
        StringBuffer failed = new StringBuffer();
        while (iter.hasNext()) {
            failed.append(iter.nextNode().getPath());
            failed.append(", ");
        }
        fail("Merge must not fail. failed nodes: " + failed);
        return;
    }
    p1 = testRootNodeW2.getProperty(nodeName1 + "/" + propertyName1).getString();
    p2 = testRootNodeW2.getProperty(nodeName2 + "/" + propertyName1).getString();
    assertEquals("Activity merge did not restore property on node 1.", newValue, p1);
    assertEquals("Activity merge did not restore property on node 2.", newValue, p2);
}

60. TreeComparator#showTree()

Project: jackrabbit
File: TreeComparator.java
/**
     * Recursive display of source and target tree
     */
public void showTree(Node n, int level) throws RepositoryException {
    StringBuffer sb = new StringBuffer();
    for (int t = 0; t < level; t++) {
        sb.append("-");
    }
    sb.append(n.getName() + " ");
    sb.append(n.getPrimaryNodeType().getName() + " [ ");
    PropertyIterator pi = n.getProperties();
    while (pi.hasNext()) {
        Property p = (Property) pi.next();
        sb.append(p.getName() + " ");
    }
    sb.append("]");
    sc.log(sb.toString());
    NodeIterator ni = n.getNodes();
    while (ni.hasNext()) {
        showTree((Node) ni.next(), level + 1);
    }
}

61. XPathQueryLevel2Test#testFullTextSearch()

Project: jackrabbit
File: XPathQueryLevel2Test.java
/**
     * Test full-text search of the repository.<br>
     * <p>
     * For configuration description see {@link #setUpFullTextTest()}.
     */
public void testFullTextSearch() throws Exception {
    setUpFullTextTest();
    QueryResult result = execute(getFullTextStatement());
    // must be 1
    checkResult(result, 1);
    // evaluate result
    NodeIterator itr = result.getNodes();
    while (itr.hasNext()) {
        Value value = itr.nextNode().getProperty(propertyName1).getValue();
        if (value != null) {
            String fullText = value.getString();
            if (fullText.indexOf("cat") > 0) {
                fail("Search Text: full text search not correct, returned prohibited text");
            }
        }
    }
}

62. XPathPosIndexTest#docOrderTest()

Project: jackrabbit
File: XPathPosIndexTest.java
//-----------------------------< internal >---------------------------------
/**
     * Executes a statement, checks if the Result contains exactly one node with
     * <code>path</code>.
     *
     * @param stmt to be executed
     * @param path the path of the node in the query result.
     */
private void docOrderTest(Statement stmt, String path) throws RepositoryException, NotExecutableException {
    if (!isSupported(Repository.QUERY_XPATH_POS_INDEX)) {
        throw new NotExecutableException("Repository does not support document order on result set.");
    }
    int count = 0;
    // check precondition: at least 3 nodes
    for (NodeIterator it = testRootNode.getNodes(); it.hasNext(); it.nextNode()) {
        count++;
    }
    if (count < 3) {
        throw new NotExecutableException("Workspace does not contain enough content under: " + testRoot + ". At least 3 nodes are required for this test.");
    }
    QueryResult result = execute(stmt);
    checkResult(result, 1);
    assertEquals("Wrong result node.", path, result.getNodes().nextNode().getPath());
}

63. XPathDocOrderTest#docOrderTest()

Project: jackrabbit
File: XPathDocOrderTest.java
//-----------------------------< internal >---------------------------------
/**
     * Executes a statement, checks if the Result contains exactly one node with
     * <code>path</code>.
     *
     * @param stmt to be executed
     * @param path the path of the node in the query result.
     */
private void docOrderTest(Statement stmt, String path) throws RepositoryException, NotExecutableException {
    if (!isSupported(Repository.QUERY_XPATH_DOC_ORDER)) {
        throw new NotExecutableException("Repository does not support document order on result set.");
    }
    int count = 0;
    // check precondition: at least 3 nodes
    for (NodeIterator it = testRootNode.getNodes(); it.hasNext(); it.nextNode()) {
        count++;
    }
    if (count < 3) {
        throw new NotExecutableException("Workspace does not contain enough content under: " + testRoot + ". At least 3 nodes are required for this test.");
    }
    QueryResult result = execute(stmt);
    checkResult(result, 1);
    assertEquals("Wrong result node.", path, result.getNodes().nextNode().getPath());
}

64. QueryResultNodeIteratorTest#testNoSuchElementException()

Project: jackrabbit
File: QueryResultNodeIteratorTest.java
/**
     * Tests if a {@link java.util.NoSuchElementException} is thrown when {@link
     * javax.jcr.NodeIterator#nextNode()} is called and there are no more nodes
     * available.
     * @throws NotExecutableException 
     */
public void testNoSuchElementException() throws RepositoryException, NotExecutableException {
    NodeIterator it = execute(xpathRoot + "//*", qsXPATH).getNodes();
    while (it.hasNext()) {
        it.nextNode();
    }
    try {
        it.nextNode();
        fail("nextNode() must throw a NoSuchElementException when no nodes are available");
    } catch (NoSuchElementException e) {
    }
}

65. QueryResultNodeIteratorTest#testGetPosition()

Project: jackrabbit
File: QueryResultNodeIteratorTest.java
/**
     * Tests the method <code>NodeIterator.getPosition()</code>.
     */
public void testGetPosition() throws RepositoryException, NotExecutableException {
    QueryResult rs = execute(xpathRoot + "//*", qsXPATH);
    // getPosition initially returns 0
    NodeIterator it = rs.getNodes();
    assertEquals("Initial call to getPosition() must return 0.", 0, it.getPosition());
    // check getPosition while iterating
    int index = 0;
    while (it.hasNext()) {
        it.nextNode();
        assertEquals("Wrong position returned by getPosition()", ++index, it.getPosition());
    }
}

66. PropertyDefTest#traverse()

Project: jackrabbit
File: PropertyDefTest.java
// ---------------------------------< internal >----------------------------
/**
     * Traverses the node hierarchy and applies
     * {@link #checkMandatoryConstraint(javax.jcr.Node, javax.jcr.nodetype.NodeType)}
     * to all descendant nodes of <code>parentNode</code>.
     */
private void traverse(Node parentNode) throws RepositoryException {
    NodeIterator nodes = parentNode.getNodes();
    while (nodes.hasNext()) {
        Node node = nodes.nextNode();
        NodeType primeType = node.getPrimaryNodeType();
        checkMandatoryConstraint(node, primeType);
        NodeType mixins[] = node.getMixinNodeTypes();
        for (int i = 0; i < mixins.length; i++) {
            checkMandatoryConstraint(node, mixins[i]);
        }
        traverse(node);
    }
}

67. NodeTypeTest#locateNodeWithoutPrimaryItem()

Project: jackrabbit
File: NodeTypeTest.java
/**
     * Returns the first descendant of <code>node</code> without a primary item
     *
     * @param node
     * @return first node without primary item
     */
private Node locateNodeWithoutPrimaryItem(Node node) throws RepositoryException {
    try {
        node.getPrimaryItem();
    } catch (ItemNotFoundException e) {
        return node;
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node returnedNode = this.locateNodeWithoutPrimaryItem(nodes.nextNode());
        if (returnedNode != null) {
            return returnedNode;
        }
    }
    return null;
}

68. NodeDefTest#traverse()

Project: jackrabbit
File: NodeDefTest.java
//-----------------------< internal >---------------------------------------
/**
     * Traverses the node hierarchy and applies
     * {@link #checkMandatoryConstraint(javax.jcr.Node, javax.jcr.nodetype.NodeType)}
     * to all descendant nodes of <code>parentNode</code>.
     */
private void traverse(Node parentNode) throws RepositoryException {
    NodeIterator nodes = parentNode.getNodes();
    while (nodes.hasNext()) {
        Node node = nodes.nextNode();
        NodeType primaryType = node.getPrimaryNodeType();
        checkMandatoryConstraint(node, primaryType);
        NodeType mixins[] = node.getMixinNodeTypes();
        for (int i = 0; i < mixins.length; i++) {
            checkMandatoryConstraint(node, mixins[i]);
        }
        traverse(node);
    }
}

69. NodeReadMethodsTest#locateNodeWithSameNameSiblings()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Returns the first descendant of <code>node</code> which has same name
     * siblings.
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node with same name siblings
     */
private Node locateNodeWithSameNameSiblings(Node node) throws RepositoryException {
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node n = nodes.nextNode();
        NodeIterator nodes2 = node.getNodes(n.getName());
        int i = 0;
        while (nodes2.hasNext()) {
            nodes2.next();
            i++;
        }
        if (i > 1) {
            // node has same name siblings
            return n;
        } else {
            Node returnedNode = locateNodeWithSameNameSiblings(n);
            if (returnedNode != null) {
                return returnedNode;
            }
        }
    }
    return null;
}

70. NodeReadMethodsTest#locateNodeWithoutPrimaryItem()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Returns the first descendant of <code>node</code> which does not define a
     * primary item.
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node without a primary item
     */
private Node locateNodeWithoutPrimaryItem(Node node) throws RepositoryException {
    if (node.getPrimaryNodeType().getPrimaryItemName() == null) {
        return node;
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node n = locateNodeWithoutPrimaryItem(nodes.nextNode());
        if (n != null) {
            return n;
        }
    }
    return null;
}

71. NodeReadMethodsTest#locateNodeWithPrimaryItem()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Returns the first descendant of <code>node</code> which defines a primary
     * item.
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node with a primary item
     */
private Node locateNodeWithPrimaryItem(Node node) throws RepositoryException {
    if (node.getPrimaryNodeType().getPrimaryItemName() != null) {
        return node;
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node returnedNode = locateNodeWithPrimaryItem(nodes.nextNode());
        if (returnedNode != null) {
            return returnedNode;
        }
    }
    return null;
}

72. NodeReadMethodsTest#locateNodeWithReference()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Returns the first descendant of <code>node</code> which has a property of
     * type {@link javax.jcr.PropertyType#REFERENCE} set and is <b>not</b>
     * multivalued.
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node with a property of PropertType.REFERENCE
     */
private Node locateNodeWithReference(Node node) throws RepositoryException {
    PropertyIterator properties = node.getProperties();
    while (properties.hasNext()) {
        Property p = properties.nextProperty();
        if (p.getType() == PropertyType.REFERENCE && !p.getDefinition().isMultiple()) {
            return node;
        }
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node returnedNode = locateNodeWithReference(nodes.nextNode());
        if (returnedNode != null) {
            return returnedNode;
        }
    }
    return null;
}

73. NodeReadMethodsTest#locateNonReferenceableNode()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Returns the first descendant of <code>node</code> which is not of type
     * mix:referenceable.
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node which is not of type mix:referenceable
     */
private Node locateNonReferenceableNode(Node node) throws RepositoryException {
    if (!node.isNodeType(mixReferenceable)) {
        return node;
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node returnedNode = locateNonReferenceableNode(nodes.nextNode());
        if (returnedNode != null) {
            return returnedNode;
        }
    }
    return null;
}

74. NodeReadMethodsTest#locateReferenceableNode()

Project: jackrabbit
File: NodeReadMethodsTest.java
//-----------------------< internal >---------------------------------------
/**
     * Returns the first descendant of <code>node</code> which is of type
     * mix:referencable.
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node of type mix:referenceable
     */
private Node locateReferenceableNode(Node node) throws RepositoryException {
    if (node.isNodeType(mixReferenceable)) {
        return node;
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node returnedNode = locateReferenceableNode(nodes.nextNode());
        if (returnedNode != null) {
            return returnedNode;
        }
    }
    return null;
}

75. NodeReadMethodsTest#testHasNodes()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Test if hasNodes() returns true if any sub node exists or false if not.
     * Tested node: root
     */
public void testHasNodes() throws RepositoryException {
    Node node = testRootNode;
    NodeIterator nodes = node.getNodes();
    int i = 0;
    while (nodes.hasNext()) {
        nodes.nextNode();
        i++;
    }
    if (i == 0) {
        assertFalse("node.hasNodes() returns true although " + "no sub nodes existing", node.hasNodes());
    } else {
        assertTrue("node.hasNodes() returns false althuogh " + "sub nodes are existing", node.hasNodes());
    }
}

76. NodeReadMethodsTest#testHasNode()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Test if hasNode(String relPath) returns true if the required node exists
     * and false if it doesn't. Tested node: root
     */
public void testHasNode() throws NotExecutableException, RepositoryException {
    Node node = testRootNode;
    NodeIterator nodes = node.getNodes();
    StringBuffer notExistingNodeName = new StringBuffer();
    while (nodes.hasNext()) {
        Node n = nodes.nextNode();
        assertTrue("hasNode(String relPath) returns false although " + "node at relPath is existing", node.hasNode(n.getName()));
        notExistingNodeName.append(n.getName() + "X");
    }
    if (notExistingNodeName.toString().equals("")) {
        throw new NotExecutableException("Workspace does not have sufficient content for this test. " + "Root node must have at least one child node.");
    }
    assertFalse("hasNode(String relPath) returns true although " + "node at relPath is not existing", node.hasNode(notExistingNodeName.toString().replaceAll(":", "")));
}

77. NodeIteratorTest#testNoSuchElementException()

Project: jackrabbit
File: NodeIteratorTest.java
/**
     * Tests if a {@link java.util.NoSuchElementException} is thrown when {@link
     * javax.jcr.NodeIterator#nextNode()} is called and there are no more nodes
     * available.
     */
public void testNoSuchElementException() throws RepositoryException {
    NodeIterator iter = testRootNode.getNodes();
    while (iter.hasNext()) {
        iter.nextNode();
    }
    try {
        iter.nextNode();
        fail("nextNode() must throw a NoSuchElementException when no nodes are available");
    } catch (NoSuchElementException e) {
    }
}

78. NodeDiscoveringNodeTypesTest#locateNodeWithMixinNodeTypes()

Project: jackrabbit
File: NodeDiscoveringNodeTypesTest.java
//-----------------------< internal >---------------------------------------
/**
     * Returns the first descendant of <code>node</code> which defines mixin
     * node type(s).
     *
     * @param node <code>Node</code> to start traversal.
     * @return first node with mixin node type(s)
     */
private Node locateNodeWithMixinNodeTypes(Node node) throws RepositoryException {
    if (node.getMixinNodeTypes().length != 0) {
        return node;
    }
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        Node returnedNode = this.locateNodeWithMixinNodeTypes(nodes.nextNode());
        if (returnedNode != null) {
            return returnedNode;
        }
    }
    return null;
}

79. ItemSequence#getMinimal()

Project: jackrabbit
File: ItemSequence.java
/**
     * Returns the node amongst the child nodes of <code>node</code> whose key
     * is minimal wrt. {@link TreeManager#getOrder()}. Returns <code>null</code>
     * id either <code>node</code> has no child nodes or <code>node</code> is a
     * leaf (see {@link TreeManager#isLeaf(Node)}).
     */
protected final Node getMinimal(Node node) throws RepositoryException {
    if (!node.hasNodes() || treeManager.isLeaf(node)) {
        return null;
    }
    // Search for minimal key in the nodes children
    // todo performance: for ordered nodes use binary search
    NodeIterator childNodes = node.getNodes();
    Node p = childNodes.nextNode();
    String minKey = p.getName();
    while (childNodes.hasNext()) {
        Node n = childNodes.nextNode();
        if (order.compare(n.getName(), minKey) < 0) {
            p = n;
            minKey = p.getName();
        }
    }
    return p;
}

80. ItemSequence#getSuccessor()

Project: jackrabbit
File: ItemSequence.java
/**
     * Returns the successor node for the given
     * <code>key</key>. That is the node
     * whose key directly succeeds the passed <code>key</code> in the order
     * determined by {@link TreeManager#getOrder()}. There are two cases:
     * <ul>
     * <li>A node with the given <code>key</code> is mapped: then that node is
     * returned.</li>
     * <li>A node with the given <code>key</code> is not mapped: the the node
     * where that would contain that key if present is returned.</li>
     * </ul>
     */
protected final Node getSuccessor(Node node, String key) throws RepositoryException {
    if (!node.hasNodes() || treeManager.isLeaf(node)) {
        return null;
    }
    // Shortcut for exact match
    try {
        return node.getNode(key);
    } catch (PathNotFoundException ignore) {
    }
    // Search for direct successor of key in the nodes children
    // todo performance: for ordered nodes use binary search
    NodeIterator childNodes = node.getNodes();
    Node s = null;
    while (childNodes.hasNext()) {
        Node n = childNodes.nextNode();
        String childKey = n.getName();
        if (order.compare(key, childKey) < 0 && (s == null || order.compare(childKey, s.getName()) < 0)) {
            s = n;
        }
    }
    return s;
}

81. ItemSequence#getPredecessor()

Project: jackrabbit
File: ItemSequence.java
/**
     * Returns the direct predecessor of <code>key</code> amongst
     * <code>node</code>'s child nodes wrt. to {@link TreeManager#getOrder()}.
     * Returns <code>null</code> if either <code>node</code> has no child nodes
     * or <code>node</code> is a leaf (see {@link TreeManager#isLeaf(Node)}) or
     * <code>key</code> is smaller than all the keys of all child nodes of
     * <code>node</code>.
     */
protected final Node getPredecessor(Node node, String key) throws RepositoryException {
    if (!node.hasNodes() || treeManager.isLeaf(node)) {
        return null;
    }
    // Shortcut for exact match
    try {
        return node.getNode(key);
    } catch (PathNotFoundException ignore) {
    }
    // Search for direct predecessor of key in the nodes children
    // todo performance: for ordered nodes use binary search
    NodeIterator childNodes = node.getNodes();
    Node p = null;
    while (childNodes.hasNext()) {
        Node n = childNodes.nextNode();
        String childKey = n.getName();
        if (order.compare(key, childKey) > 0 && (p == null || order.compare(childKey, p.getName()) > 0)) {
            p = n;
        }
    }
    return p;
}

82. DerefTest#testDerefToVersionNode()

Project: jackrabbit
File: DerefTest.java
/**
     * Checks if jcr:deref works when dereferencing into the version storage.
     */
public void testDerefToVersionNode() throws RepositoryException {
    Node referenced = testRootNode.addNode(nodeName1);
    referenced.addMixin(mixVersionable);
    testRootNode.save();
    Version version = referenced.checkin();
    Node referencedVersionNode = version.getNode(jcrFrozenNode);
    Node referencer = testRootNode.addNode(nodeName2);
    referencer.setProperty(propertyName1, referencedVersionNode);
    testRootNode.save();
    String query = "/" + testRoot + "/*[@" + propertyName1 + "]/jcr:deref(@" + propertyName1 + ",'*')";
    QueryManager qm = superuser.getWorkspace().getQueryManager();
    Query q = qm.createQuery(query, Query.XPATH);
    QueryResult qr = q.execute();
    NodeIterator ni = qr.getNodes();
    assertEquals("Must find one result in query", 1, ni.getSize());
    while (ni.hasNext()) {
        Node node = (Node) ni.next();
        assertTrue(node.getProperty("jcr:frozenUuid").getString().equals(referenced.getUUID()));
    }
}

83. VirtualNodeTypeStateManager#recursiveRemove()

Project: jackrabbit
File: VirtualNodeTypeStateManager.java
/**
     * Adds a subtree of itemstates as 'removed' to a list of events
     *
     * @param events
     * @param parent
     * @param node
     * @throws RepositoryException
     */
private void recursiveRemove(List<EventState> events, NodeImpl parent, NodeImpl node) throws RepositoryException {
    events.add(EventState.childNodeRemoved(parent.getNodeId(), parent.getPrimaryPath(), node.getNodeId(), node.getPrimaryPath().getLastElement(), ((NodeTypeImpl) parent.getPrimaryNodeType()).getQName(), parent.getMixinTypeNames(), node.getSession()));
    NodeIterator niter = node.getNodes();
    while (niter.hasNext()) {
        NodeImpl n = (NodeImpl) niter.nextNode();
        recursiveRemove(events, node, n);
    }
}

84. ListTreeCommand#addChildren()

Project: sling
File: ListTreeCommand.java
private void addChildren(ResourceProxy parent, Node node, int remainingLevels) throws RepositoryException {
    if (remainingLevels < 0) {
        // paranoia check
        throw new IllegalArgumentException("remainingLevels must be >=0, not: " + remainingLevels);
    }
    final long start = System.currentTimeMillis();
    NodeIterator nodes = node.getNodes();
    final long end = System.currentTimeMillis();
    log("ListTreeCommand.child -> " + node.getPath(), start, end);
    while (nodes.hasNext()) {
        Node childNode = nodes.nextNode();
        // TODO - this should not be needed if we obey the vlt filters
        if (childNode.getPath().equals("/jcr:system")) {
            continue;
        }
        final ResourceProxy childResourceProxy = nodeToResource(childNode);
        parent.addChild(childResourceProxy);
        if (remainingLevels > 0) {
            addChildren(childResourceProxy, childNode, remainingLevels - 1);
        }
    }
}

85. ListChildrenCommand#execute0()

Project: sling
File: ListChildrenCommand.java
@Override
protected ResourceProxy execute0(Session session) throws RepositoryException {
    Node node = session.getNode(getPath());
    NodeIterator nodes = node.getNodes();
    ResourceProxy parent = nodeToResource(node);
    while (nodes.hasNext()) {
        Node childNode = nodes.nextNode();
        // TODO - this should not be needed if we obey the vlt filters
        if (childNode.getPath().equals("/jcr:system")) {
            continue;
        }
        parent.addChild(nodeToResource(childNode));
    }
    return parent;
}

86. MockSessionTest#testRootGetNodes()

Project: sling
File: MockSessionTest.java
@Test
public void testRootGetNodes() throws RepositoryException {
    Session s = MockJcr.newSession();
    Node root = s.getRootNode();
    root.addNode("node1");
    root.addNode("node2");
    int countChildren = 0;
    NodeIterator iter = s.getRootNode().getNodes();
    while (iter.hasNext()) {
        iter.next();
        countChildren++;
    }
    assertEquals(2, countChildren);
}

87. WatchedFolder#scanNode()

Project: sling
File: WatchedFolder.java
private void scanNode(final Node folder, final ScanResult result, final Set<String> resourcesSeen) throws RepositoryException {
    final NodeIterator it = folder.getNodes();
    while (it.hasNext()) {
        final Node n = it.nextNode();
        boolean processed = false;
        for (JcrInstaller.NodeConverter nc : converters) {
            final InstallableResource r = nc.convertNode(n, priority);
            if (r != null) {
                processed = true;
                resourcesSeen.add(r.getId());
                final String oldDigest = digests.get(r.getId());
                if (r.getDigest().equals(oldDigest)) {
                    logger.debug("Digest didn't change, ignoring " + r);
                } else {
                    result.toAdd.add(r);
                }
                break;
            }
        }
        if (!processed) {
            this.scanNode(n, result, resourcesSeen);
        }
    }
}

88. JcrInstaller#findPathsUnderNode()

Project: sling
File: JcrInstaller.java
/**
     * Add n to result if it is a folder that we must watch, and recurse into its children
     * to do the same.
     */
void findPathsUnderNode(final InstallerConfig cfg, final Session session, final Node n) throws RepositoryException {
    final String path = n.getPath();
    final int priority = cfg.getFolderNameFilter().getPriority(path);
    if (priority > 0) {
        cfg.addWatchedFolder(new WatchedFolder(session, path, priority, cfg.getConverters()));
    }
    final int depth = path.split("/").length;
    if (depth > cfg.getMaxWatchedFolderDepth()) {
        logger.debug("Not recursing into {} due to maxWatchedFolderDepth={}", path, cfg.getMaxWatchedFolderDepth());
        return;
    }
    final NodeIterator it = n.getNodes();
    while (it.hasNext()) {
        findPathsUnderNode(cfg, session, it.nextNode());
    }
}

89. HtmlContentRenderer#renderChildNodes()

Project: sling
File: HtmlContentRenderer.java
protected void renderChildNodes(PrintWriter pw, Node parent) throws RepositoryException {
    pw.println("<div class='childnodes'>");
    final String prefix = parent.getName() + "/";
    final NodeIterator it = parent.getNodes();
    while (it.hasNext()) {
        final Node kid = it.nextNode();
        pw.print("<a href='");
        pw.print(prefix);
        pw.print(kid.getName());
        pw.print("'>");
        pw.print(kid.getName());
        pw.println("</a>");
    }
    pw.println("</div>");
}

90. WritePipe#writeTree()

Project: sling
File: WritePipe.java
/**
     * write the configured tree at the target resource, creating each node if needed, copying values.
     * @param conf
     * @return
     */
private void writeTree(Node conf, Resource target) throws RepositoryException {
    copyProperties(resolver.getResource(conf.getPath()), target);
    NodeIterator childrenConf = conf.getNodes();
    if (childrenConf.hasNext()) {
        Node targetNode = target.adaptTo(Node.class);
        while (childrenConf.hasNext()) {
            Node childConf = childrenConf.nextNode();
            String name = childConf.getName();
            logger.info("dubbing {} at {}", conf.getPath(), target.getPath());
            if (!isDryRun()) {
                Node childTarget = targetNode.hasNode(name) ? targetNode.getNode(name) : targetNode.addNode(name, childConf.getPrimaryNodeType().getName());
                writeTree(childConf, resolver.getResource(childTarget.getPath()));
            }
        }
    }
}

91. JcrResourceBundleTest#cleanRepository()

Project: sling
File: JcrResourceBundleTest.java
public void cleanRepository() throws Exception {
    NodeIterator nodes = getSession().getRootNode().getNodes();
    while (nodes.hasNext()) {
        Node node = nodes.nextNode();
        if (!node.getDefinition().isProtected() && !node.getDefinition().isMandatory()) {
            try {
                node.remove();
            } catch (RepositoryException e) {
                log.error("Test clean repo: Cannot remove node: " + node.getPath(), e);
            }
        }
    }
    getSession().save();
}

92. MSOfficeMetadataSequencerTest#shouldSequenceAnotherExcelFiles()

Project: modeshape
File: MSOfficeMetadataSequencerTest.java
@Test
public void shouldSequenceAnotherExcelFiles() throws Exception {
    createNodeWithContentFromFile("msoffice_file.xls", "msoffice_file.xls");
    Node outputNode = getOutputNode(rootNode, "msoffice_file.xls/" + METADATA_NODE);
    assertNotNull(outputNode);
    assertEquals(METADATA_NODE, outputNode.getPrimaryNodeType().getName());
    assertEquals(MimeTypeConstants.MICROSOFT_EXCEL, outputNode.getProperty(JCR_MIME_TYPE).getString());
    assertMetadata(outputNode);
    NodeIterator sheetsIterator = outputNode.getNodes();
    assertEquals(EXCEL_SHEETS.size(), sheetsIterator.getSize());
    while (sheetsIterator.hasNext()) {
        Node sheet = sheetsIterator.nextNode();
        assertEquals(EXCEL_SHEET_NODE, sheet.getPrimaryNodeType().getName());
        String sheetName = sheet.getProperty(SHEET_NAME).getString();
        assertTrue(EXCEL_SHEETS.containsKey(sheetName));
        String text = EXCEL_SHEETS.get(sheetName);
        if (text != null) {
            assertTrue(sheet.getProperty(TEXT).getString().contains(text));
        }
    }
}

93. MSOfficeMetadataSequencerTest#shouldSequenceExcelFiles()

Project: modeshape
File: MSOfficeMetadataSequencerTest.java
@Test
public void shouldSequenceExcelFiles() throws Exception {
    createNodeWithContentFromFile("excel.xls", "excel.xls");
    Node outputNode = getOutputNode(rootNode, "excel.xls/" + METADATA_NODE);
    assertNotNull(outputNode);
    assertEquals(METADATA_NODE, outputNode.getPrimaryNodeType().getName());
    assertEquals(MimeTypeConstants.MICROSOFT_EXCEL, outputNode.getProperty(JCR_MIME_TYPE).getString());
    assertMetadata(outputNode);
    NodeIterator sheetsIterator = outputNode.getNodes();
    assertEquals(EXCEL_SHEETS.size(), sheetsIterator.getSize());
    while (sheetsIterator.hasNext()) {
        Node sheet = sheetsIterator.nextNode();
        assertEquals(EXCEL_SHEET_NODE, sheet.getPrimaryNodeType().getName());
        String sheetName = sheet.getProperty(SHEET_NAME).getString();
        assertTrue(EXCEL_SHEETS.containsKey(sheetName));
        String text = EXCEL_SHEETS.get(sheetName);
        if (text != null) {
            assertTrue(sheet.getProperty(TEXT).getString().contains(text));
        }
    }
}

94. MSOfficeMetadataSequencerTest#shouldSequenceWordFiles()

Project: modeshape
File: MSOfficeMetadataSequencerTest.java
@Test
public void shouldSequenceWordFiles() throws Exception {
    createNodeWithContentFromFile("word.doc", "word.doc");
    Node outputNode = getOutputNode(rootNode, "word.doc/" + METADATA_NODE);
    assertNotNull(outputNode);
    assertEquals(METADATA_NODE, outputNode.getPrimaryNodeType().getName());
    String mimeType = outputNode.getProperty(JCR_MIME_TYPE).getString();
    assertEquals(MimeTypeConstants.MICROSOFT_WORD.equals(mimeType) || MimeTypeConstants.MICROSOFT_APPLICATION_MS_WORD.equals(mimeType), true);
    assertMetadata(outputNode);
    NodeIterator headingsIterator = outputNode.getNodes();
    assertEquals(WORD_HEADINGS.size(), headingsIterator.getSize());
    while (headingsIterator.hasNext()) {
        Node heading = headingsIterator.nextNode();
        assertEquals(HEADING_NODE, heading.getPrimaryNodeType().getName());
        Integer headingLevel = WORD_HEADINGS.get(heading.getProperty(HEADING_NAME).getString());
        assertEquals(headingLevel.longValue(), heading.getProperty(HEADING_LEVEL).getLong());
    }
}

95. OracleDdlSequencerTest#shouldParseUnterminatedStatements()

Project: modeshape
File: OracleDdlSequencerTest.java
@Test
public void shouldParseUnterminatedStatements() throws Exception {
    Node statementsNode = sequenceDdl("ddl/dialect/oracle/unterminatedStatements.ddl");
    verifyPrimaryType(statementsNode, NT_UNSTRUCTURED);
    verifyProperty(statementsNode, PARSER_ID, "ORACLE");
    assertThat(statementsNode.getNodes().getSize(), is(3L));
    final NodeIterator itr = statementsNode.getNodes();
    while (itr.hasNext()) {
        verifyMixinType(itr.nextNode(), StandardDdlLexicon.TYPE_CREATE_TABLE_STATEMENT);
    }
}

96. JcrTools#onEachNode()

Project: modeshape
File: JcrTools.java
/**
     * Execute the supplied operation on each node in the workspace accessible by the supplied session.
     * 
     * @param session the session
     * @param includeSystemNodes true if all nodes under "/jcr:system" should be included, or false if the system nodes should be
     *        excluded
     * @param operation the operation
     * @throws Exception the exception thrown by the repository or the operation
     */
public void onEachNode(Session session, boolean includeSystemNodes, NodeOperation operation) throws Exception {
    Node node = session.getRootNode();
    operation.run(node);
    NodeIterator iter = node.getNodes();
    while (iter.hasNext()) {
        Node child = iter.nextNode();
        if (!includeSystemNodes && child.getName().equals("jcr:system"))
            continue;
        operation.run(child);
        onEachNodeBelow(child, operation);
    }
}

97. ModeShapeTckTest#checkinRecursively()

Project: modeshape
File: ModeShapeTckTest.java
protected void checkinRecursively(Node node, VersionManager vm) throws RepositoryException {
    String path = node.getPath();
    if (node.isNodeType("mix:versionable") && vm.isCheckedOut(path)) {
        try {
            vm.checkin(path);
        } catch (VersionException e) {
            node.remove();
            return;
        }
    }
    NodeIterator iter = node.getNodes();
    while (iter.hasNext()) {
        checkinRecursively(iter.nextNode(), vm);
    }
}

98. JcrUnorderedCollectionsTest#afterEach()

Project: modeshape
File: JcrUnorderedCollectionsTest.java
@Override
public void afterEach() throws Exception {
    NodeIterator nodeIterator = session.getRootNode().getNodes();
    while (nodeIterator.hasNext()) {
        Node node = nodeIterator.nextNode();
        if (!JcrLexicon.SYSTEM.getString().equals(node.getName())) {
            node.remove();
        }
    }
    session.save();
    super.afterEach();
}

99. NodeReadMethodsTest#setUp()

Project: jackrabbit
File: NodeReadMethodsTest.java
/**
     * Sets up the fixture for this test.
     */
protected void setUp() throws Exception {
    isReadOnly = true;
    super.setUp();
    session = getHelper().getReadOnlySession();
    testRootNode = session.getRootNode().getNode(testPath);
    NodeIterator nodes = testRootNode.getNodes();
    try {
        childNode = nodes.nextNode();
    } catch (NoSuchElementException e) {
    }
}

100. NodeOrderableChildNodesTest#prepareTest()

Project: jackrabbit
File: NodeOrderableChildNodesTest.java
/**
     * Sets up the test content needed for the test cases.
     */
private void prepareTest() throws RepositoryException {
    // get root node
    Node defaultRootNode = (Node) superuser.getItem(testRootNode.getPath());
    // create testNode
    parentNode = defaultRootNode.addNode(nodeName1, getProperty("nodetype2"));
    // add child node
    Node firstNode = parentNode.addNode(nodeName2, getProperty("nodetype3"));
    // add a second child node
    Node secondNode = parentNode.addNode(nodeName3, getProperty("nodetype3"));
    // save the new nodes
    superuser.save();
    // get child node refs
    NodeIterator it = parentNode.getNodes();
    initialFirstNode = it.nextNode();
    initialSecondNode = it.nextNode();
    // first lets test if the nodes have been added in the right order
    assertTrue("Child nodes are not added in proper order ", firstNode.isSame(initialFirstNode));
    assertTrue("Child nodes are not added in proper order ", secondNode.isSame(initialSecondNode));
}