Package ch.hortis.sonar.mvn

Source Code of ch.hortis.sonar.mvn.PrepareMojo

/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.hortis.sonar.mvn;

import ch.hortis.sonar.mvn.reports.ReportHandler;

import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.cli.ConsoleDownloadMonitor;
import org.apache.maven.embedder.MavenEmbedder;
import org.apache.maven.embedder.MavenEmbedderConsoleLogger;
import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.embedder.PlexusLoggerAdapter;
import org.apache.maven.monitor.event.DefaultEventMonitor;
import org.apache.maven.monitor.event.EventMonitor;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;

import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;

/**
* @goal prepare
*/
public class PrepareMojo extends AbstractMojo {

  /**
   * The maven project running this plugin
   *
   * @parameter expression="${project}"
   * @required
   * @readonly
   */
  private org.apache.maven.project.MavenProject mavenProject;

  /**
   * we clone the mavenProject because its plugins configuration is overriden.
   */
  private org.apache.maven.project.MavenProject executedProject;

  private MavenEmbedder maven = null;

  public void execute() throws MojoExecutionException {
    initMavenEmbedder();
    preparePom();
    savePomCopy( );
    executeGoals();
    finalizeMavenEmbedder();
  }

  protected void initMavenEmbedder() throws MojoExecutionException {
    try {
      this.maven = new MavenEmbedder();
      maven.setClassLoader(Thread.currentThread().getContextClassLoader());
      maven.setLogger(new MavenEmbedderConsoleLogger());
      maven.setAlignWithUserInstallation(true);
      maven.start();
    } catch (Exception e) {
      throw new MojoExecutionException( "Can not start the maven embedder", e);
    }

    File pom = mavenProject.getFile();
    try {
      this.executedProject = maven.readProjectWithDependencies(pom);
    } catch (Exception e) {
      throw new MojoExecutionException("Can not read the maven project " + pom.getAbsolutePath(), e);
    }
  }

  private void finalizeMavenEmbedder() {
    try {
      maven.stop();
    } catch (MavenEmbedderException e) {
      getLog().warn("can not stop the maven embedder", e);
    }
  }

  protected void executeGoals() throws MojoExecutionException {
    EventMonitor eventMonitor = new DefaultEventMonitor(new PlexusLoggerAdapter(maven.getLogger()));
    boolean hasJavaSources = PomUtils.getJavaSourceFiles( executedProject ).size()>0;
    boolean hasJavaTests = PomUtils.getJavaTestFiles( executedProject ).size()>0;

    for (Report report : Report.getReports()) {
      ReportHandler reportHandler = report.getReportHandler();
      if (reportHandler!=null) {
        if ( (hasJavaSources || reportHandler.executeEvenIfNoJavaSources())
            && (hasJavaTests || reportHandler.executeEvenIfNoJavaTests()) &&
            reportHandler.execute( executedProject )) {
          executeReport(eventMonitor, reportHandler);
        }
      }
    }
  }

  private void executeReport(EventMonitor eventMonitor, ReportHandler reportHandler) throws MojoExecutionException {
    for (String command : reportHandler.getCommands()) {
      try {
        maven.execute( executedProject, Arrays.asList(new String[]{command}), eventMonitor,
                       new ConsoleDownloadMonitor(), null, executedProject.getBasedir());
      } catch (Throwable e) {
        if (reportHandler.mustFailOnError()) {
          getLog().error( "Cannot execute the command " + command, e );
          throw new MojoExecutionException( "Cannot execute the command " + command, e );
        } else {
          getLog().warn( "Cannot execute the command " + command, e );
        }
      }
    }
  }

  protected void preparePom() {
    for (ReportHandler reportHandler : Report.getReportHandlers()) {
      reportHandler.preparePom(executedProject);
    }
    if (executedProject.getReporting() != null) {
      executedProject.getReporting().setPlugins(null);
    }
    //  avoid a bug with maven when artifact versionRange is null
    // should be fixed with maven 2.0.7 (bug with 2.0.6)
    if ( executedProject.getArtifact().getVersionRange() == null ) {
      getLog().warn( "Project has no version range" );
      MavenProject parent = executedProject;
      while ( parent.getParent() != null ) {
        parent = parent.getParent();
        if ( parent.getVersion() != null ) {
          executedProject.getArtifact().setVersionRange( VersionRange.createFromVersion( parent.getVersion() ) );
        }
      }
      if ( executedProject.getArtifact().getVersionRange() == null ) {
        getLog().warn( "Unable to define POM artifact version, please provide it in the project POM, forcing to version 1.0" );
        executedProject.getArtifact().setVersionRange( VersionRange.createFromVersion( "1.0" ) );
      } else {
        getLog().info( "Pom version set to " + executedProject.getArtifact().getVersionRange() );
      }
    }
  }

  protected void savePomCopy( ) {
    File targetDir = new File( executedProject.getBuild().getDirectory());
    try {
      if (!targetDir.exists()) {
        targetDir.mkdir();
      }
      executedProject.writeModel( new FileWriter( new File(targetDir, "pom-sonar.xml"), false ));

    } catch (Exception e) {
      getLog().warn("can not save the sonar pom.xml to " + targetDir, e);
    }
  }
}
TOP

Related Classes of ch.hortis.sonar.mvn.PrepareMojo

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.