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.commons.weaver.maven;
20  
21  import java.io.File;
22  import java.lang.annotation.ElementType;
23  import java.lang.annotation.Retention;
24  import java.lang.annotation.RetentionPolicy;
25  import java.lang.annotation.Target;
26  import java.util.List;
27  import java.util.Properties;
28  import java.util.stream.Collectors;
29  
30  import org.apache.commons.lang3.ArrayUtils;
31  import org.apache.commons.lang3.StringUtils;
32  import org.apache.maven.RepositoryUtils;
33  import org.apache.maven.model.Dependency;
34  import org.apache.maven.plugin.AbstractMojo;
35  import org.apache.maven.plugin.MojoExecutionException;
36  import org.apache.maven.plugin.MojoFailureException;
37  import org.apache.maven.plugins.annotations.Component;
38  import org.apache.maven.plugins.annotations.Parameter;
39  import org.apache.maven.project.MavenProject;
40  import org.eclipse.aether.RepositorySystem;
41  import org.eclipse.aether.RepositorySystemSession;
42  import org.eclipse.aether.collection.CollectRequest;
43  import org.eclipse.aether.resolution.DependencyRequest;
44  import org.eclipse.aether.resolution.DependencyResolutionException;
45  import org.eclipse.aether.resolution.DependencyResult;
46  import org.eclipse.aether.util.artifact.JavaScopes;
47  import org.eclipse.aether.util.filter.ScopeDependencyFilter;
48  
49  /**
50   * Defines common properties and high-level management common to all commons-weaver Maven goals.
51   * @since 1.3
52   */
53  abstract class AbstractCWMojo extends AbstractMojo {
54      /**
55       * Marks a mojo as requiring dependencies in {@link JavaScopes#TEST} scope.
56       */
57      @Target(ElementType.TYPE)
58      @Retention(RetentionPolicy.RUNTIME)
59      @interface TestScope {
60      }
61  
62      /**
63       * {@code verbose} parameter.
64       */
65      @Parameter(defaultValue = "false")
66      protected boolean verbose;
67  
68      /**
69       * {@code weaver.config} parameter.
70       */
71      @Parameter(property = "weaver.config", required = false)
72      protected Properties weaverConfig;
73  
74      @Parameter(defaultValue = "${project}")
75      protected MavenProject project;
76  
77      @Component
78      protected RepositorySystem repositorySystem;
79  
80      @Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
81      protected RepositorySystemSession repositorySystemSession;
82  
83      /**
84       * Get the target directory for this prepare mojo.
85       *
86       * @return {@link File}
87       */
88      protected abstract File getTarget();
89  
90      /**
91       * Execute this mojo.
92       *
93       * @throws MojoExecutionException in the event of failure
94       */
95      @Override
96      public final void execute() throws MojoExecutionException, MojoFailureException {
97          final JavaLoggingToMojoLoggingRedirector logRedirector = new JavaLoggingToMojoLoggingRedirector(getLog());
98          logRedirector.activate();
99  
100         try {
101             final List<String> classpath;
102             try {
103                 classpath = createClasspath();
104             } catch (DependencyResolutionException e) {
105                 throw new MojoExecutionException("Error getting classpath artifacts", e);
106             }
107             final File target = getTarget();
108             final Properties config = weaverConfig == null ? new Properties() : weaverConfig;
109 
110             getLog().debug(String.format("classpath=%s%ntarget=%s%nconfig=%s", classpath, target, config));
111 
112             doExecute(target, classpath, config);
113         } finally {
114             logRedirector.deactivate();
115         }
116     }
117 
118     protected abstract void doExecute(File target, List<String> classpath, Properties config)
119         throws MojoExecutionException, MojoFailureException;
120 
121     private List<String> createClasspath() throws DependencyResolutionException {
122         final CollectRequest collect = new CollectRequest();
123         collect.setRootArtifact(RepositoryUtils.toArtifact(project.getArtifact()));
124         collect.setRequestContext("project");
125         collect.setRepositories(project.getRemoteProjectRepositories());
126 
127         for (final Dependency dependency : project.getDependencies()) {
128             // guard against case where best-effort resolution for invalid models is requested:
129             if (StringUtils.isAnyBlank(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion())) {
130                 continue;
131             }
132             collect.addDependency(
133                 RepositoryUtils.toDependency(dependency, repositorySystemSession.getArtifactTypeRegistry()));
134         }
135         final DependencyResult dependencyResult =
136             repositorySystem.resolveDependencies(repositorySystemSession, new DependencyRequest()
137                 .setFilter(new ScopeDependencyFilter(getExcludeScopes())).setCollectRequest(collect));
138 
139         return dependencyResult.getArtifactResults().stream().map(ar -> ar.getArtifact().getFile().getAbsolutePath())
140             .distinct().collect(Collectors.toList());
141     }
142 
143     private String[] getExcludeScopes() {
144         return getClass().isAnnotationPresent(TestScope.class) ? ArrayUtils.EMPTY_STRING_ARRAY
145             : new String[] { JavaScopes.TEST };
146     }
147 }