View Javadoc
1   package org.apache.maven.plugin.dependency;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   * http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import org.apache.maven.artifact.Artifact;
23  import org.apache.maven.artifact.factory.ArtifactFactory;
24  import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
25  import org.apache.maven.artifact.repository.ArtifactRepository;
26  import org.apache.maven.artifact.resolver.ArtifactCollector;
27  import org.apache.maven.artifact.resolver.ArtifactResolver;
28  import org.apache.maven.plugin.AbstractMojo;
29  import org.apache.maven.plugin.MojoExecutionException;
30  import org.apache.maven.plugin.MojoFailureException;
31  import org.apache.maven.plugin.dependency.utils.DependencySilentLog;
32  import org.apache.maven.plugin.logging.Log;
33  import org.apache.maven.plugins.annotations.Component;
34  import org.apache.maven.plugins.annotations.Parameter;
35  import org.apache.maven.project.MavenProject;
36  import org.codehaus.plexus.archiver.ArchiverException;
37  import org.codehaus.plexus.archiver.UnArchiver;
38  import org.codehaus.plexus.archiver.manager.ArchiverManager;
39  import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
40  import org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector;
41  import org.codehaus.plexus.util.FileUtils;
42  import org.codehaus.plexus.util.ReflectionUtils;
43  import org.codehaus.plexus.util.StringUtils;
44  
45  import java.io.File;
46  import java.io.IOException;
47  import java.lang.reflect.Field;
48  import java.util.List;
49  
50  /**
51   * @author <a href="mailto:brianf@apache.org">Brian Fox</a>
52   * @version $Id: AbstractDependencyMojo.java 552528
53   *          2007-07-02 16:12:47Z markh $
54   */
55  public abstract class AbstractDependencyMojo
56      extends AbstractMojo
57  {
58      /**
59       * Used to look up Artifacts in the remote repository.
60       */
61      @Component
62      protected ArtifactFactory factory;
63  
64      /**
65       * Used to look up Artifacts in the remote repository.
66       */
67      @Component
68      protected ArtifactResolver resolver;
69  
70      /**
71       * Artifact collector, needed to resolve dependencies.
72       */
73      @Component( role = ArtifactCollector.class )
74      protected ArtifactCollector artifactCollector;
75  
76      /**
77       *
78       */
79      @Component( role = ArtifactMetadataSource.class, hint = "maven" )
80      protected ArtifactMetadataSource artifactMetadataSource;
81  
82      /**
83       * Location of the local repository.
84       */
85      @Parameter( defaultValue = "${localRepository}", readonly = true, required = true )
86      private ArtifactRepository local;
87  
88      /**
89       * List of Remote Repositories used by the resolver
90       */
91      @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true )
92      protected List<ArtifactRepository> remoteRepos;
93  
94      /**
95       * To look up Archiver/UnArchiver implementations
96       */
97      @Component
98      protected ArchiverManager archiverManager;
99  
100     /**
101      * <p>
102      * will use the jvm chmod, this is available for user and all level group level will be ignored
103      * </p>
104      * <b>since 2.6 is on by default</b>
105      * @since 2.5.1
106      */
107     @Parameter( property = "dependency.useJvmChmod", defaultValue = "true" )
108     protected boolean useJvmChmod = true;
109 
110     /**
111      * ignore to set file permissions when unpacking a dependency
112      * @since 2.7
113      */
114     @Parameter( property = "dependency.ignorePermissions", defaultValue = "false" )
115     protected boolean ignorePermissions;
116 
117     /**
118      * POM
119      */
120     @Parameter( defaultValue = "${project}", readonly = true, required = true )
121     protected MavenProject project;
122 
123     /**
124      * Contains the full list of projects in the reactor.
125      */
126     @Parameter( defaultValue = "${reactorProjects}", readonly = true )
127     protected List<MavenProject> reactorProjects;
128 
129     /**
130      * If the plugin should be silent.
131      *
132      * @since 2.0
133      */
134     @Parameter( property = "silent", defaultValue = "false" )
135     protected boolean silent;
136 
137     /**
138      * Output absolute filename for resolved artifacts
139      *
140      * @since 2.0
141      */
142     @Parameter( property = "outputAbsoluteArtifactFilename", defaultValue = "false" )
143     protected boolean outputAbsoluteArtifactFilename;
144 
145     /**
146      * Skip plugin execution completely.
147      *
148      * @since 2.7
149      */
150     @Parameter( property = "mdep.skip", defaultValue = "false" )
151     private boolean skip;
152 
153     // Mojo methods -----------------------------------------------------------
154 
155     /*
156      * @see org.apache.maven.plugin.Mojo#execute()
157      */
158     public final void execute()
159         throws MojoExecutionException, MojoFailureException
160     {
161         if ( isSkip() )
162         {
163             getLog().info( "Skipping plugin execution" );
164             return;
165         }
166 
167         doExecute();
168     }
169 
170     protected abstract void doExecute()
171             throws MojoExecutionException, MojoFailureException;
172 
173 
174     private Log log;
175 
176     /**
177      * @return Returns the log.
178      */
179     public Log getLog()
180     {
181         if ( log == null )
182         {
183             if ( silent )
184             {
185                 log = new DependencySilentLog();
186             }
187             else
188             {
189                 log = super.getLog();
190             }
191         }
192 
193         return this.log;
194     }
195 
196     /**
197      * @return Returns the archiverManager.
198      */
199     public ArchiverManager getArchiverManager()
200     {
201         return this.archiverManager;
202     }
203 
204     /**
205      * Does the actual copy of the file and logging.
206      *
207      * @param artifact represents the file to copy.
208      * @param destFile file name of destination file.
209      * @throws MojoExecutionException with a message if an
210      *                                error occurs.
211      */
212     protected void copyFile( File artifact, File destFile )
213         throws MojoExecutionException
214     {
215         try
216         {
217             getLog().info( "Copying "
218                                + ( this.outputAbsoluteArtifactFilename ? artifact.getAbsolutePath()
219                                                : artifact.getName() ) + " to " + destFile );
220 
221             if ( artifact.isDirectory() )
222             {
223                 // usual case is a future jar packaging, but there are special cases: classifier and other packaging
224                 throw new MojoExecutionException( "Artifact has not been packaged yet. When used on reactor artifact, "
225                     + "copy should be executed after packaging: see MDEP-187." );
226             }
227 
228             FileUtils.copyFile( artifact, destFile );
229         }
230         catch ( IOException e )
231         {
232             throw new MojoExecutionException( "Error copying artifact from " + artifact + " to " + destFile, e );
233         }
234     }
235 
236     protected void unpack( Artifact artifact, File location )
237         throws MojoExecutionException
238     {
239         unpack( artifact, location, null, null );
240     }
241 
242     /**
243      * Unpacks the archive file.
244      *
245      * @param artifact File to be unpacked.
246      * @param location Location where to put the unpacked files.
247      * @param includes Comma separated list of file patterns to include i.e. <code>**&#47;.xml,
248      *                 **&#47;*.properties</code>
249      * @param excludes Comma separated list of file patterns to exclude i.e. <code>**&#47;*.xml,
250      *                 **&#47;*.properties</code>
251      */
252     protected void unpack( Artifact artifact, File location, String includes, String excludes )
253         throws MojoExecutionException
254     {
255         File file = artifact.getFile(); 
256         try
257         {
258             logUnpack( file, location, includes, excludes );
259 
260             location.mkdirs();
261 
262             if ( file.isDirectory() )
263             {
264                 // usual case is a future jar packaging, but there are special cases: classifier and other packaging
265                 throw new MojoExecutionException( "Artifact has not been packaged yet. When used on reactor artifact, "
266                     + "unpack should be executed after packaging: see MDEP-98." );
267             }
268 
269             UnArchiver unArchiver;
270 
271             try
272             {
273                 unArchiver = archiverManager.getUnArchiver( artifact.getType() );
274                 getLog().debug( "Found unArchiver by type: " + unArchiver );
275             }
276             catch ( NoSuchArchiverException e )
277             {
278                 unArchiver = archiverManager.getUnArchiver( file );
279                 getLog().debug( "Found unArchiver by extension: " + unArchiver );
280             }
281 
282             unArchiver.setUseJvmChmod( useJvmChmod );
283 
284             unArchiver.setIgnorePermissions( ignorePermissions );
285 
286             unArchiver.setSourceFile( file );
287 
288             unArchiver.setDestDirectory( location );
289 
290             if ( StringUtils.isNotEmpty( excludes ) || StringUtils.isNotEmpty( includes ) )
291             {
292                 // Create the selectors that will filter
293                 // based on include/exclude parameters
294                 // MDEP-47
295                 IncludeExcludeFileSelector[] selectors =
296                     new IncludeExcludeFileSelector[]{ new IncludeExcludeFileSelector() };
297 
298                 if ( StringUtils.isNotEmpty( excludes ) )
299                 {
300                     selectors[0].setExcludes( excludes.split( "," ) );
301                 }
302 
303                 if ( StringUtils.isNotEmpty( includes ) )
304                 {
305                     selectors[0].setIncludes( includes.split( "," ) );
306                 }
307 
308                 unArchiver.setFileSelectors( selectors );
309             }
310             if ( this.silent )
311             {
312                 silenceUnarchiver( unArchiver );
313             }
314 
315             unArchiver.extract();
316         }
317         catch ( NoSuchArchiverException e )
318         {
319             throw new MojoExecutionException( "Unknown archiver type", e );
320         }
321         catch ( ArchiverException e )
322         {
323             throw new MojoExecutionException(
324                 "Error unpacking file: " + file + " to: " + location + "\r\n" + e.toString(), e );
325         }
326     }
327 
328     private void silenceUnarchiver( UnArchiver unArchiver )
329     {
330         // dangerous but handle any errors. It's the only way to silence the unArchiver.
331         try
332         {
333             Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses( "logger", unArchiver.getClass() );
334 
335             field.setAccessible( true );
336 
337             field.set( unArchiver, this.getLog() );
338         }
339         catch ( Exception e )
340         {
341             // was a nice try. Don't bother logging because the log is silent.
342         }
343     }
344 
345     /**
346      * @return Returns the factory.
347      */
348     public ArtifactFactory getFactory()
349     {
350         return this.factory;
351     }
352 
353     /**
354      * @param factory The factory to set.
355      */
356     public void setFactory( ArtifactFactory factory )
357     {
358         this.factory = factory;
359     }
360 
361     /**
362      * @return Returns the project.
363      */
364     public MavenProject getProject()
365     {
366         return this.project;
367     }
368 
369     /**
370      * @return Returns the local.
371      */
372     protected ArtifactRepository getLocal()
373     {
374         return this.local;
375     }
376 
377     /**
378      * @param local The local to set.
379      */
380     public void setLocal( ArtifactRepository local )
381     {
382         this.local = local;
383     }
384 
385     /**
386      * @return Returns the remoteRepos.
387      */
388     public List<ArtifactRepository> getRemoteRepos()
389     {
390         return this.remoteRepos;
391     }
392 
393     /**
394      * @param remoteRepos The remoteRepos to set.
395      */
396     public void setRemoteRepos( List<ArtifactRepository> remoteRepos )
397     {
398         this.remoteRepos = remoteRepos;
399     }
400 
401     /**
402      * @return Returns the resolver.
403      */
404     public ArtifactResolver getResolver()
405     {
406         return this.resolver;
407     }
408 
409     /**
410      * @param resolver The resolver to set.
411      */
412     public void setResolver( ArtifactResolver resolver )
413     {
414         this.resolver = resolver;
415     }
416 
417     /**
418      * @param archiverManager The archiverManager to set.
419      */
420     public void setArchiverManager( ArchiverManager archiverManager )
421     {
422         this.archiverManager = archiverManager;
423     }
424 
425     /**
426      * @return Returns the artifactCollector.
427      */
428     public ArtifactCollector getArtifactCollector()
429     {
430         return this.artifactCollector;
431     }
432 
433     /**
434      * @param theArtifactCollector The artifactCollector to set.
435      */
436     public void setArtifactCollector( ArtifactCollector theArtifactCollector )
437     {
438         this.artifactCollector = theArtifactCollector;
439     }
440 
441     /**
442      * @return Returns the artifactMetadataSource.
443      */
444     public ArtifactMetadataSource getArtifactMetadataSource()
445     {
446         return this.artifactMetadataSource;
447     }
448 
449     /**
450      * @param theArtifactMetadataSource The artifactMetadataSource to set.
451      */
452     public void setArtifactMetadataSource( ArtifactMetadataSource theArtifactMetadataSource )
453     {
454         this.artifactMetadataSource = theArtifactMetadataSource;
455     }
456 
457     public boolean isUseJvmChmod()
458     {
459         return useJvmChmod;
460     }
461 
462     public void setUseJvmChmod( boolean useJvmChmod )
463     {
464         this.useJvmChmod = useJvmChmod;
465     }
466 
467     public boolean isSkip()
468     {
469         return skip;
470     }
471 
472     public void setSkip( boolean skip )
473     {
474         this.skip = skip;
475     }
476 
477 
478     private void logUnpack( File file, File location, String includes, String excludes )
479     {
480         if ( !getLog().isInfoEnabled() )
481         {
482             return;
483         }
484 
485         StringBuilder msg = new StringBuilder();
486         msg.append( "Unpacking " );
487         msg.append( file );
488         msg.append( " to " );
489         msg.append( location );
490 
491         if ( includes != null && excludes != null )
492         {
493             msg.append( " with includes \"" );
494             msg.append( includes );
495             msg.append( "\" and excludes \"" );
496             msg.append( excludes );
497             msg.append( "\"" );
498         }
499         else if ( includes != null )
500         {
501             msg.append( " with includes \"" );
502             msg.append( includes );
503             msg.append( "\"" );
504         }
505         else if ( excludes != null )
506         {
507             msg.append( " with excludes \"" );
508             msg.append( excludes );
509             msg.append( "\"" );
510         }
511 
512         getLog().info( msg.toString() );
513     }
514 }