001    /*
002     * SonarQube, open source software quality management tool.
003     * Copyright (C) 2008-2014 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * SonarQube is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * SonarQube is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public License
017     * along with this program; if not, write to the Free Software Foundation,
018     * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019     */
020    package org.sonar.batch.maven;
021    
022    import org.apache.maven.execution.MavenSession;
023    import org.apache.maven.project.MavenProject;
024    import org.sonar.api.batch.SupportedEnvironment;
025    import org.sonar.api.batch.bootstrap.ProjectBuilder;
026    import org.sonar.api.batch.bootstrap.ProjectDefinition;
027    import org.sonar.api.batch.bootstrap.ProjectReactor;
028    
029    import java.util.List;
030    
031    /**
032     * Class that inject MavenProject in each module container
033     */
034    @SupportedEnvironment("maven")
035    public class MavenProjectBuilder extends ProjectBuilder {
036    
037      private final MavenSession mavenSession;
038    
039      public MavenProjectBuilder(MavenSession mavenSession) {
040        this.mavenSession = mavenSession;
041      }
042    
043      @Override
044      public void build(Context context) {
045        ProjectReactor reactor = context.projectReactor();
046        for (ProjectDefinition moduleDef : reactor.getProjects()) {
047          setMavenProjectIfApplicable(moduleDef);
048        }
049      }
050    
051      private void setMavenProjectIfApplicable(ProjectDefinition definition) {
052        if (mavenSession != null) {
053          String moduleKey = definition.getKey();
054          for (MavenProject mavenModule : (List<MavenProject>) mavenSession.getSortedProjects()) {
055            String mavenModuleKey = mavenModule.getGroupId() + ":" + mavenModule.getArtifactId();
056            if (mavenModuleKey.equals(moduleKey) && !definition.getContainerExtensions().contains(mavenModule)) {
057              definition.addContainerExtension(mavenModule);
058            }
059          }
060        }
061      }
062    
063    }