001package org.apache.maven.plugins.enforcer;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *  http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import org.apache.maven.artifact.Artifact;
023import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
024import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
025import org.apache.maven.execution.MavenSession;
026import org.apache.maven.plugin.logging.Log;
027import org.apache.maven.plugins.enforcer.utils.ArtifactUtils;
028import org.apache.maven.project.DefaultProjectBuildingRequest;
029import org.apache.maven.project.MavenProject;
030import org.apache.maven.project.ProjectBuildingRequest;
031import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
032import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException;
033import org.apache.maven.shared.dependency.graph.DependencyNode;
034import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
035import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
036
037import java.util.HashSet;
038import java.util.Set;
039
040/**
041 * Abstract Rule for banning dependencies.
042 *
043 * @author <a href="mailto:brianf@apache.org">Brian Fox</a>
044 */
045public abstract class AbstractBanDependencies
046    extends AbstractNonCacheableEnforcerRule
047{
048
049    /** Specify if transitive dependencies should be searched (default) or only look at direct dependencies. */
050    private boolean searchTransitive = true;
051
052    private transient DependencyGraphBuilder graphBuilder;
053
054    @Override
055    public void execute( EnforcerRuleHelper helper )
056        throws EnforcerRuleException
057    {
058        MavenProject project;
059        try
060        {
061            project = (MavenProject) helper.evaluate( "${project}" );
062        }
063        catch ( ExpressionEvaluationException eee )
064        {
065            throw new EnforcerRuleException( "Unable to retrieve the MavenProject: ", eee );
066        }
067
068        MavenSession session;
069        try
070        {
071            session = (MavenSession) helper.evaluate( "${session}" );
072        }
073        catch ( ExpressionEvaluationException eee )
074        {
075            throw new EnforcerRuleException( "Unable to retrieve the reactor MavenProject: ", eee );
076        }
077
078        try
079        {
080            graphBuilder = (DependencyGraphBuilder) helper.getComponent( DependencyGraphBuilder.class );
081        }
082        catch ( ComponentLookupException e )
083        {
084            throw new EnforcerRuleException( "Unable to lookup DependencyGraphBuilder: ", e );
085        }
086        
087        ProjectBuildingRequest buildingRequest =
088            new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() );
089        buildingRequest.setProject( project );
090
091        // get the correct list of dependencies
092        Set<Artifact> dependencies = getDependenciesToCheck( buildingRequest );
093
094        // look for banned dependencies
095        Set<Artifact> foundExcludes = checkDependencies( dependencies, helper.getLog() );
096
097        // if any are found, fail the check but list all of them
098        if ( foundExcludes != null && !foundExcludes.isEmpty() )
099        {
100            String message = getMessage();
101
102            StringBuilder buf = new StringBuilder();
103            if ( message != null )
104            {
105                buf.append( message + System.lineSeparator() );
106            }
107            for ( Artifact artifact : foundExcludes )
108            {
109                buf.append( getErrorMessage( artifact ) );
110            }
111            message = buf.toString() + "Use 'mvn dependency:tree' to locate the source of the banned dependencies.";
112
113            throw new EnforcerRuleException( message );
114        }
115
116    }
117
118    protected CharSequence getErrorMessage( Artifact artifact )
119    {
120        return "Found Banned Dependency: " + artifact.getId() + System.lineSeparator();
121    }
122
123    protected Set<Artifact> getDependenciesToCheck( ProjectBuildingRequest buildingRequest )
124    {
125        Set<Artifact> dependencies = null;
126        try
127        {
128            DependencyNode node = graphBuilder.buildDependencyGraph( buildingRequest, null );
129            if ( searchTransitive )
130            {
131                dependencies = ArtifactUtils.getAllDescendants( node );
132            }
133            else if ( node.getChildren() != null )
134            {
135                dependencies = new HashSet<>();
136                for ( DependencyNode depNode : node.getChildren() )
137                {
138                    dependencies.add( depNode.getArtifact() );
139                }
140            }
141        }
142        catch ( DependencyGraphBuilderException e )
143        {
144            // otherwise we need to change the signature of this protected method
145            throw new RuntimeException( e );
146        }
147        return dependencies;
148    }
149
150    /**
151     * Checks the set of dependencies against the list of excludes.
152     *
153     * @param dependencies the dependencies
154     * @param log the log
155     * @return the sets the
156     * @throws EnforcerRuleException the enforcer rule exception
157     */
158    protected abstract Set<Artifact> checkDependencies( Set<Artifact> dependencies, Log log )
159        throws EnforcerRuleException;
160
161    /**
162     * Checks if is search transitive.
163     *
164     * @return the searchTransitive
165     */
166    public boolean isSearchTransitive()
167    {
168        return this.searchTransitive;
169    }
170
171    /**
172     * Sets the search transitive.
173     *
174     * @param theSearchTransitive the searchTransitive to set
175     */
176    public void setSearchTransitive( boolean theSearchTransitive )
177    {
178        this.searchTransitive = theSearchTransitive;
179    }
180
181}