Package ch.hortis.sonar.mvn

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

/*
* This program is copyright (c) 2007 Hortis-GRC SA.
*
* This file is part of Sonar.
* Sonar is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
package ch.hortis.sonar.mvn;

import ch.hortis.sonar.mvn.reports.ReportHandler;
import ch.hortis.sonar.service.WebInterfaceService;
import ch.hortis.sonar.service.WebInterfaceServiceImpl;
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;
 
  /**
   * Sonar host URL
   * @parameter expression="${sonar.host.url}" default-value="http://localhost:9000" alias="sonar.host.url"
   */
  private String sonarHostURL;

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

  private MavenEmbedder maven = null;
 
  private WebInterfaceService webInterfaceService;

  public void execute() throws MojoExecutionException {
    if ( webInterfaceService == null ) {
      webInterfaceService = new WebInterfaceServiceImpl( sonarHostURL );
    }
    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( this, getLog() ) ) {
          executeReport(eventMonitor, reportHandler);
        }
      }
    }
  }

  private void executeReport(EventMonitor eventMonitor, ReportHandler reportHandler) throws MojoExecutionException {
    // add snapshots repository...
    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() throws MojoExecutionException {
    File targetDir = new File( executedProject.getBuild().getDirectory() + "/sonar" );
    if (!targetDir.exists() && !targetDir.mkdirs()) {
      throw new MojoExecutionException( "Unable to created directory " + targetDir.getPath() );
    }

    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( ) throws MojoExecutionException {
    File targetDir = new File( executedProject.getBuild().getDirectory() + "/sonar");
    try {
      executedProject.writeModel( new FileWriter( new File( targetDir, "pom.xml" ), false ) );
    } catch (Exception e) {
      throw new MojoExecutionException("can not save the sonar pom.xml to " + targetDir, e);
    }
  }

  public org.apache.maven.project.MavenProject getExecutedProject() {
    return executedProject;
  }
 
  public ClassLoader getClassLoader() {
    return this.getClass().getClassLoader();
  }

  public WebInterfaceService getWebInterfaceService() {
    return webInterfaceService;
  }

  public void setWebInterfaceService( WebInterfaceService webInterfaceService ) {
    this.webInterfaceService = webInterfaceService;
  }
 
}
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.