View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.api.services;
20  
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.Collections;
24  import java.util.List;
25  import java.util.Objects;
26  import java.util.Optional;
27  import java.util.function.Predicate;
28  
29  import org.apache.maven.api.Artifact;
30  import org.apache.maven.api.DependencyCoordinates;
31  import org.apache.maven.api.JavaPathType;
32  import org.apache.maven.api.PathScope;
33  import org.apache.maven.api.PathType;
34  import org.apache.maven.api.Project;
35  import org.apache.maven.api.RemoteRepository;
36  import org.apache.maven.api.Session;
37  import org.apache.maven.api.SourceRoot;
38  import org.apache.maven.api.Version;
39  import org.apache.maven.api.annotations.Experimental;
40  import org.apache.maven.api.annotations.Immutable;
41  import org.apache.maven.api.annotations.Nonnull;
42  import org.apache.maven.api.annotations.NotThreadSafe;
43  import org.apache.maven.api.annotations.Nullable;
44  
45  import static java.util.Objects.requireNonNull;
46  
47  /**
48   * A request to collect the transitive dependencies and to build a dependency graph from them. There are three ways to
49   * create a dependency graph. First, only the root dependency can be given. Second, a root dependency and direct
50   * dependencies can be specified in which case the specified direct dependencies are merged with the direct dependencies
51   * retrieved from the artifact descriptor of the root dependency. And last, only direct dependencies can be specified in
52   * which case the root node of the resulting graph has no associated dependency.
53   *
54   * @since 4.0.0
55   */
56  @Experimental
57  @Immutable
58  public interface DependencyResolverRequest extends RepositoryAwareRequest {
59  
60      enum RequestType {
61          COLLECT,
62          FLATTEN,
63          RESOLVE
64      }
65  
66      @Nonnull
67      RequestType getRequestType();
68  
69      @Nonnull
70      Optional<Project> getProject();
71  
72      @Nonnull
73      Optional<Artifact> getRootArtifact();
74  
75      @Nonnull
76      Optional<DependencyCoordinates> getRoot();
77  
78      @Nonnull
79      Collection<DependencyCoordinates> getDependencies();
80  
81      @Nonnull
82      Collection<DependencyCoordinates> getManagedDependencies();
83  
84      boolean getVerbose();
85  
86      @Nonnull
87      PathScope getPathScope();
88  
89      /**
90       * Returns a filter for the types of path (class-path, module-path, …) accepted by the tool.
91       * For example, if a Java tools accepts only class-path elements, then the filter should return
92       * {@code true} for {@link JavaPathType#CLASSES} and {@code false} for {@link JavaPathType#MODULES}.
93       * If no filter is explicitly set, then the default is a filter accepting everything.
94       *
95       * @return a filter for the types of path (class-path, module-path, …) accepted by the tool
96       */
97      @Nullable
98      Predicate<PathType> getPathTypeFilter();
99  
100     /**
101      * Returns the version of the platform where the code will be executed.
102      * It should be the highest value of the {@code <targetVersion>} elements
103      * inside the {@code <source>} elements of a <abbr>POM</abbr> file.
104      *
105      * <h4>Application to Java</h4>
106      * In the context of a Java project, this is the value given to the {@code --release} compiler option.
107      * This value can determine whether a dependency will be placed on the class-path or on the module-path.
108      * For example, if the {@code module-info.class} entry of a <abbr>JAR</abbr> file exists only in the
109      * {@code META-INF/versions/17/} sub-directory, then the default location of that dependency will be
110      * the module-path only if the {@code --release} option is equal or greater than 17.
111      *
112      * <p>If this value is not provided, then the default value in the context of Java projects
113      * is the Java version on which Maven is running, as given by {@link Runtime#version()}.</p>
114      *
115      * @return version of the platform where the code will be executed, or {@code null} for default
116      *
117      * @see SourceRoot#targetVersion()
118      */
119     @Nullable
120     Version getTargetVersion();
121 
122     @Nonnull
123     static DependencyResolverRequestBuilder builder() {
124         return new DependencyResolverRequestBuilder();
125     }
126 
127     @Nonnull
128     static DependencyResolverRequest build(Session session, RequestType requestType, Artifact rootArtifact) {
129         return build(session, requestType, rootArtifact, PathScope.MAIN_RUNTIME);
130     }
131 
132     @Nonnull
133     static DependencyResolverRequest build(
134             Session session, RequestType requestType, Artifact rootArtifact, PathScope scope) {
135         return new DependencyResolverRequestBuilder()
136                 .session(session)
137                 .requestType(requestType)
138                 .rootArtifact(rootArtifact)
139                 .pathScope(scope)
140                 .build();
141     }
142 
143     @Nonnull
144     static DependencyResolverRequest build(Session session, RequestType requestType, Project project) {
145         return build(session, requestType, project, PathScope.MAIN_RUNTIME);
146     }
147 
148     @Nonnull
149     static DependencyResolverRequest build(Session session, RequestType requestType, Project project, PathScope scope) {
150         return new DependencyResolverRequestBuilder()
151                 .session(session)
152                 .requestType(requestType)
153                 .project(project)
154                 .pathScope(scope)
155                 .build();
156     }
157 
158     @Nonnull
159     static DependencyResolverRequest build(Session session, RequestType requestType, DependencyCoordinates dependency) {
160         return build(session, requestType, dependency, PathScope.MAIN_RUNTIME);
161     }
162 
163     @Nonnull
164     static DependencyResolverRequest build(
165             Session session, RequestType requestType, DependencyCoordinates dependency, PathScope scope) {
166         return new DependencyResolverRequestBuilder()
167                 .session(session)
168                 .requestType(requestType)
169                 .dependency(dependency)
170                 .pathScope(scope)
171                 .build();
172     }
173 
174     @Nonnull
175     static DependencyResolverRequest build(
176             Session session, RequestType requestType, List<DependencyCoordinates> dependencies) {
177         return build(session, requestType, dependencies, PathScope.MAIN_RUNTIME);
178     }
179 
180     @Nonnull
181     static DependencyResolverRequest build(
182             Session session, RequestType requestType, List<DependencyCoordinates> dependencies, PathScope scope) {
183         return new DependencyResolverRequestBuilder()
184                 .session(session)
185                 .requestType(requestType)
186                 .dependencies(dependencies)
187                 .pathScope(scope)
188                 .build();
189     }
190 
191     @NotThreadSafe
192     class DependencyResolverRequestBuilder {
193 
194         Session session;
195         RequestTrace trace;
196         RequestType requestType;
197         Project project;
198         Artifact rootArtifact;
199         DependencyCoordinates root;
200         List<DependencyCoordinates> dependencies = Collections.emptyList();
201         List<DependencyCoordinates> managedDependencies = Collections.emptyList();
202         boolean verbose;
203         PathScope pathScope;
204         Predicate<PathType> pathTypeFilter;
205         Version targetVersion;
206         List<RemoteRepository> repositories;
207 
208         DependencyResolverRequestBuilder() {}
209 
210         @Nonnull
211         public DependencyResolverRequestBuilder session(@Nonnull Session session) {
212             this.session = session;
213             return this;
214         }
215 
216         @Nonnull
217         public DependencyResolverRequestBuilder trace(RequestTrace trace) {
218             this.trace = trace;
219             return this;
220         }
221 
222         @Nonnull
223         public DependencyResolverRequestBuilder requestType(@Nonnull RequestType requestType) {
224             this.requestType = requestType;
225             return this;
226         }
227 
228         @Nonnull
229         public DependencyResolverRequestBuilder project(@Nullable Project project) {
230             this.project = project;
231             return this;
232         }
233 
234         /**
235          * Sets the root artifact for the dependency graph.
236          * This must not be confused with {@link #root(DependencyCoordinates)}: The root <em>dependency</em>, like any
237          * other specified dependency, will be subject to dependency collection/resolution, i.e. should have an artifact
238          * descriptor and a corresponding artifact file. The root <em>artifact</em> on the other hand is only used
239          * as a label for the root node of the graph in case no root dependency was specified. As such, the configured
240          * root artifact is ignored if {@link #root(DependencyCoordinates)} has been set.
241          *
242          * @param rootArtifact the root artifact for the dependency graph, may be {@code null}
243          * @return this request for chaining, never {@code null}
244          */
245         @Nonnull
246         public DependencyResolverRequestBuilder rootArtifact(@Nullable Artifact rootArtifact) {
247             this.rootArtifact = rootArtifact;
248             return this;
249         }
250 
251         /**
252          * @param root The root dependency
253          * @return this request for chaining, never {@code null}
254          */
255         @Nonnull
256         public DependencyResolverRequestBuilder root(@Nonnull DependencyCoordinates root) {
257             this.root = root;
258             return this;
259         }
260 
261         /**
262          * Sets the direct dependencies. If both a root dependency and direct dependencies are given in the request, the
263          * direct dependencies from the request will be merged with the direct dependencies from the root dependency's
264          * artifact descriptor, giving higher priority to the dependencies from the request.
265          *
266          * @param dependencies the direct dependencies, may be {@code null}
267          * @return this request for chaining, never {@code null}
268          */
269         @Nonnull
270         public DependencyResolverRequestBuilder dependencies(@Nullable List<DependencyCoordinates> dependencies) {
271             this.dependencies = (dependencies != null) ? dependencies : Collections.emptyList();
272             return this;
273         }
274 
275         /**
276          * Adds the specified direct dependency.
277          *
278          * @param dependency the dependency to add, may be {@code null}
279          * @return this request for chaining, never {@code null}
280          */
281         @Nonnull
282         public DependencyResolverRequestBuilder dependency(@Nullable DependencyCoordinates dependency) {
283             if (dependency != null) {
284                 if (this.dependencies.isEmpty()) {
285                     this.dependencies = new ArrayList<>();
286                 }
287                 this.dependencies.add(dependency);
288             }
289             return this;
290         }
291 
292         /**
293          * Sets the dependency management to apply to transitive dependencies. To clarify, this management does not
294          * apply to
295          * the direct dependencies of the root node.
296          *
297          * @param managedDependencies the dependency management, may be {@code null}
298          * @return this request for chaining, never {@code null}
299          */
300         @Nonnull
301         public DependencyResolverRequestBuilder managedDependencies(
302                 @Nullable List<DependencyCoordinates> managedDependencies) {
303             this.managedDependencies = (managedDependencies != null) ? managedDependencies : Collections.emptyList();
304             return this;
305         }
306 
307         /**
308          * Adds the specified managed dependency.
309          *
310          * @param managedDependency The managed dependency to add, may be {@code null} in which case the call
311          *                          will have no effect.
312          * @return this request for chaining, never {@code null}
313          */
314         @Nonnull
315         public DependencyResolverRequestBuilder managedDependency(@Nullable DependencyCoordinates managedDependency) {
316             if (managedDependency != null) {
317                 if (this.managedDependencies.isEmpty()) {
318                     this.managedDependencies = new ArrayList<>();
319                 }
320                 this.managedDependencies.add(managedDependency);
321             }
322             return this;
323         }
324 
325         /**
326          * Specifies that the collection should be verbose.
327          *
328          * @param verbose whether the collection should be verbose or not
329          * @return this request for chaining, never {@code null}
330          */
331         @Nonnull
332         public DependencyResolverRequestBuilder verbose(boolean verbose) {
333             this.verbose = verbose;
334             return this;
335         }
336 
337         @Nonnull
338         public DependencyResolverRequestBuilder pathScope(@Nullable PathScope pathScope) {
339             this.pathScope = pathScope;
340             return this;
341         }
342 
343         /**
344          * Filters the types of paths to include in the result.
345          * The result will contain only the paths of types for which the predicate returned {@code true}.
346          * It is recommended to apply a filter for retaining only the types of paths of interest,
347          * because it can resolve ambiguities when a path could be of many types.
348          *
349          * @param pathTypeFilter predicate evaluating whether a path type should be included in the result
350          * @return {@code this} for method call chaining
351          */
352         @Nonnull
353         public DependencyResolverRequestBuilder pathTypeFilter(@Nonnull Predicate<PathType> pathTypeFilter) {
354             this.pathTypeFilter = pathTypeFilter;
355             return this;
356         }
357 
358         /**
359          * Specifies the type of paths to include in the result. This is a convenience method for
360          * {@link #pathTypeFilter(Predicate)} using {@link Collection#contains(Object)} as the filter.
361          *
362          * @param desiredTypes the type of paths to include in the result
363          * @return {@code this} for method call chaining
364          */
365         @Nonnull
366         public DependencyResolverRequestBuilder pathTypeFilter(@Nonnull Collection<? extends PathType> desiredTypes) {
367             return pathTypeFilter(desiredTypes::contains);
368         }
369 
370         /**
371          * Sets the version of the platform where the code will be executed.
372          *
373          * @param target version of the platform where the code will be executed, or {@code null} for the default
374          * @return {@code this} for method call chaining
375          */
376         @Nonnull
377         public DependencyResolverRequestBuilder targetVersion(@Nullable Version target) {
378             targetVersion = target;
379             return this;
380         }
381 
382         @Nonnull
383         public DependencyResolverRequestBuilder repositories(@Nonnull List<RemoteRepository> repositories) {
384             this.repositories = repositories;
385             return this;
386         }
387 
388         @Nonnull
389         public DependencyResolverRequest build() {
390             return new DefaultDependencyResolverRequest(
391                     session,
392                     trace,
393                     requestType,
394                     project,
395                     rootArtifact,
396                     root,
397                     dependencies,
398                     managedDependencies,
399                     verbose,
400                     pathScope,
401                     pathTypeFilter,
402                     targetVersion,
403                     repositories);
404         }
405 
406         static class DefaultDependencyResolverRequest extends BaseRequest<Session>
407                 implements DependencyResolverRequest {
408 
409             static final class AlwaysTrueFilter implements Predicate<PathType> {
410                 @Override
411                 public boolean test(PathType pathType) {
412                     return true;
413                 }
414 
415                 @Override
416                 public boolean equals(Object obj) {
417                     return obj instanceof AlwaysTrueFilter;
418                 }
419 
420                 @Override
421                 public int hashCode() {
422                     return AlwaysTrueFilter.class.hashCode();
423                 }
424 
425                 @Override
426                 public String toString() {
427                     return "AlwaysTrueFilter[]";
428                 }
429             }
430 
431             private static final Predicate<PathType> DEFAULT_FILTER = new AlwaysTrueFilter();
432 
433             private final RequestType requestType;
434             private final Project project;
435             private final Artifact rootArtifact;
436             private final DependencyCoordinates root;
437             private final Collection<DependencyCoordinates> dependencies;
438             private final Collection<DependencyCoordinates> managedDependencies;
439             private final boolean verbose;
440             private final PathScope pathScope;
441             private final Predicate<PathType> pathTypeFilter;
442             private final Version targetVersion;
443             private final List<RemoteRepository> repositories;
444 
445             /**
446              * Creates a request with the specified properties.
447              *
448              * @param session      {@link Session}
449              * @param rootArtifact The root dependency whose transitive dependencies should be collected, may be {@code
450              *                     null}.
451              */
452             @SuppressWarnings("checkstyle:ParameterNumber")
453             DefaultDependencyResolverRequest(
454                     @Nonnull Session session,
455                     @Nullable RequestTrace trace,
456                     @Nonnull RequestType requestType,
457                     @Nullable Project project,
458                     @Nullable Artifact rootArtifact,
459                     @Nullable DependencyCoordinates root,
460                     @Nonnull Collection<DependencyCoordinates> dependencies,
461                     @Nonnull Collection<DependencyCoordinates> managedDependencies,
462                     boolean verbose,
463                     @Nullable PathScope pathScope,
464                     @Nullable Predicate<PathType> pathTypeFilter,
465                     @Nullable Version targetVersion,
466                     @Nullable List<RemoteRepository> repositories) {
467                 super(session, trace);
468                 this.requestType = requireNonNull(requestType, "requestType cannot be null");
469                 this.project = project;
470                 this.rootArtifact = rootArtifact;
471                 this.root = root;
472                 this.dependencies = List.copyOf(requireNonNull(dependencies, "dependencies cannot be null"));
473                 this.managedDependencies =
474                         List.copyOf(requireNonNull(managedDependencies, "managedDependencies cannot be null"));
475                 this.verbose = verbose;
476                 this.pathScope = requireNonNull(pathScope, "pathScope cannot be null");
477                 this.pathTypeFilter = (pathTypeFilter != null) ? pathTypeFilter : DEFAULT_FILTER;
478                 this.targetVersion = targetVersion;
479                 this.repositories = validate(repositories);
480                 if (verbose && requestType != RequestType.COLLECT) {
481                     throw new IllegalArgumentException("verbose cannot only be true when collecting dependencies");
482                 }
483             }
484 
485             @Nonnull
486             @Override
487             public RequestType getRequestType() {
488                 return requestType;
489             }
490 
491             @Nonnull
492             @Override
493             public Optional<Project> getProject() {
494                 return Optional.ofNullable(project);
495             }
496 
497             @Nonnull
498             @Override
499             public Optional<Artifact> getRootArtifact() {
500                 return Optional.ofNullable(rootArtifact);
501             }
502 
503             @Nonnull
504             @Override
505             public Optional<DependencyCoordinates> getRoot() {
506                 return Optional.ofNullable(root);
507             }
508 
509             @Nonnull
510             @Override
511             public Collection<DependencyCoordinates> getDependencies() {
512                 return dependencies;
513             }
514 
515             @Nonnull
516             @Override
517             public Collection<DependencyCoordinates> getManagedDependencies() {
518                 return managedDependencies;
519             }
520 
521             @Override
522             public boolean getVerbose() {
523                 return verbose;
524             }
525 
526             @Override
527             public PathScope getPathScope() {
528                 return pathScope;
529             }
530 
531             @Override
532             public Predicate<PathType> getPathTypeFilter() {
533                 return pathTypeFilter;
534             }
535 
536             @Override
537             public Version getTargetVersion() {
538                 return targetVersion;
539             }
540 
541             @Override
542             public List<RemoteRepository> getRepositories() {
543                 return repositories;
544             }
545 
546             @Override
547             public boolean equals(Object o) {
548                 return o instanceof DefaultDependencyResolverRequest that
549                         && verbose == that.verbose
550                         && requestType == that.requestType
551                         && Objects.equals(project, that.project)
552                         && Objects.equals(rootArtifact, that.rootArtifact)
553                         && Objects.equals(root, that.root)
554                         && Objects.equals(dependencies, that.dependencies)
555                         && Objects.equals(managedDependencies, that.managedDependencies)
556                         && Objects.equals(pathScope, that.pathScope)
557                         && Objects.equals(pathTypeFilter, that.pathTypeFilter)
558                         && Objects.equals(targetVersion, that.targetVersion)
559                         && Objects.equals(repositories, that.repositories);
560             }
561 
562             @Override
563             public int hashCode() {
564                 return Objects.hash(
565                         requestType,
566                         project,
567                         rootArtifact,
568                         root,
569                         dependencies,
570                         managedDependencies,
571                         verbose,
572                         pathScope,
573                         pathTypeFilter,
574                         targetVersion,
575                         repositories);
576             }
577 
578             @Override
579             public String toString() {
580                 return "DependencyResolverRequest[" + "requestType="
581                         + requestType + ", project="
582                         + project + ", rootArtifact="
583                         + rootArtifact + ", root="
584                         + root + ", dependencies="
585                         + dependencies + ", managedDependencies="
586                         + managedDependencies + ", verbose="
587                         + verbose + ", pathScope="
588                         + pathScope + ", pathTypeFilter="
589                         + pathTypeFilter + ", targetVersion="
590                         + targetVersion + ", repositories="
591                         + repositories + ']';
592             }
593         }
594     }
595 }