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.commons.lang3.Validate;
29 import org.apache.maven.execution.ProjectDependencyGraph;
30 import org.apache.maven.project.DuplicateProjectException;
31 import org.apache.maven.project.MavenProject;
32 import org.apache.maven.project.ProjectSorter;
33 import org.codehaus.plexus.util.dag.CycleDetectedException;
34
35
36
37
38
39
40 public class DefaultProjectDependencyGraph
41 implements ProjectDependencyGraph
42 {
43
44 private ProjectSorter sorter;
45
46
47
48
49
50
51
52
53 public DefaultProjectDependencyGraph( Collection<MavenProject> projects )
54 throws CycleDetectedException, DuplicateProjectException
55 {
56 this.sorter = new ProjectSorter( projects );
57 }
58
59 public List<MavenProject> getSortedProjects()
60 {
61 return new ArrayList<>( sorter.getSortedProjects() );
62 }
63
64 public List<MavenProject> getDownstreamProjects( MavenProject project, boolean transitive )
65 {
66 Validate.notNull( project, "project cannot be null" );
67
68 Set<String> projectIds = new HashSet<>();
69
70 getDownstreamProjects( ProjectSorter.getId( project ), projectIds, transitive );
71
72 return getSortedProjects( projectIds );
73 }
74
75 private void getDownstreamProjects( String projectId, Set<String> projectIds, boolean transitive )
76 {
77 for ( String id : sorter.getDependents( projectId ) )
78 {
79 if ( projectIds.add( id ) && transitive )
80 {
81 getDownstreamProjects( id, projectIds, transitive );
82 }
83 }
84 }
85
86 public List<MavenProject> getUpstreamProjects( MavenProject project, boolean transitive )
87 {
88 Validate.notNull( project, "project cannot be null" );
89
90 Set<String> projectIds = new HashSet<>();
91
92 getUpstreamProjects( ProjectSorter.getId( project ), projectIds, transitive );
93
94 return getSortedProjects( projectIds );
95 }
96
97 private void getUpstreamProjects( String projectId, Collection<String> projectIds, boolean transitive )
98 {
99 for ( String id : sorter.getDependencies( projectId ) )
100 {
101 if ( projectIds.add( id ) && transitive )
102 {
103 getUpstreamProjects( id, projectIds, transitive );
104 }
105 }
106 }
107
108 private List<MavenProject> getSortedProjects( Set<String> projectIds )
109 {
110 List<MavenProject> result = new ArrayList<>( projectIds.size() );
111
112 for ( MavenProject mavenProject : sorter.getSortedProjects() )
113 {
114 if ( projectIds.contains( ProjectSorter.getId( mavenProject ) ) )
115 {
116 result.add( mavenProject );
117 }
118 }
119
120 return result;
121 }
122
123 @Override
124 public String toString()
125 {
126 return sorter.getSortedProjects().toString();
127 }
128
129 }