1 package org.apache.maven.graph;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Set;
27
28 import org.apache.maven.execution.ProjectDependencyGraph;
29 import org.apache.maven.project.DuplicateProjectException;
30 import org.apache.maven.project.MavenProject;
31 import org.apache.maven.project.ProjectSorter;
32 import org.codehaus.plexus.util.dag.CycleDetectedException;
33
34
35
36
37
38
39 public class DefaultProjectDependencyGraph
40 implements ProjectDependencyGraph
41 {
42
43 private ProjectSorter sorter;
44
45
46
47
48
49
50
51
52 public DefaultProjectDependencyGraph( Collection<MavenProject> projects )
53 throws CycleDetectedException, DuplicateProjectException
54 {
55 this.sorter = new ProjectSorter( projects );
56 }
57
58 public List<MavenProject> getSortedProjects()
59 {
60 return new ArrayList<MavenProject>( sorter.getSortedProjects() );
61 }
62
63 public List<MavenProject> getDownstreamProjects( MavenProject project, boolean transitive )
64 {
65 if ( project == null )
66 {
67 throw new IllegalArgumentException( "project missing" );
68 }
69
70 Set<String> projectIds = new HashSet<String>();
71
72 getDownstreamProjects( ProjectSorter.getId( project ), projectIds, transitive );
73
74 return getSortedProjects( projectIds );
75 }
76
77 private void getDownstreamProjects( String projectId, Set<String> projectIds, boolean transitive )
78 {
79 for ( String id : sorter.getDependents( projectId ) )
80 {
81 if ( projectIds.add( id ) && transitive )
82 {
83 getDownstreamProjects( id, projectIds, transitive );
84 }
85 }
86 }
87
88 public List<MavenProject> getUpstreamProjects( MavenProject project, boolean transitive )
89 {
90 if ( project == null )
91 {
92 throw new IllegalArgumentException( "project missing" );
93 }
94
95 Set<String> projectIds = new HashSet<String>();
96
97 getUpstreamProjects( ProjectSorter.getId( project ), projectIds, transitive );
98
99 return getSortedProjects( projectIds );
100 }
101
102 private void getUpstreamProjects( String projectId, Collection<String> projectIds, boolean transitive )
103 {
104 for ( String id : sorter.getDependencies( projectId ) )
105 {
106 if ( projectIds.add( id ) && transitive )
107 {
108 getUpstreamProjects( id, projectIds, transitive );
109 }
110 }
111 }
112
113 private List<MavenProject> getSortedProjects( Set<String> projectIds )
114 {
115 List<MavenProject> result = new ArrayList<MavenProject>( projectIds.size() );
116
117 for ( MavenProject mavenProject : sorter.getSortedProjects() )
118 {
119 if ( projectIds.contains( ProjectSorter.getId( mavenProject ) ) )
120 {
121 result.add( mavenProject );
122 }
123 }
124
125 return result;
126 }
127
128 @Override
129 public String toString()
130 {
131 return sorter.getSortedProjects().toString();
132 }
133
134 }