Coverage Report - org.apache.maven.plugins.shade.mojo.ShadeMojo
 
Classes in this File Line Coverage Branch Coverage Complexity
ShadeMojo
11%
31/270
9%
13/142
6.312
 
 1  
 package org.apache.maven.plugins.shade.mojo;
 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 java.io.File;
 23  
 import java.io.FileInputStream;
 24  
 import java.io.FileOutputStream;
 25  
 import java.io.IOException;
 26  
 import java.io.Writer;
 27  
 import java.util.ArrayList;
 28  
 import java.util.Arrays;
 29  
 import java.util.Collections;
 30  
 import java.util.HashMap;
 31  
 import java.util.HashSet;
 32  
 import java.util.Iterator;
 33  
 import java.util.LinkedHashSet;
 34  
 import java.util.List;
 35  
 import java.util.Map;
 36  
 import java.util.Set;
 37  
 
 38  
 import org.apache.maven.artifact.Artifact;
 39  
 import org.apache.maven.artifact.factory.ArtifactFactory;
 40  
 import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
 41  
 import org.apache.maven.artifact.repository.ArtifactRepository;
 42  
 import org.apache.maven.artifact.resolver.ArtifactCollector;
 43  
 import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
 44  
 import org.apache.maven.artifact.resolver.ArtifactResolutionException;
 45  
 import org.apache.maven.artifact.resolver.ArtifactResolver;
 46  
 import org.apache.maven.model.Dependency;
 47  
 import org.apache.maven.model.Exclusion;
 48  
 import org.apache.maven.model.Model;
 49  
 import org.apache.maven.plugin.AbstractMojo;
 50  
 import org.apache.maven.plugin.MojoExecutionException;
 51  
 import org.apache.maven.plugins.shade.Shader;
 52  
 import org.apache.maven.plugins.shade.filter.Filter;
 53  
 import org.apache.maven.plugins.shade.filter.MinijarFilter;
 54  
 import org.apache.maven.plugins.shade.filter.SimpleFilter;
 55  
 import org.apache.maven.plugins.shade.pom.PomWriter;
 56  
 import org.apache.maven.plugins.shade.relocation.Relocator;
 57  
 import org.apache.maven.plugins.shade.relocation.SimpleRelocator;
 58  
 import org.apache.maven.plugins.shade.resource.ResourceTransformer;
 59  
 import org.apache.maven.project.MavenProject;
 60  
 import org.apache.maven.project.MavenProjectBuilder;
 61  
 import org.apache.maven.project.MavenProjectHelper;
 62  
 import org.apache.maven.project.ProjectBuildingException;
 63  
 import org.apache.maven.shared.dependency.tree.DependencyNode;
 64  
 import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
 65  
 import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException;
 66  
 import org.codehaus.plexus.PlexusConstants;
 67  
 import org.codehaus.plexus.PlexusContainer;
 68  
 import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
 69  
 import org.codehaus.plexus.context.Context;
 70  
 import org.codehaus.plexus.context.ContextException;
 71  
 import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
 72  
 import org.codehaus.plexus.util.IOUtil;
 73  
 import org.codehaus.plexus.util.WriterFactory;
 74  
 
 75  
 /**
 76  
  * Mojo that performs shading delegating to the Shader component.
 77  
  *
 78  
  * @author Jason van Zyl
 79  
  * @author Mauro Talevi
 80  
  * @author David Blevins
 81  
  * @author Hiram Chirino
 82  
  * @goal shade
 83  
  * @phase package
 84  
  * @requiresDependencyResolution runtime
 85  
  * @threadSafe
 86  
  */
 87  1
 public class ShadeMojo
 88  
     extends AbstractMojo
 89  
     implements Contextualizable
 90  
 {
 91  
     /**
 92  
      * @parameter default-value="${project}"
 93  
      * @readonly
 94  
      * @required
 95  
      */
 96  
     private MavenProject project;
 97  
 
 98  
     /**
 99  
      * @component
 100  
      * @required
 101  
      * @readonly
 102  
      */
 103  
     private MavenProjectHelper projectHelper;
 104  
 
 105  
     /**
 106  
      * @component role="org.apache.maven.plugins.shade.Shader" roleHint="default"
 107  
      * @required
 108  
      * @readonly
 109  
      */
 110  
     private Shader shader;
 111  
 
 112  
     /**
 113  
      * The dependency tree builder to use.
 114  
      *
 115  
      * @component
 116  
      * @required
 117  
      * @readonly
 118  
      */
 119  
     private DependencyTreeBuilder dependencyTreeBuilder;
 120  
 
 121  
     /**
 122  
      * ProjectBuilder, needed to create projects from the artifacts.
 123  
      *
 124  
      * @component
 125  
      * @required
 126  
      * @readonly
 127  
      */
 128  
     private MavenProjectBuilder mavenProjectBuilder;
 129  
 
 130  
     /**
 131  
      * The artifact metadata source to use.
 132  
      *
 133  
      * @component
 134  
      * @required
 135  
      * @readonly
 136  
      */
 137  
     private ArtifactMetadataSource artifactMetadataSource;
 138  
 
 139  
     /**
 140  
      * The artifact collector to use.
 141  
      *
 142  
      * @component
 143  
      * @required
 144  
      * @readonly
 145  
      */
 146  
     private ArtifactCollector artifactCollector;
 147  
 
 148  
     /**
 149  
      * Remote repositories which will be searched for source attachments.
 150  
      *
 151  
      * @parameter default-value="${project.remoteArtifactRepositories}"
 152  
      * @required
 153  
      * @readonly
 154  
      */
 155  
     protected List remoteArtifactRepositories;
 156  
 
 157  
     /**
 158  
      * Local maven repository.
 159  
      *
 160  
      * @parameter default-value="${localRepository}"
 161  
      * @required
 162  
      * @readonly
 163  
      */
 164  
     protected ArtifactRepository localRepository;
 165  
 
 166  
     /**
 167  
      * Artifact factory, needed to download source jars for inclusion in classpath.
 168  
      *
 169  
      * @component
 170  
      * @required
 171  
      * @readonly
 172  
      */
 173  
     protected ArtifactFactory artifactFactory;
 174  
 
 175  
     /**
 176  
      * Artifact resolver, needed to download source jars for inclusion in classpath.
 177  
      *
 178  
      * @component
 179  
      * @required
 180  
      * @readonly
 181  
      */
 182  
     protected ArtifactResolver artifactResolver;
 183  
 
 184  
     /**
 185  
      * Artifacts to include/exclude from the final artifact. Artifacts are denoted by composite identifiers of the
 186  
      * general form <code>groupId:artifactId:type:classifier</code>. Since version 1.3, the wildcard characters '*' and
 187  
      * '?' can be used within the sub parts of those composite identifiers to do pattern matching. For convenience, the
 188  
      * syntax <code>groupId</code> is equivalent to <code>groupId:*:*:*</code>, <code>groupId:artifactId</code> is
 189  
      * equivalent to <code>groupId:artifactId:*:*</code> and <code>groupId:artifactId:classifier</code> is equivalent to
 190  
      * <code>groupId:artifactId:*:classifier</code>. For example:
 191  
      * <pre>
 192  
      * &lt;artifactSet&gt;
 193  
      *   &lt;includes&gt;
 194  
      *     &lt;include&gt;org.apache.maven:*&lt;/include&gt;
 195  
      *   &lt;/includes&gt;
 196  
      *   &lt;excludes&gt;
 197  
      *     &lt;exclude&gt;*:maven-core&lt;/exclude&gt;
 198  
      *   &lt;/excludes&gt;
 199  
      * &lt;/artifactSet&gt;
 200  
      * </pre>
 201  
      *
 202  
      * @parameter
 203  
      */
 204  
     private ArtifactSet artifactSet;
 205  
 
 206  
     /**
 207  
      * Packages to be relocated. For example:
 208  
      * <pre>
 209  
      * &lt;relocations&gt;
 210  
      *   &lt;relocation&gt;
 211  
      *     &lt;pattern&gt;org.apache&lt;/pattern&gt;
 212  
      *     &lt;shadedPattern&gt;hidden.org.apache&lt;/shadedPattern&gt;
 213  
      *     &lt;includes&gt;
 214  
      *       &lt;include&gt;org.apache.maven.*&lt;/include&gt;
 215  
      *     &lt;/includes&gt;
 216  
      *     &lt;excludes&gt;
 217  
      *       &lt;exclude&gt;org.apache.maven.Public*&lt;/exclude&gt;
 218  
      *     &lt;/excludes&gt;
 219  
      *   &lt;/relocation&gt;
 220  
      * &lt;/relocations&gt;
 221  
      * </pre>
 222  
      * <em>Note:</em> Support for includes exists only since version 1.4.
 223  
      *
 224  
      * @parameter
 225  
      */
 226  
     private PackageRelocation[] relocations;
 227  
 
 228  
     /**
 229  
      * Resource transformers to be used. Please see the "Examples" section for more information on available
 230  
      * transformers and their configuration.
 231  
      *
 232  
      * @parameter
 233  
      */
 234  
     private ResourceTransformer[] transformers;
 235  
 
 236  
     /**
 237  
      * Archive Filters to be used. Allows you to specify an artifact in the form of a composite identifier as used by
 238  
      * {@link #artifactSet} and a set of include/exclude file patterns for filtering which contents of the archive are
 239  
      * added to the shaded jar. From a logical perspective, includes are processed before excludes, thus it's possible
 240  
      * to use an include to collect a set of files from the archive then use excludes to further reduce the set. By
 241  
      * default, all files are included and no files are excluded. If multiple filters apply to an artifact, the
 242  
      * intersection of the matched files will be included in the final JAR. For example:
 243  
      * <pre>
 244  
      * &lt;filters&gt;
 245  
      *   &lt;filter&gt;
 246  
      *     &lt;artifact&gt;junit:junit&lt;/artifact&gt;
 247  
      *     &lt;includes&gt;
 248  
      *       &lt;include&gt;org/junit/**&lt;/include&gt;
 249  
      *     &lt;/includes&gt;
 250  
      *     &lt;excludes&gt;
 251  
      *       &lt;exclude&gt;org/junit/experimental/**&lt;/exclude&gt;
 252  
      *     &lt;/excludes&gt;
 253  
      *   &lt;/filter&gt;
 254  
      * &lt;/filters&gt;
 255  
      * </pre>
 256  
      *
 257  
      * @parameter
 258  
      */
 259  
     private ArchiveFilter[] filters;
 260  
 
 261  
     /**
 262  
      * The destination directory for the shaded artifact.
 263  
      *
 264  
      * @parameter default-value="${project.build.directory}"
 265  
      */
 266  
     private File outputDirectory;
 267  
 
 268  
     /**
 269  
      * The name of the shaded artifactId.
 270  
      * <p/>
 271  
      * If you like to change the name of the native artifact, you may use the &lt;build>&lt;finalName> setting.
 272  
      * If this is set to something different than &lt;build>&lt;finalName>, no file replacement
 273  
      * will be performed, even if shadedArtifactAttached is being used.
 274  
      *
 275  
      * @parameter expression="${finalName}"
 276  
      */
 277  
     private String finalName;
 278  
 
 279  
     /**
 280  
      * The name of the shaded artifactId. So you may want to use a different artifactId and keep
 281  
      * the standard version. If the original artifactId was "foo" then the final artifact would
 282  
      * be something like foo-1.0.jar. So if you change the artifactId you might have something
 283  
      * like foo-special-1.0.jar.
 284  
      *
 285  
      * @parameter expression="${shadedArtifactId}" default-value="${project.artifactId}"
 286  
      */
 287  
     private String shadedArtifactId;
 288  
 
 289  
     /**
 290  
      * If specified, this will include only artifacts which have groupIds which
 291  
      * start with this.
 292  
      *
 293  
      * @parameter expression="${shadedGroupFilter}"
 294  
      */
 295  
     private String shadedGroupFilter;
 296  
 
 297  
     /**
 298  
      * Defines whether the shaded artifact should be attached as classifier to
 299  
      * the original artifact.  If false, the shaded jar will be the main artifact
 300  
      * of the project
 301  
      *
 302  
      * @parameter expression="${shadedArtifactAttached}" default-value="false"
 303  
      */
 304  
     private boolean shadedArtifactAttached;
 305  
 
 306  
     /**
 307  
      * Flag whether to generate a simplified POM for the shaded artifact. If set to <code>true</code>, dependencies that
 308  
      * have been included into the uber JAR will be removed from the <code>&lt;dependencies&gt;</code> section of the
 309  
      * generated POM. The reduced POM will be named <code>dependency-reduced-pom.xml</code> and is stored into the same
 310  
      * directory as the shaded artifact. Unless you also specify dependencyReducedPomLocation, the plugin will
 311  
      * create a temporary file named <code>dependency-reduced-pom.xml</code> in the project basedir. 
 312  
      *
 313  
      * @parameter expression="${createDependencyReducedPom}" default-value="true"
 314  
      */
 315  
     private boolean createDependencyReducedPom;
 316  
     
 317  
     
 318  
     /**
 319  
      *  @parameter expression="${dependencyReducedPomLocation}" defaultValue="${basedir}/dependency-reduced-pom.xml"
 320  
      */
 321  
     private File dependencyReducedPomLocation;
 322  
 
 323  
     /**
 324  
      * When true, dependencies are kept in the pom but with scope 'provided'; when false,
 325  
      * the dependency is removed.
 326  
      *
 327  
      * @parameter expression="${keepDependenciesWithProvidedScope}" default-value="false"
 328  
      */
 329  
     private boolean keepDependenciesWithProvidedScope;
 330  
 
 331  
     /**
 332  
      * When true, transitive deps of removed dependencies are promoted to direct dependencies.
 333  
      * This should allow the drop in replacement of the removed deps with the new shaded
 334  
      * jar and everything should still work.
 335  
      *
 336  
      * @parameter expression="${promoteTransitiveDependencies}" default-value="false"
 337  
      */
 338  
     private boolean promoteTransitiveDependencies;
 339  
 
 340  
     /**
 341  
      * The name of the classifier used in case the shaded artifact is attached.
 342  
      *
 343  
      * @parameter expression="${shadedClassifierName}" default-value="shaded"
 344  
      */
 345  
     private String shadedClassifierName;
 346  
 
 347  
     /**
 348  
      * When true, it will attempt to create a sources jar as well
 349  
      *
 350  
      * @parameter expression="${createSourcesJar}" default-value="false"
 351  
      */
 352  
     private boolean createSourcesJar;
 353  
 
 354  
     /**
 355  
      * When true, dependencies will be stripped down on the class level to only the transitive hull required for the
 356  
      * artifact. <em>Note:</em> Usage of this feature requires Java 1.5 or higher.
 357  
      *
 358  
      * @parameter default-value="false"
 359  
      * @since 1.4
 360  
      */
 361  
     private boolean minimizeJar;
 362  
 
 363  
     /**
 364  
      * The path to the output file for the shaded artifact. When this parameter is set, the created archive will neither
 365  
      * replace the project's main artifact nor will it be attached. Hence, this parameter causes the parameters
 366  
      * {@link #finalName}, {@link #shadedArtifactAttached}, {@link #shadedClassifierName} and
 367  
      * {@link #createDependencyReducedPom} to be ignored when used.
 368  
      *
 369  
      * @parameter
 370  
      * @since 1.3
 371  
      */
 372  
     private File outputFile;
 373  
 
 374  
     /**
 375  
      * You can pass here the roleHint about your own Shader implementation plexus component.
 376  
      *
 377  
      * @parameter
 378  
      * @since 1.6
 379  
      */
 380  
     private String shaderHint;
 381  
 
 382  
     /**
 383  
      * @since 1.6
 384  
      */
 385  
     private PlexusContainer plexusContainer;
 386  
 
 387  
     public void contextualize( Context context )
 388  
         throws ContextException
 389  
     {
 390  0
         plexusContainer = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
 391  0
     }
 392  
 
 393  
     /**
 394  
      * @throws MojoExecutionException
 395  
      */
 396  
     public void execute()
 397  
         throws MojoExecutionException
 398  
     {
 399  
 
 400  0
         if ( shaderHint != null )
 401  
         {
 402  
             try
 403  
             {
 404  0
                 shader = (Shader) plexusContainer.lookup( Shader.ROLE, shaderHint );
 405  
             }
 406  0
             catch ( ComponentLookupException e )
 407  
             {
 408  0
                 throw new MojoExecutionException(
 409  
                     "unable to lookup own Shader implementation with hint:'" + shaderHint + "'", e );
 410  0
             }
 411  
         }
 412  
 
 413  0
         Set<File> artifacts = new LinkedHashSet<File>();
 414  0
         Set<String> artifactIds = new LinkedHashSet<String>();
 415  0
         Set<File> sourceArtifacts = new LinkedHashSet<File>();
 416  
 
 417  0
         ArtifactSelector artifactSelector =
 418  
             new ArtifactSelector( project.getArtifact(), artifactSet, shadedGroupFilter );
 419  
 
 420  0
         if ( artifactSelector.isSelected( project.getArtifact() ) && 
 421  
                         !"pom".equals( project.getArtifact().getType() ) )
 422  
         {
 423  0
             if ( invalidMainArtifact() )
 424  
             {
 425  0
                 getLog().error( "The project main artifact does not exist. This could have the following" );
 426  0
                 getLog().error( "reasons:" );
 427  0
                 getLog().error( "- You have invoked the goal directly from the command line. This is not" );
 428  0
                 getLog().error( "  supported. Please add the goal to the default lifecycle via an" );
 429  0
                 getLog().error( "  <execution> element in your POM and use \"mvn package\" to have it run." );
 430  0
                 getLog().error( "- You have bound the goal to a lifecycle phase before \"package\". Please" );
 431  0
                 getLog().error( "  remove this binding from your POM such that the goal will be run in" );
 432  0
                 getLog().error( "  the proper phase." );
 433  0
                 getLog().error( "- You removed the configuration of the maven-jar-plugin that produces the main artifact." );
 434  0
                 throw new MojoExecutionException(
 435  
                     "Failed to create shaded artifact, " + "project main artifact does not exist." );
 436  
             }
 437  
 
 438  0
             artifacts.add( project.getArtifact().getFile() );
 439  
 
 440  0
             if ( createSourcesJar )
 441  
             {
 442  0
                 File file = shadedSourcesArtifactFile();
 443  0
                 if ( file.isFile() )
 444  
                 {
 445  0
                     sourceArtifacts.add( file );
 446  
                 }
 447  
             }
 448  
         }
 449  
 
 450  0
         for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); )
 451  
         {
 452  0
             Artifact artifact = (Artifact) it.next();
 453  
 
 454  0
             if ( !artifactSelector.isSelected( artifact ) )
 455  
             {
 456  0
                 getLog().info( "Excluding " + artifact.getId() + " from the shaded jar." );
 457  
 
 458  0
                 continue;
 459  
             }
 460  
 
 461  0
             if ( "pom".equals( artifact.getType() ) )
 462  
             {
 463  0
                 getLog().info( "Skipping pom dependency " + artifact.getId() + " in the shaded jar." );
 464  0
                 continue;
 465  
             }
 466  
 
 467  0
             getLog().info( "Including " + artifact.getId() + " in the shaded jar." );
 468  
 
 469  0
             artifacts.add( artifact.getFile() );
 470  0
             artifactIds.add( getId( artifact ) );
 471  
 
 472  0
             if ( createSourcesJar )
 473  
             {
 474  0
                 File file = resolveArtifactSources( artifact );
 475  0
                 if ( file != null )
 476  
                 {
 477  0
                     sourceArtifacts.add( file );
 478  
                 }
 479  
             }
 480  0
         }
 481  
 
 482  0
         File outputJar = ( outputFile != null ) ? outputFile : shadedArtifactFileWithClassifier();
 483  0
         File sourcesJar = shadedSourceArtifactFileWithClassifier();
 484  
 
 485  
         // Now add our extra resources
 486  
         try
 487  
         {
 488  0
             List<Filter> filters = getFilters();
 489  
 
 490  0
             List<Relocator> relocators = getRelocators();
 491  
 
 492  0
             List<ResourceTransformer> resourceTransformers = getResourceTransformers();
 493  
 
 494  0
             shader.shade( artifacts, outputJar, filters, relocators, resourceTransformers );
 495  
 
 496  0
             if ( createSourcesJar )
 497  
             {
 498  0
                 shader.shade( sourceArtifacts, sourcesJar, filters, relocators, resourceTransformers );
 499  
             }
 500  
 
 501  0
             if ( outputFile == null )
 502  
             {
 503  0
                 boolean renamed = false;
 504  
 
 505  
                 // rename the output file if a specific finalName is set
 506  
                 // but don't rename if the finalName is the <build><finalName>
 507  
                 // because this will be handled implicitly later
 508  0
                 if ( finalName != null && finalName.length() > 0 && !finalName.equals(
 509  
                     project.getBuild().getFinalName() ) )
 510  
                 {
 511  0
                     String finalFileName = finalName + "." + project.getArtifact().getArtifactHandler().getExtension();
 512  0
                     File finalFile = new File( outputDirectory, finalFileName );
 513  0
                     replaceFile( finalFile, outputJar );
 514  0
                     outputJar = finalFile;
 515  
 
 516  0
                     renamed = true;
 517  
                 }
 518  
 
 519  0
                 if ( shadedArtifactAttached )
 520  
                 {
 521  0
                     getLog().info( "Attaching shaded artifact." );
 522  0
                     projectHelper.attachArtifact( project, project.getArtifact().getType(), shadedClassifierName,
 523  
                                                   outputJar );
 524  0
                     if ( createSourcesJar )
 525  
                     {
 526  0
                         projectHelper.attachArtifact( project, "jar", shadedClassifierName + "-sources", sourcesJar );
 527  
                     }
 528  
                 }
 529  0
                 else if ( !renamed )
 530  
                 {
 531  0
                     getLog().info( "Replacing original artifact with shaded artifact." );
 532  0
                     File originalArtifact = project.getArtifact().getFile();
 533  0
                     replaceFile( originalArtifact, outputJar );
 534  
 
 535  0
                     if ( createSourcesJar )
 536  
                     {
 537  0
                         File shadedSources = shadedSourcesArtifactFile();
 538  
 
 539  0
                         replaceFile( shadedSources, sourcesJar );
 540  
 
 541  0
                         projectHelper.attachArtifact( project, "jar", "sources", shadedSources );
 542  
                     }
 543  
 
 544  0
                     if ( createDependencyReducedPom )
 545  
                     {
 546  0
                         createDependencyReducedPom( artifactIds );
 547  
                     }
 548  
                 }
 549  
             }
 550  
         }
 551  0
         catch ( Exception e )
 552  
         {
 553  0
             throw new MojoExecutionException( "Error creating shaded jar: " + e.getMessage(), e );
 554  0
         }
 555  0
     }
 556  
 
 557  
     private boolean invalidMainArtifact( )
 558  
     {
 559  0
         return project.getArtifact().getFile() == null || ! project.getArtifact().getFile().isFile();                                       
 560  
     }
 561  
 
 562  
     private void replaceFile( File oldFile, File newFile )
 563  
         throws MojoExecutionException
 564  
     {
 565  0
         getLog().info( "Replacing " + oldFile + " with " + newFile );
 566  
 
 567  0
         File origFile = new File( outputDirectory, "original-" + oldFile.getName() );
 568  0
         if ( oldFile.exists() && !oldFile.renameTo( origFile ) )
 569  
         {
 570  
             //try a gc to see if an unclosed stream needs garbage collecting
 571  0
             System.gc();
 572  0
             System.gc();
 573  
 
 574  0
             if ( !oldFile.renameTo( origFile ) )
 575  
             {
 576  
                 // Still didn't work.   We'll do a copy
 577  
                 try
 578  
                 {
 579  0
                     FileOutputStream fout = new FileOutputStream( origFile );
 580  0
                     FileInputStream fin = new FileInputStream( oldFile );
 581  
                     try
 582  
                     {
 583  0
                         IOUtil.copy( fin, fout );
 584  
                     }
 585  
                     finally
 586  
                     {
 587  0
                         IOUtil.close( fin );
 588  0
                         IOUtil.close( fout );
 589  0
                     }
 590  
                 }
 591  0
                 catch ( IOException ex )
 592  
                 {
 593  
                     //kind of ignorable here.   We're just trying to save the original
 594  0
                     getLog().warn( ex );
 595  0
                 }
 596  
             }
 597  
         }
 598  0
         if ( !newFile.renameTo( oldFile ) )
 599  
         {
 600  
             //try a gc to see if an unclosed stream needs garbage collecting
 601  0
             System.gc();
 602  0
             System.gc();
 603  
 
 604  0
             if ( !newFile.renameTo( oldFile ) )
 605  
             {
 606  
                 // Still didn't work.   We'll do a copy
 607  
                 try
 608  
                 {
 609  0
                     FileOutputStream fout = new FileOutputStream( oldFile );
 610  0
                     FileInputStream fin = new FileInputStream( newFile );
 611  
                     try
 612  
                     {
 613  0
                         IOUtil.copy( fin, fout );
 614  
                     }
 615  
                     finally
 616  
                     {
 617  0
                         IOUtil.close( fin );
 618  0
                         IOUtil.close( fout );
 619  0
                     }
 620  
                 }
 621  0
                 catch ( IOException ex )
 622  
                 {
 623  0
                     throw new MojoExecutionException( "Could not replace original artifact with shaded artifact!", ex );
 624  0
                 }
 625  
             }
 626  
         }
 627  0
     }
 628  
 
 629  
     private File resolveArtifactSources( Artifact artifact )
 630  
     {
 631  
 
 632  1
         Artifact resolvedArtifact =
 633  
             artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(),
 634  
                                                           artifact.getVersion(), "java-source", "sources" );
 635  
 
 636  
         try
 637  
         {
 638  1
             artifactResolver.resolve( resolvedArtifact, remoteArtifactRepositories, localRepository );
 639  
         }
 640  0
         catch ( ArtifactNotFoundException e )
 641  
         {
 642  
             // ignore, the jar has not been found
 643  
         }
 644  0
         catch ( ArtifactResolutionException e )
 645  
         {
 646  0
             getLog().warn( "Could not get sources for " + artifact );
 647  1
         }
 648  
 
 649  1
         if ( resolvedArtifact.isResolved() )
 650  
         {
 651  1
             return resolvedArtifact.getFile();
 652  
         }
 653  0
         return null;
 654  
     }
 655  
 
 656  
     private List<Relocator> getRelocators()
 657  
     {
 658  0
         List<Relocator> relocators = new ArrayList<Relocator>();
 659  
 
 660  0
         if ( relocations == null )
 661  
         {
 662  0
             return relocators;
 663  
         }
 664  
 
 665  0
         for ( int i = 0; i < relocations.length; i++ )
 666  
         {
 667  0
             PackageRelocation r = relocations[i];
 668  
 
 669  0
             relocators.add( new SimpleRelocator( r.getPattern(), r.getShadedPattern(), r.getIncludes(), r.getExcludes(),
 670  
                                                  r.isRawString() ) );
 671  
         }
 672  
 
 673  0
         return relocators;
 674  
     }
 675  
 
 676  
     private List<ResourceTransformer> getResourceTransformers()
 677  
     {
 678  0
         if ( transformers == null )
 679  
         {
 680  0
             return Collections.emptyList();
 681  
         }
 682  
 
 683  0
         return Arrays.asList( transformers );
 684  
     }
 685  
 
 686  
     private List<Filter> getFilters()
 687  
         throws MojoExecutionException
 688  
     {
 689  1
         List<Filter> filters = new ArrayList<Filter>();
 690  1
         List<SimpleFilter> simpleFilters = new ArrayList<SimpleFilter>();
 691  
 
 692  1
         if ( this.filters != null && this.filters.length > 0 )
 693  
         {
 694  1
             Map<Artifact, ArtifactId> artifacts = new HashMap<Artifact, ArtifactId>();
 695  
 
 696  1
             artifacts.put( project.getArtifact(), new ArtifactId( project.getArtifact() ) );
 697  
 
 698  1
             for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); )
 699  
             {
 700  0
                 Artifact artifact = (Artifact) it.next();
 701  
 
 702  0
                 artifacts.put( artifact, new ArtifactId( artifact ) );
 703  0
             }
 704  
 
 705  2
             for ( int i = 0; i < this.filters.length; i++ )
 706  
             {
 707  1
                 ArchiveFilter filter = this.filters[i];
 708  
 
 709  1
                 ArtifactId pattern = new ArtifactId( filter.getArtifact() );
 710  
 
 711  1
                 Set<File> jars = new HashSet<File>();
 712  
 
 713  1
                 for ( Iterator it = artifacts.entrySet().iterator(); it.hasNext(); )
 714  
                 {
 715  1
                     Map.Entry entry = (Map.Entry) it.next();
 716  
 
 717  1
                     if ( ( (ArtifactId) entry.getValue() ).matches( pattern ) )
 718  
                     {
 719  1
                         Artifact artifact = (Artifact) entry.getKey();
 720  
 
 721  1
                         jars.add( artifact.getFile() );
 722  
 
 723  1
                         if ( createSourcesJar )
 724  
                         {
 725  1
                             File file = resolveArtifactSources( artifact );
 726  1
                             if ( file != null )
 727  
                             {
 728  1
                                 jars.add( file );
 729  
                             }
 730  
                         }
 731  
                     }
 732  1
                 }
 733  
 
 734  1
                 if ( jars.isEmpty() )
 735  
                 {
 736  0
                     getLog().info( "No artifact matching filter " + filter.getArtifact() );
 737  
 
 738  0
                     continue;
 739  
                 }
 740  
 
 741  1
                 simpleFilters.add( new SimpleFilter( jars, filter.getIncludes(), filter.getExcludes() ) );
 742  
             }
 743  
         }
 744  
 
 745  1
         filters.addAll( simpleFilters );
 746  
 
 747  1
         if ( minimizeJar )
 748  
         {
 749  0
             getLog().info( "Minimizing jar " + project.getArtifact() );
 750  
 
 751  
             try
 752  
             {
 753  0
                 filters.add( new MinijarFilter( project, getLog(), simpleFilters ) );
 754  
             }
 755  0
             catch ( IOException e )
 756  
             {
 757  0
                 throw new MojoExecutionException( "Failed to analyze class dependencies", e );
 758  0
             }
 759  
         }
 760  
 
 761  1
         return filters;
 762  
     }
 763  
 
 764  
     private File shadedArtifactFileWithClassifier()
 765  
     {
 766  0
         Artifact artifact = project.getArtifact();
 767  0
         final String shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-" + shadedClassifierName + "."
 768  
             + artifact.getArtifactHandler().getExtension();
 769  0
         return new File( outputDirectory, shadedName );
 770  
     }
 771  
 
 772  
     private File shadedSourceArtifactFileWithClassifier()
 773  
     {
 774  0
         Artifact artifact = project.getArtifact();
 775  0
         final String shadedName =
 776  
             shadedArtifactId + "-" + artifact.getVersion() + "-" + shadedClassifierName + "-sources."
 777  
                 + artifact.getArtifactHandler().getExtension();
 778  0
         return new File( outputDirectory, shadedName );
 779  
     }
 780  
 
 781  
     private File shadedSourcesArtifactFile()
 782  
     {
 783  0
         Artifact artifact = project.getArtifact();
 784  
 
 785  
         String shadedName;
 786  
 
 787  0
         if ( project.getBuild().getFinalName() != null )
 788  
         {
 789  0
             shadedName = project.getBuild().getFinalName() + "-sources." + artifact.getArtifactHandler().getExtension();
 790  
         }
 791  
         else
 792  
         {
 793  0
             shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-sources."
 794  
                 + artifact.getArtifactHandler().getExtension();
 795  
         }
 796  
 
 797  0
         return new File( outputDirectory, shadedName );
 798  
     }
 799  
 
 800  
     // We need to find the direct dependencies that have been included in the uber JAR so that we can modify the
 801  
     // POM accordingly.
 802  
     private void createDependencyReducedPom( Set<String> artifactsToRemove )
 803  
         throws IOException, DependencyTreeBuilderException, ProjectBuildingException
 804  
     {
 805  0
         Model model = project.getOriginalModel();
 806  0
         List<Dependency> dependencies = new ArrayList<Dependency>();
 807  
 
 808  0
         boolean modified = false;
 809  
 
 810  0
         List<Dependency> transitiveDeps = new ArrayList<Dependency>();
 811  
 
 812  0
         for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); )
 813  
         {
 814  0
             Artifact artifact = (Artifact) it.next();
 815  
 
 816  0
             if ( "pom".equals( artifact.getType() ) )
 817  
             {
 818  
                 // don't include pom type dependencies in dependency reduced pom
 819  0
                 continue;
 820  
             }
 821  
 
 822  
             //promote
 823  0
             Dependency dep = new Dependency();
 824  0
             dep.setArtifactId( artifact.getArtifactId() );
 825  0
             if ( artifact.hasClassifier() )
 826  
             {
 827  0
                 dep.setClassifier( artifact.getClassifier() );
 828  
             }
 829  0
             dep.setGroupId( artifact.getGroupId() );
 830  0
             dep.setOptional( artifact.isOptional() );
 831  0
             dep.setScope( artifact.getScope() );
 832  0
             dep.setType( artifact.getType() );
 833  0
             dep.setVersion( artifact.getVersion() );
 834  
 
 835  
             //we'll figure out the exclusions in a bit.
 836  
 
 837  0
             transitiveDeps.add( dep );
 838  0
         }
 839  0
         List<Dependency> origDeps = project.getDependencies();
 840  
 
 841  0
         if ( promoteTransitiveDependencies )
 842  
         {
 843  0
             origDeps = transitiveDeps;
 844  
         }
 845  
 
 846  0
         for ( Iterator<Dependency> i = origDeps.iterator(); i.hasNext(); )
 847  
         {
 848  0
             Dependency d = i.next();
 849  
 
 850  0
             dependencies.add( d );
 851  
 
 852  0
             String id = getId( d );
 853  
 
 854  0
             if ( artifactsToRemove.contains( id ) )
 855  
             {
 856  0
                 modified = true;
 857  
 
 858  0
                 if ( keepDependenciesWithProvidedScope )
 859  
                 {
 860  0
                     d.setScope( "provided" );
 861  
                 }
 862  
                 else
 863  
                 {
 864  0
                     dependencies.remove( d );
 865  
                 }
 866  
             }
 867  0
         }
 868  
 
 869  
         // Check to see if we have a reduction and if so rewrite the POM.
 870  0
         if ( modified )
 871  
         {
 872  0
             while ( modified )
 873  
             {
 874  
 
 875  0
                 model.setDependencies( dependencies );
 876  
 
 877  0
                 if ( dependencyReducedPomLocation == null )
 878  
                 {
 879  0
                     dependencyReducedPomLocation = new File ( outputDirectory, "dependency-reduced-pom.xml" );
 880  
                 }
 881  
                 
 882  0
                 File f = dependencyReducedPomLocation;
 883  0
                 if ( f.exists() )
 884  
                 {
 885  0
                     f.delete();
 886  
                 }
 887  
 
 888  0
                 Writer w = WriterFactory.newXmlWriter( f );
 889  
 
 890  0
                 String origRelativePath = null;
 891  0
                 String replaceRelativePath = null;
 892  0
                 if ( model.getParent() != null)
 893  
                 {
 894  0
                     origRelativePath = model.getParent().getRelativePath();
 895  
                     
 896  
                 }
 897  0
                 replaceRelativePath = origRelativePath;
 898  
 
 899  0
                 if ( origRelativePath == null )
 900  
                 {
 901  0
                     origRelativePath = "../pom.xml";
 902  
                 }
 903  
 
 904  0
                 if ( model.getParent() != null ) 
 905  
                 {
 906  0
                     File parentFile = new File( project.getBasedir(), model.getParent().getRelativePath() ).getCanonicalFile();
 907  0
                     if ( !parentFile.isFile() )
 908  
                     {
 909  0
                         parentFile = new File( parentFile, "pom.xml");
 910  
                     }
 911  
                     
 912  0
                     parentFile = parentFile.getCanonicalFile();
 913  
                     
 914  0
                     String relPath = RelativizePath.convertToRelativePath( parentFile, f );
 915  0
                     model.getParent().setRelativePath( relPath );
 916  
                 }
 917  
                 
 918  
                 try
 919  
                 {
 920  0
                     PomWriter.write( w, model, true );
 921  
                 }
 922  
                 finally
 923  
                 {
 924  0
                     if ( model.getParent() != null )
 925  
                     {
 926  0
                         model.getParent().setRelativePath( replaceRelativePath );
 927  
                     }
 928  0
                     w.close();
 929  0
                 }
 930  
 
 931  0
                 MavenProject p2 = mavenProjectBuilder.build( f, localRepository, null );
 932  0
                 modified = updateExcludesInDeps( p2, dependencies, transitiveDeps );
 933  
 
 934  0
             }
 935  
 
 936  0
             project.setFile( dependencyReducedPomLocation );
 937  
         }
 938  0
     }
 939  
     
 940  
     private String getId( Artifact artifact )
 941  
     {
 942  0
         return getId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier() );
 943  
     }
 944  
 
 945  
     private String getId( Dependency dependency )
 946  
     {
 947  0
         return getId( dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(),
 948  
                       dependency.getClassifier() );
 949  
     }
 950  
 
 951  
     private String getId( String groupId, String artifactId, String type, String classifier )
 952  
     {
 953  0
         return groupId + ":" + artifactId + ":" + type + ":" + ( ( classifier != null ) ? classifier : "" );
 954  
     }
 955  
 
 956  
     public boolean updateExcludesInDeps( MavenProject project, List<Dependency> dependencies, List<Dependency> transitiveDeps )
 957  
         throws DependencyTreeBuilderException
 958  
     {
 959  0
         DependencyNode node = dependencyTreeBuilder.buildDependencyTree( project, localRepository, artifactFactory,
 960  
                                                                          artifactMetadataSource, null,
 961  
                                                                          artifactCollector );
 962  0
         boolean modified = false;
 963  0
         Iterator it = node.getChildren().listIterator();
 964  0
         while ( it.hasNext() )
 965  
         {
 966  0
             DependencyNode n2 = (DependencyNode) it.next();
 967  0
             Iterator it2 = n2.getChildren().listIterator();
 968  0
             while ( it2.hasNext() )
 969  
             {
 970  0
                 DependencyNode n3 = (DependencyNode) it2.next();
 971  
                 //anything two levels deep that is marked "included"
 972  
                 //is stuff that was excluded by the original poms, make sure it
 973  
                 //remains excluded IF promoting transitives.
 974  0
                 if ( n3.getState() == DependencyNode.INCLUDED )
 975  
                 {
 976  
                     //check if it really isn't in the list of original dependencies.  Maven
 977  
                     //prior to 2.0.8 may grab versions from transients instead of
 978  
                     //from the direct deps in which case they would be marked included
 979  
                     //instead of OMITTED_FOR_DUPLICATE
 980  
 
 981  
                     //also, if not promoting the transitives, level 2's would be included
 982  0
                     boolean found = false;
 983  0
                     for ( int x = 0; x < transitiveDeps.size(); x++ )
 984  
                     {
 985  0
                         Dependency dep = transitiveDeps.get( x );
 986  0
                         if ( dep.getArtifactId().equals( n3.getArtifact().getArtifactId() ) && dep.getGroupId().equals(
 987  
                             n3.getArtifact().getGroupId() ) )
 988  
                         {
 989  0
                             found = true;
 990  
                         }
 991  
 
 992  
                     }
 993  
 
 994  0
                     if ( !found )
 995  
                     {
 996  0
                         for ( int x = 0; x < dependencies.size(); x++ )
 997  
                         {
 998  0
                             Dependency dep = dependencies.get( x );
 999  0
                             if ( dep.getArtifactId().equals( n2.getArtifact().getArtifactId() )
 1000  
                                 && dep.getGroupId().equals( n2.getArtifact().getGroupId() ) )
 1001  
                             {
 1002  0
                                 Exclusion exclusion = new Exclusion();
 1003  0
                                 exclusion.setArtifactId( n3.getArtifact().getArtifactId() );
 1004  0
                                 exclusion.setGroupId( n3.getArtifact().getGroupId() );
 1005  0
                                 dep.addExclusion( exclusion );
 1006  0
                                 modified = true;
 1007  0
                                 break;
 1008  
                             }
 1009  
                         }
 1010  
                     }
 1011  
                 }
 1012  0
             }
 1013  0
         }
 1014  0
         return modified;
 1015  
     }
 1016  
 }