1 package org.apache.maven.shared.dependency.tree.filter;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.Collections;
23 import java.util.Iterator;
24 import java.util.List;
25
26 import org.apache.maven.shared.dependency.tree.DependencyNode;
27
28 /**
29 * A dependency node filter than only accepts nodes that are ancestors of, or equal to, a given list of nodes.
30 *
31 * @author <a href="mailto:markhobson@gmail.com">Mark Hobson</a>
32 * @version $Id: AncestorOrSelfDependencyNodeFilter.java 661727 2008-05-30 14:21:49Z bentmann $
33 * @since 1.1
34 */
35 public class AncestorOrSelfDependencyNodeFilter implements DependencyNodeFilter
36 {
37
38
39 /**
40 * The list of nodes that this filter accepts ancestors-or-self of.
41 */
42 private final List descendantNodes;
43
44
45
46 public AncestorOrSelfDependencyNodeFilter( DependencyNode descendantNode )
47 {
48 this( Collections.singletonList( descendantNode ) );
49 }
50
51 /**
52 * Creates a dependency node filter that only accepts nodes that are ancestors of, or equal to, the specified list
53 * of nodes.
54 *
55 * @param descendantNodes
56 * the list of nodes to accept ancestors-or-self of
57 */
58 public AncestorOrSelfDependencyNodeFilter( List descendantNodes )
59 {
60 this.descendantNodes = descendantNodes;
61 }
62
63
64
65 /**
66 * {@inheritDoc}
67 */
68 public boolean accept( DependencyNode node )
69 {
70 boolean accept = false;
71
72 for ( Iterator iterator = descendantNodes.iterator(); !accept && iterator.hasNext(); )
73 {
74 DependencyNode descendantNode = (DependencyNode) iterator.next();
75
76 if ( isAncestorOrSelf( node, descendantNode ) )
77 {
78 accept = true;
79 }
80 }
81
82 return accept;
83 }
84
85
86
87 /**
88 * Gets whether the first dependency node is an ancestor-or-self of the second.
89 *
90 * @param ancestorNode
91 * the ancestor-or-self dependency node
92 * @param descendantNode
93 * the dependency node to test
94 * @return <code>true</code> if <code>ancestorNode</code> is an ancestor, or equal to,
95 * <code>descendantNode</code>
96 */
97 private boolean isAncestorOrSelf( DependencyNode ancestorNode, DependencyNode descendantNode )
98 {
99 boolean ancestor = false;
100
101 while ( !ancestor && descendantNode != null )
102 {
103 ancestor = ancestorNode.equals( descendantNode );
104
105 descendantNode = descendantNode.getParent();
106 }
107
108 return ancestor;
109 }
110 }