View Javadoc
1   package org.apache.maven.plugin.javadoc.resolver;
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 static org.codehaus.plexus.util.IOUtil.close;
23  
24  import org.apache.maven.artifact.Artifact;
25  import org.apache.maven.artifact.DefaultArtifact;
26  import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
27  import org.apache.maven.artifact.repository.ArtifactRepository;
28  import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
29  import org.apache.maven.artifact.resolver.ArtifactResolutionException;
30  import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
31  import org.apache.maven.artifact.resolver.ArtifactResolver;
32  import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
33  import org.apache.maven.plugin.javadoc.AbstractJavadocMojo;
34  import org.apache.maven.plugin.javadoc.JavadocUtil;
35  import org.apache.maven.plugin.javadoc.ResourcesBundleMojo;
36  import org.apache.maven.plugin.javadoc.options.JavadocOptions;
37  import org.apache.maven.plugin.javadoc.options.io.xpp3.JavadocOptionsXpp3Reader;
38  import org.apache.maven.project.MavenProject;
39  import org.codehaus.plexus.archiver.ArchiverException;
40  import org.codehaus.plexus.archiver.UnArchiver;
41  import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
42  import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
43  
44  import java.io.File;
45  import java.io.FileInputStream;
46  import java.io.IOException;
47  import java.util.ArrayList;
48  import java.util.Arrays;
49  import java.util.Collection;
50  import java.util.HashMap;
51  import java.util.LinkedHashSet;
52  import java.util.List;
53  import java.util.Map;
54  import java.util.Set;
55  
56  /**
57   * 
58   */
59  public final class ResourceResolver
60  {
61  
62      /**
63       * The classifier for sources.
64       */
65      public static final String SOURCES_CLASSIFIER = "sources";
66  
67      /**
68       * The classifier for test sources 
69       */
70      public static final String TEST_SOURCES_CLASSIFIER = "test-sources";
71  
72      private static final List<String> SOURCE_VALID_CLASSIFIERS = Arrays.asList( SOURCES_CLASSIFIER,
73                                                                                  TEST_SOURCES_CLASSIFIER );
74  
75      private static final List<String> RESOURCE_VALID_CLASSIFIERS =
76          Arrays.asList( AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER,
77                         AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER );
78  
79      private ResourceResolver()
80      {
81      }
82  
83      /**
84       * @param config {@link SourceResolverConfig}
85       * @return list of {@link JavadocBundle}.
86       * @throws IOException {@link IOException}
87       */
88      @SuppressWarnings( "unchecked" )
89      public static List<JavadocBundle> resolveDependencyJavadocBundles( final SourceResolverConfig config )
90          throws IOException
91      {
92          final List<JavadocBundle> bundles = new ArrayList<JavadocBundle>();
93  
94          final Map<String, MavenProject> projectMap = new HashMap<String, MavenProject>();
95          if ( config.reactorProjects() != null )
96          {
97              for ( final MavenProject p : config.reactorProjects() )
98              {
99                  projectMap.put( key( p.getGroupId(), p.getArtifactId() ), p );
100             }
101         }
102 
103         final List<Artifact> artifacts = config.project().getTestArtifacts();
104 
105         final List<Artifact> forResourceResolution = new ArrayList<Artifact>( artifacts.size() );
106         for ( final Artifact artifact : artifacts )
107         {
108             final String key = key( artifact.getGroupId(), artifact.getArtifactId() );
109             final MavenProject p = projectMap.get( key );
110             if ( p != null )
111             {
112                 bundles.addAll( resolveBundleFromProject( config, p, artifact ) );
113             }
114             else
115             {
116                 forResourceResolution.add( artifact );
117             }
118         }
119 
120         bundles.addAll( resolveBundlesFromArtifacts( config, forResourceResolution ) );
121 
122         return bundles;
123     }
124 
125     /**
126      * @param config {@link SourceResolverConfig}
127      * @return The list of resolved dependencies.
128      * @throws ArtifactResolutionException {@link ArtifactResolutionException}
129      * @throws ArtifactNotFoundException {@link ArtifactNotFoundException}
130      */
131     @SuppressWarnings( "unchecked" )
132     public static List<String> resolveDependencySourcePaths( final SourceResolverConfig config )
133         throws ArtifactResolutionException, ArtifactNotFoundException
134     {
135         final List<String> dirs = new ArrayList<String>();
136 
137         final Map<String, MavenProject> projectMap = new HashMap<String, MavenProject>();
138         if ( config.reactorProjects() != null )
139         {
140             for ( final MavenProject p : config.reactorProjects() )
141             {
142                 projectMap.put( key( p.getGroupId(), p.getArtifactId() ), p );
143             }
144         }
145 
146         final List<Artifact> artifacts = config.project().getTestArtifacts();
147 
148         final List<Artifact> forResourceResolution = new ArrayList<Artifact>( artifacts.size() );
149         for ( final Artifact artifact : artifacts )
150         {
151             final String key = key( artifact.getGroupId(), artifact.getArtifactId() );
152             final MavenProject p = projectMap.get( key );
153             if ( p != null )
154             {
155                 dirs.addAll( resolveFromProject( config, p, artifact ) );
156             }
157             else
158             {
159                 forResourceResolution.add( artifact );
160             }
161         }
162 
163         dirs.addAll( resolveFromArtifacts( config, forResourceResolution ) );
164 
165         return dirs;
166     }
167 
168     private static List<JavadocBundle> resolveBundleFromProject( SourceResolverConfig config, MavenProject project,
169                                                            Artifact artifact ) throws IOException
170     {
171         List<JavadocBundle> bundles = new ArrayList<JavadocBundle>();
172         
173         List<String> classifiers = new ArrayList<String>();
174         if ( config.includeCompileSources() )
175         {
176             classifiers.add( AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER );
177         }
178         
179         if ( config.includeTestSources() )
180         {
181             classifiers.add( AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER );
182         }
183         
184         for ( String classifier : classifiers )
185         {
186             File optionsFile =
187                 new File( project.getBuild().getDirectory(), "javadoc-bundle-options/javadoc-options-" + classifier
188                     + ".xml" );
189             if ( !optionsFile.exists() )
190             {
191                 continue;
192             }
193             
194             FileInputStream stream = null;
195             try
196             {
197                 stream = new FileInputStream( optionsFile );
198                 JavadocOptions options = new JavadocOptionsXpp3Reader().read( stream );
199                 
200                 bundles.add( new JavadocBundle( options, new File( project.getBasedir(),
201                                                                    options.getJavadocResourcesDirectory() ) ) );
202             }
203             catch ( XmlPullParserException e )
204             {
205                 IOException error =
206                     new IOException( "Failed to read javadoc options from: " + optionsFile + "\nReason: "
207                         + e.getMessage() );
208                 error.initCause( e );
209                 
210                 throw error;
211             }
212             finally
213             {
214                 close( stream );
215             }
216         }
217 
218         return bundles;
219     }
220 
221     private static List<JavadocBundle> resolveBundlesFromArtifacts( final SourceResolverConfig config,
222                                                                     final List<Artifact> artifacts )
223         throws IOException
224     {
225         final List<Artifact> toResolve = new ArrayList<Artifact>( artifacts.size() );
226 
227         for ( final Artifact artifact : artifacts )
228         {
229             if ( config.filter() != null && !config.filter().include( artifact ) )
230             {
231                 continue;
232             }
233 
234             if ( config.includeCompileSources() )
235             {
236                 toResolve.add( createResourceArtifact( artifact,
237                                                        AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER,
238                                                        config ) );
239             }
240 
241             if ( config.includeTestSources() )
242             {
243                 toResolve.add( createResourceArtifact( artifact,
244                                                        AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER,
245                                                        config ) );
246             }
247         }
248 
249         List<String> dirs = null;
250         try
251         {
252             dirs = resolveAndUnpack( toResolve, config, RESOURCE_VALID_CLASSIFIERS, false );
253         }
254         catch ( ArtifactResolutionException e )
255         {
256             if ( config.log().isDebugEnabled() )
257             {
258                 config.log().debug( e.getMessage(), e );
259             }
260         }
261         catch ( ArtifactNotFoundException e )
262         {
263             if ( config.log().isDebugEnabled() )
264             {
265                 config.log().debug( e.getMessage(), e );
266             }
267         }
268         
269         List<JavadocBundle> result = new ArrayList<JavadocBundle>();
270 
271         if ( dirs != null )
272         {
273             for ( String d : dirs )
274             {
275                 File dir = new File( d );
276                 File resources = new File( dir, ResourcesBundleMojo.RESOURCES_DIR_PATH );
277                 JavadocOptions options = null;
278 
279                 File javadocOptions = new File( dir, ResourcesBundleMojo.BUNDLE_OPTIONS_PATH );
280                 if ( javadocOptions.exists() )
281                 {
282                     FileInputStream reader = null;
283                     try
284                     {
285                         reader = new FileInputStream( javadocOptions );
286                         options = new JavadocOptionsXpp3Reader().read( reader );
287                     }
288                     catch ( XmlPullParserException e )
289                     {
290                         IOException error = new IOException( "Failed to parse javadoc options: " + e.getMessage() );
291                         error.initCause( e );
292                         
293                         throw error;
294                     }
295                     finally
296                     {
297                         close( reader );
298                     }
299                 }
300                 
301                 result.add( new JavadocBundle( options, resources ) );
302             }
303         }
304         
305         return result;
306     }
307 
308     private static List<String> resolveFromArtifacts( final SourceResolverConfig config,
309                                                       final List<Artifact> artifacts )
310         throws ArtifactResolutionException, ArtifactNotFoundException
311     {
312         final List<Artifact> toResolve = new ArrayList<Artifact>( artifacts.size() );
313 
314         for ( final Artifact artifact : artifacts )
315         {
316             if ( config.filter() != null && !config.filter().include( artifact ) )
317             {
318                 continue;
319             }
320 
321             if ( config.includeCompileSources() )
322             {
323                 toResolve.add( createResourceArtifact( artifact, SOURCES_CLASSIFIER, config ) );
324             }
325 
326             if ( config.includeTestSources() )
327             {
328                 toResolve.add( createResourceArtifact( artifact, TEST_SOURCES_CLASSIFIER, config ) );
329             }
330         }
331 
332         return resolveAndUnpack( toResolve, config, SOURCE_VALID_CLASSIFIERS, true );
333     }
334 
335     private static Artifact createResourceArtifact( final Artifact artifact, final String classifier,
336                                                     final SourceResolverConfig config )
337     {
338         final DefaultArtifact a =
339             (DefaultArtifact) config.artifactFactory().createArtifactWithClassifier( artifact.getGroupId(),
340                                                                                      artifact.getArtifactId(),
341                                                                                      artifact.getVersion(), "jar",
342                                                                                      classifier );
343 
344         a.setRepository( artifact.getRepository() );
345 
346         return a;
347     }
348 
349     @SuppressWarnings( "unchecked" )
350     private static List<String> resolveAndUnpack( final List<Artifact> artifacts, final SourceResolverConfig config,
351                                                   final List<String> validClassifiers, final boolean propagateErrors )
352         throws ArtifactResolutionException, ArtifactNotFoundException
353     {
354         // NOTE: Since these are '-sources' and '-test-sources' artifacts, they won't actually 
355         // resolve transitively...this is just used to aggregate resolution failures into a single 
356         // exception.
357         final Set<Artifact> artifactSet = new LinkedHashSet<Artifact>( artifacts );
358         final Artifact pomArtifact = config.project().getArtifact();
359         final ArtifactRepository localRepo = config.localRepository();
360         final List<ArtifactRepository> remoteRepos = config.project().getRemoteArtifactRepositories();
361         final ArtifactMetadataSource metadataSource = config.artifactMetadataSource();
362 
363         final ArtifactFilter filter = config.filter();
364         ArtifactFilter resolutionFilter = null;
365         if ( filter != null )
366         {
367             // Wrap the filter in a ProjectArtifactFilter in order to always include the pomArtifact for resolution.
368             // NOTE that this is necessary, b/c the -sources artifacts are added dynamically to the pomArtifact
369             // and the resolver also checks the dependency trail with the given filter, thus the pomArtifact has
370             // to be explicitly included by the filter, otherwise the -sources artifacts won't be resolved.
371             resolutionFilter = new ProjectArtifactFilter( pomArtifact, filter );
372         }
373 
374         final ArtifactResolver resolver = config.artifactResolver();
375         
376         @SuppressWarnings( "rawtypes" )
377         Map managed = config.project().getManagedVersionMap();
378         
379         final ArtifactResolutionResult resolutionResult = resolver.resolveTransitively(
380                 artifactSet, pomArtifact, managed, localRepo, remoteRepos, metadataSource, resolutionFilter );
381 
382         final List<String> result = new ArrayList<String>( artifacts.size() );
383         for ( final Artifact a : (Collection<Artifact>) resolutionResult.getArtifacts() )
384         {
385             if ( !validClassifiers.contains( a.getClassifier() ) || ( filter != null && !filter.include( a ) ) )
386             {
387                 continue;
388             }
389 
390             final File d =
391                 new File( config.outputBasedir(), a.getArtifactId() + "-" + a.getVersion() + "-" + a.getClassifier() );
392 
393             if ( !d.exists() )
394             {
395                 d.mkdirs();
396             }
397 
398             try
399             {
400                 final UnArchiver unArchiver = config.archiverManager().getUnArchiver( a.getType() );
401 
402                 unArchiver.setDestDirectory( d );
403                 unArchiver.setSourceFile( a.getFile() );
404 
405                 unArchiver.extract();
406 
407                 result.add( d.getAbsolutePath() );
408             }
409             catch ( final NoSuchArchiverException e )
410             {
411                 if ( propagateErrors )
412                 {
413                     throw new ArtifactResolutionException( "Failed to retrieve valid un-archiver component: "
414                         + a.getType(), a, e );
415                 }
416             }
417             catch ( final ArchiverException e )
418             {
419                 if ( propagateErrors )
420                 {
421                     throw new ArtifactResolutionException( "Failed to unpack: " + a.getId(), a, e );
422                 }
423             }
424         }
425 
426         return result;
427     }
428 
429     @SuppressWarnings( "unchecked" )
430     private static List<String> resolveFromProject( final SourceResolverConfig config,
431                                                     final MavenProject reactorProject, final Artifact artifact )
432     {
433         final List<String> dirs = new ArrayList<String>();
434 
435         if ( config.filter() == null || config.filter().include( artifact ) )
436         {
437             if ( config.includeCompileSources() )
438             {
439                 final List<String> srcRoots = reactorProject.getCompileSourceRoots();
440                 for ( final String root : srcRoots )
441                 {
442                     dirs.add( root );
443                 }
444             }
445 
446             if ( config.includeTestSources() )
447             {
448                 final List<String> srcRoots = reactorProject.getTestCompileSourceRoots();
449                 for ( final String root : srcRoots )
450                 {
451                     dirs.add( root );
452                 }
453             }
454         }
455 
456         return JavadocUtil.pruneDirs( reactorProject, dirs );
457     }
458 
459     private static String key( final String gid, final String aid )
460     {
461         return gid + ":" + aid;
462     }
463 
464 }