浏览代码

SONAR-3821 Drop any Maven dependency

tags/5.2-RC1
Julien HENRY 9 年前
父节点
当前提交
5dd7b6e298
共有 49 个文件被更改,包括 107 次插入2539 次删除
  1. 53
    0
      plugins/sonar-batch-maven-plugin/pom.xml
  2. 12
    6
      plugins/sonar-batch-maven-plugin/src/main/java/org/sonar/plugins/batch/maven/MavenBatchPlugin.java
  3. 3
    2
      plugins/sonar-batch-maven-plugin/src/main/java/org/sonar/plugins/batch/maven/MavenProjectBuilder.java
  4. 13
    54
      pom.xml
  5. 1
    1
      server/sonar-server/src/main/resources/org/sonar/server/plugins/example-batch-index.txt
  6. 1
    13
      sonar-application/assembly.xml
  7. 1
    1
      sonar-application/pom.xml
  8. 3
    13
      sonar-batch-shaded/pom.xml
  9. 0
    20
      sonar-batch/pom.xml
  10. 0
    12
      sonar-batch/src/main/java/org/sonar/batch/ProjectConfigurator.java
  11. 0
    7
      sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchComponents.java
  12. 0
    63
      sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultProjectClasspath.java
  13. 0
    62
      sonar-batch/src/main/java/org/sonar/batch/maven/MavenProjectBootstrapper.java
  14. 0
    302
      sonar-batch/src/main/java/org/sonar/batch/maven/MavenProjectConverter.java
  15. 1
    9
      sonar-batch/src/main/java/org/sonar/batch/scan/ModuleScanContainer.java
  16. 4
    20
      sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/ProjectFileSystemAdapter.java
  17. 0
    73
      sonar-batch/src/test/java/org/sonar/batch/maven/MavenProjectBootstrapperTest.java
  18. 0
    245
      sonar-batch/src/test/java/org/sonar/batch/maven/MavenProjectConverterTest.java
  19. 0
    82
      sonar-batch/src/test/java/org/sonar/batch/maven/SonarMavenProjectBuilderTest.java
  20. 1
    2
      sonar-batch/src/test/java/org/sonar/batch/qualitygate/GenerateQualityGateEventsTest.java
  21. 9
    0
      sonar-plugin-api-deps/pom.xml
  22. 0
    14
      sonar-plugin-api/pom.xml
  23. 0
    99
      sonar-plugin-api/src/main/java/org/sonar/api/batch/ProjectClasspath.java
  24. 0
    432
      sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenPlugin.java
  25. 0
    51
      sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenSurefireUtils.java
  26. 0
    150
      sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenUtils.java
  27. 5
    64
      sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java
  28. 0
    305
      sonar-plugin-api/src/test/java/org/sonar/api/batch/maven/MavenPluginTest.java
  29. 0
    42
      sonar-plugin-api/src/test/java/org/sonar/api/batch/maven/MavenSurefireUtilsTest.java
  30. 0
    64
      sonar-plugin-api/src/test/java/org/sonar/api/batch/maven/MavenUtilsTest.java
  31. 0
    11
      sonar-plugin-api/src/test/java/org/sonar/api/resources/ProjectTest.java
  32. 0
    190
      sonar-plugin-api/src/test/java/org/sonar/api/test/MavenTestUtils.java
  33. 0
    37
      sonar-plugin-api/src/test/java/org/sonar/api/test/ProjectTestBuilder.java
  34. 0
    7
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/pom.xml
  35. 0
    1
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/src/main/java/.hidden
  36. 0
    1
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/src/main/java/.hiddendir/file_in_hidden_dir.txt
  37. 0
    0
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/src/main/java/foo.sql
  38. 0
    26
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/japanese-project/pom.xml
  39. 0
    8
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/nonexistent-dirs/pom.xml
  40. 0
    0
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/nonexistent-dirs/src/main/java
  41. 0
    7
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample-with-different-suffixes/pom.xml
  42. 0
    1
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample-with-different-suffixes/src/main/java/foo.c
  43. 0
    1
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample-with-different-suffixes/src/main/java/foo.sql
  44. 0
    8
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/pom.xml
  45. 0
    4
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/src/main/java/foo/Bar.java
  46. 0
    4
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/src/main/java/foo/Whizz.java
  47. 0
    6
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/src/test/java/foo/BarTest.java
  48. 0
    8
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/ProjectTest/equalsProject/pom.xml
  49. 0
    11
      sonar-plugin-api/src/test/resources/org/sonar/api/resources/ProjectTest/keyContainsBranch/pom.xml

+ 53
- 0
plugins/sonar-batch-maven-plugin/pom.xml 查看文件

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar</artifactId>
<version>5.2-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>

<groupId>org.codehaus.sonar.plugins</groupId>
<artifactId>sonar-batch-maven-plugin</artifactId>
<name>SonarQube :: Batch Maven Plugin</name>
<packaging>sonar-plugin</packaging>
<description>Inject MavenProject in each module.</description>

<dependencies>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-plugin-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-packaging-maven-plugin</artifactId>
<configuration>
<pluginKey>mavenbatch</pluginKey>
<pluginName>Maven Batch</pluginName>
<pluginClass>org.sonar.plugins.batch.maven.MavenBatchPlugin</pluginClass>
<pluginDescription>
<![CDATA[Inject MavenProject in each module.]]></pluginDescription>
</configuration>
</plugin>
</plugins>
</build>
</project>

sonar-batch/src/main/java/org/sonar/batch/maven/package-info.java → plugins/sonar-batch-maven-plugin/src/main/java/org/sonar/plugins/batch/maven/MavenBatchPlugin.java 查看文件

@@ -17,12 +17,18 @@
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.batch.maven;

/**
* This package is a part of bootstrap process, so we should take care about backward compatibility.
*/
@ParametersAreNonnullByDefault
package org.sonar.batch.maven;
import org.sonar.api.SonarPlugin;

import java.util.Arrays;
import java.util.List;

public class MavenBatchPlugin extends SonarPlugin {

import javax.annotation.ParametersAreNonnullByDefault;
@Override
public List getExtensions() {
return Arrays.asList(MavenProjectBuilder.class);
}

}

sonar-batch/src/main/java/org/sonar/batch/maven/MavenProjectBuilder.java → plugins/sonar-batch-maven-plugin/src/main/java/org/sonar/plugins/batch/maven/MavenProjectBuilder.java 查看文件

@@ -17,7 +17,7 @@
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.maven;
package org.sonar.plugins.batch.maven;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.MavenProject;
@@ -51,7 +51,8 @@ public class MavenProjectBuilder extends ProjectBuilder {
private void setMavenProjectIfApplicable(ProjectDefinition definition) {
if (mavenSession != null) {
String moduleKey = definition.getKey();
for (MavenProject mavenModule : (List<MavenProject>) mavenSession.getSortedProjects()) {
for (MavenProject mavenModule : (List<MavenProject>) mavenSession.getProjects()) {
// FIXME assumption that moduleKey was not modified by user and follow convention <groupId>:<artifactId>
String mavenModuleKey = mavenModule.getGroupId() + ":" + mavenModule.getArtifactId();
if (mavenModuleKey.equals(moduleKey) && !definition.getContainerExtensions().contains(mavenModule)) {
definition.addContainerExtension(mavenModule);

+ 13
- 54
pom.xml 查看文件

@@ -14,8 +14,8 @@
<module>sonar-plugin-api-deps</module>
<module>sonar-application</module>
<module>sonar-batch</module>
<module>sonar-batch-maven-compat</module>
<module>sonar-batch-protocol</module>
<module>sonar-batch-shaded</module>
<module>sonar-check-api</module>
<module>sonar-colorizer</module>
<module>sonar-core</module>
@@ -29,6 +29,7 @@
<module>sonar-testing-harness</module>
<module>plugins/sonar-email-notifications-plugin</module>
<module>plugins/sonar-xoo-plugin</module>
<module>plugins/sonar-batch-maven-plugin</module>
</modules>

<organization>
@@ -163,7 +164,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<version>2.10</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -392,14 +393,6 @@
</excludes>
<searchTransitive>true</searchTransitive>
</bannedDependencies>
<bannedDependencies>
<!-- See SONAR-2455 -->
<message>org.codehaus.plexus:plexus-classworlds should be used instead</message>
<excludes>
<exclude>classworlds:classworlds</exclude>
</excludes>
<searchTransitive>true</searchTransitive>
</bannedDependencies>
<requireNoRepositories>
<message>Definition of new repositories is not allowed in order to deploy to central repository.
</message>
@@ -784,6 +777,16 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
@@ -984,50 +987,6 @@
<artifactId>xpp3</artifactId>
<version>1.1.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>${maven.api.version}</version>
<exclusions>
<exclusion>
<!-- See SONAR-2455 -->
<groupId>classworlds</groupId>
<artifactId>classworlds</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>${maven.api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>${maven.api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>${maven.api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-dependency-tree</artifactId>
<version>2.1</version>
<exclusions>
<exclusion>
<!-- See SONAR-2455 -->
<groupId>classworlds</groupId>
<artifactId>classworlds</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-common-artifact-filters</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>

+ 1
- 1
server/sonar-server/src/main/resources/org/sonar/server/plugins/example-batch-index.txt 查看文件

@@ -1,2 +1,2 @@
sonar-batch-maven-compat-4.4.jar|2d7cbec208114970ea419ce963775f68
sonar-batch-4.4.jar|2d7cbec208114970ea419ce963775f68
sonar-batch-library-2.3.jar|86f577369ec914ae079411803cebc7d2

+ 1
- 13
sonar-application/assembly.xml 查看文件

@@ -33,18 +33,6 @@
<outputDirectory>lib/common</outputDirectory>
<useTransitiveFiltering>true</useTransitiveFiltering>
<useProjectArtifact>false</useProjectArtifact>
<excludes>
<exclude>mysql:mysql-connector-java</exclude>
<exclude>org.postgresql:postgresql</exclude>
<exclude>net.sourceforge.jtds:jtds</exclude>
<exclude>tanukisoft:wrapper</exclude>
<exclude>org.codehaus.sonar:sonar-server</exclude>
<exclude>org.codehaus.sonar:sonar-web</exclude>
<exclude>org.codehaus.sonar:sonar-search</exclude>
<exclude>org.codehaus.sonar.plugins:*</exclude>
<exclude>org.codehaus.sonar-plugins.java:*</exclude>
<exclude>org.sonatype.jsw-binaries:jsw-binaries</exclude>
</excludes>
<scope>runtime</scope>
</dependencySet>

@@ -85,7 +73,7 @@
<outputDirectory>lib/batch</outputDirectory>
<useTransitiveDependencies>false</useTransitiveDependencies>
<includes>
<include>org.codehaus.sonar:sonar-batch-maven-compat</include>
<include>org.codehaus.sonar:sonar-batch-shaded</include>
</includes>
<scope>provided</scope>
</dependencySet>

+ 1
- 1
sonar-application/pom.xml 查看文件

@@ -55,7 +55,7 @@
</dependency>
<dependency>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-batch-maven-compat</artifactId>
<artifactId>sonar-batch-shaded</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>

sonar-batch-maven-compat/pom.xml → sonar-batch-shaded/pom.xml 查看文件

@@ -8,9 +8,9 @@
<version>5.2-SNAPSHOT</version>
</parent>

<artifactId>sonar-batch-maven-compat</artifactId>
<name>SonarQube :: Batch Maven Compat</name>
<description>Compatibility layer, which provides MavenProject for non-Maven environments.</description>
<artifactId>sonar-batch-shaded</artifactId>
<name>SonarQube :: Batch Shaded</name>
<description>All batch dependencies in a single jar</description>

<dependencies>
<dependency>
@@ -18,16 +18,6 @@
<artifactId>sonar-batch</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<exclusions>
<exclusion>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>

+ 0
- 20
sonar-batch/pom.xml 查看文件

@@ -85,26 +85,6 @@
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-dependency-tree</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>

+ 0
- 12
sonar-batch/src/main/java/org/sonar/batch/ProjectConfigurator.java 查看文件

@@ -20,7 +20,6 @@
package org.sonar.batch;

import org.apache.commons.lang.StringUtils;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.BatchSide;
@@ -64,18 +63,7 @@ public class ProjectConfigurator {

public Project create(ProjectDefinition definition) {
Project project = new Project(definition.getKey(), loadProjectBranch(), definition.getName());

// For backward compatibility we must set POM and actual packaging
project.setDescription(StringUtils.defaultString(definition.getDescription()));
project.setPackaging("jar");

for (Object component : definition.getContainerExtensions()) {
if (component instanceof MavenProject) {
MavenProject pom = (MavenProject) component;
project.setPom(pom);
project.setPackaging(pom.getPackaging());
}
}
return project;
}


+ 0
- 7
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchComponents.java 查看文件

@@ -57,9 +57,6 @@ import org.sonar.batch.issue.tracking.IssueHandlers;
import org.sonar.batch.issue.tracking.IssueTracking;
import org.sonar.batch.issue.tracking.IssueTrackingDecorator;
import org.sonar.batch.language.LanguageDistributionDecorator;
import org.sonar.batch.maven.MavenProjectBootstrapper;
import org.sonar.batch.maven.MavenProjectBuilder;
import org.sonar.batch.maven.MavenProjectConverter;
import org.sonar.batch.qualitygate.GenerateQualityGateEvents;
import org.sonar.batch.qualitygate.QualityGateVerifier;
import org.sonar.batch.rule.QProfileEventsDecorator;
@@ -85,10 +82,6 @@ public class BatchComponents {
public static Collection all(DefaultAnalysisMode analysisMode) {
List components = Lists.newArrayList(
DefaultResourceTypes.get(),

// Maven
MavenProjectBootstrapper.class, MavenProjectConverter.class, MavenProjectBuilder.class,

// SCM
ScmConfiguration.class,
ScmSensor.class,

+ 0
- 63
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultProjectClasspath.java 查看文件

@@ -1,63 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.deprecated.components;

import com.google.common.collect.Lists;
import org.apache.maven.project.MavenProject;
import org.sonar.api.batch.ProjectClasspath;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.resources.ProjectFileSystem;

import javax.annotation.Nullable;

import java.io.File;
import java.util.List;

public class DefaultProjectClasspath extends ProjectClasspath {

private ProjectDefinition def;
private ProjectFileSystem projectFileSystem;

public DefaultProjectClasspath(ProjectDefinition def, ProjectFileSystem projectFileSystem) {
this(def, projectFileSystem, null);
}

public DefaultProjectClasspath(ProjectDefinition def, ProjectFileSystem projectFileSystem, @Nullable MavenProject pom) {
super(pom);
this.def = def;
this.projectFileSystem = projectFileSystem;
}

@Override
protected List<File> createElements() {
if (pom != null) {
return super.createElements();
} else {
List<File> elements = Lists.newArrayList();
for (String path : def.getBinaries()) {
elements.add(projectFileSystem.resolvePath(path));
}
for (String path : def.getLibraries()) {
elements.add(projectFileSystem.resolvePath(path));
}
return elements;
}
}
}

+ 0
- 62
sonar-batch/src/main/java/org/sonar/batch/maven/MavenProjectBootstrapper.java 查看文件

@@ -1,62 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.maven;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.MavenProject;
import org.sonar.api.batch.SupportedEnvironment;
import org.sonar.api.batch.bootstrap.ProjectBootstrapper;
import org.sonar.api.batch.bootstrap.ProjectReactor;

import java.util.List;

/**
* @deprecated since 4.3 kept only to support old version of SonarQube Mojo
*/
@Deprecated
@SupportedEnvironment("maven")
public class MavenProjectBootstrapper implements ProjectBootstrapper {

private MavenSession session;
private MavenProjectConverter mavenProjectConverter;

public MavenProjectBootstrapper(MavenSession session, MavenProjectConverter mavenProjectConverter) {
this.session = session;
this.mavenProjectConverter = mavenProjectConverter;
}

@Override
public ProjectReactor bootstrap() {
// Don't use session.getTopLevelProject or session.getProjects to keep compatibility with Maven 2
List<MavenProject> sortedProjects = session.getSortedProjects();
MavenProject topLevelProject = null;
for (MavenProject project : sortedProjects) {
if (project.isExecutionRoot()) {
topLevelProject = project;
break;
}
}
if (topLevelProject == null) {
throw new IllegalStateException("Maven session does not declare a top level project");
}
return new ProjectReactor(mavenProjectConverter.configure(sortedProjects, topLevelProject));
}

}

+ 0
- 302
sonar-batch/src/main/java/org/sonar/batch/maven/MavenProjectConverter.java 查看文件

@@ -1,302 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.maven;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.CiManagement;
import org.apache.maven.model.IssueManagement;
import org.apache.maven.model.Scm;
import org.apache.maven.project.MavenProject;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.SupportedEnvironment;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.maven.MavenUtils;
import org.sonar.api.task.TaskExtension;
import org.sonar.api.utils.MessageException;
import org.sonar.java.api.JavaUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
* @deprecated since 4.3 kept only to support old version of SonarQube Mojo
*/
@Deprecated
@SupportedEnvironment("maven")
public class MavenProjectConverter implements TaskExtension {

private static final String UNABLE_TO_DETERMINE_PROJECT_STRUCTURE_EXCEPTION_MESSAGE = "Unable to determine structure of project." +
" Probably you use Maven Advanced Reactor Options, which is not supported by SonarQube and should not be used.";

public ProjectDefinition configure(List<MavenProject> poms, MavenProject root) {
// projects by canonical path to pom.xml
Map<String, MavenProject> paths = Maps.newHashMap();
Map<MavenProject, ProjectDefinition> defs = Maps.newHashMap();

try {
configureModules(poms, paths, defs);

rebuildModuleHierarchy(paths, defs);
} catch (IOException e) {
throw new IllegalStateException("Cannot configure project", e);
}

ProjectDefinition rootProject = defs.get(root);
if (rootProject == null) {
throw new IllegalStateException(UNABLE_TO_DETERMINE_PROJECT_STRUCTURE_EXCEPTION_MESSAGE);
}
return rootProject;
}

private void rebuildModuleHierarchy(Map<String, MavenProject> paths, Map<MavenProject, ProjectDefinition> defs) throws IOException {
for (Map.Entry<String, MavenProject> entry : paths.entrySet()) {
MavenProject pom = entry.getValue();
for (Object m : pom.getModules()) {
String moduleId = (String) m;
File modulePath = new File(pom.getBasedir(), moduleId);
MavenProject module = findMavenProject(modulePath, paths);

ProjectDefinition parentProject = defs.get(pom);
if (parentProject == null) {
throw new IllegalStateException(UNABLE_TO_DETERMINE_PROJECT_STRUCTURE_EXCEPTION_MESSAGE);
}
ProjectDefinition subProject = defs.get(module);
if (subProject == null) {
throw new IllegalStateException(UNABLE_TO_DETERMINE_PROJECT_STRUCTURE_EXCEPTION_MESSAGE);
}
parentProject.addSubProject(subProject);
}
}
}

private void configureModules(List<MavenProject> poms, Map<String, MavenProject> paths, Map<MavenProject, ProjectDefinition> defs) throws IOException {
for (MavenProject pom : poms) {
paths.put(pom.getFile().getCanonicalPath(), pom);
ProjectDefinition def = ProjectDefinition.create();
merge(pom, def);
defs.put(pom, def);
}
}

private static MavenProject findMavenProject(final File modulePath, Map<String, MavenProject> paths) throws IOException {
if (modulePath.exists() && modulePath.isDirectory()) {
for (Map.Entry<String, MavenProject> entry : paths.entrySet()) {
String pomFileParentDir = new File(entry.getKey()).getParent();
if (pomFileParentDir.equals(modulePath.getCanonicalPath())) {
return entry.getValue();
}
}
return null;
}
return paths.get(modulePath.getCanonicalPath());
}

@VisibleForTesting
void merge(MavenProject pom, ProjectDefinition definition) {
String key = getSonarKey(pom);
// IMPORTANT NOTE : reference on properties from POM model must not be saved,
// instead they should be copied explicitly - see SONAR-2896
definition
.setProperties(pom.getModel().getProperties())
.setKey(key)
.setVersion(pom.getVersion())
.setName(pom.getName())
.setDescription(pom.getDescription())
.addContainerExtension(pom);
guessJavaVersion(pom, definition);
guessEncoding(pom, definition);
convertMavenLinksToProperties(definition, pom);
synchronizeFileSystem(pom, definition);
}

private static String getSonarKey(MavenProject pom) {
return new StringBuilder().append(pom.getGroupId()).append(":").append(pom.getArtifactId()).toString();
}

private static void guessEncoding(MavenProject pom, ProjectDefinition definition) {
// See http://jira.sonarsource.com/browse/SONAR-2151
String encoding = MavenUtils.getSourceEncoding(pom);
if (encoding != null) {
definition.setProperty(CoreProperties.ENCODING_PROPERTY, encoding);
}
}

private static void guessJavaVersion(MavenProject pom, ProjectDefinition definition) {
// See http://jira.sonarsource.com/browse/SONAR-2148
// Get Java source and target versions from maven-compiler-plugin.
String version = MavenUtils.getJavaSourceVersion(pom);
if (version != null) {
definition.setProperty(JavaUtils.JAVA_SOURCE_PROPERTY, version);
}
version = MavenUtils.getJavaVersion(pom);
if (version != null) {
definition.setProperty(JavaUtils.JAVA_TARGET_PROPERTY, version);
}
}

/**
* For SONAR-3676
*/
private static void convertMavenLinksToProperties(ProjectDefinition definition, MavenProject pom) {
setPropertyIfNotAlreadyExists(definition, CoreProperties.LINKS_HOME_PAGE, pom.getUrl());

Scm scm = pom.getScm();
if (scm == null) {
scm = new Scm();
}
setPropertyIfNotAlreadyExists(definition, CoreProperties.LINKS_SOURCES, scm.getUrl());
setPropertyIfNotAlreadyExists(definition, CoreProperties.LINKS_SOURCES_DEV, scm.getDeveloperConnection());

CiManagement ci = pom.getCiManagement();
if (ci == null) {
ci = new CiManagement();
}
setPropertyIfNotAlreadyExists(definition, CoreProperties.LINKS_CI, ci.getUrl());

IssueManagement issues = pom.getIssueManagement();
if (issues == null) {
issues = new IssueManagement();
}
setPropertyIfNotAlreadyExists(definition, CoreProperties.LINKS_ISSUE_TRACKER, issues.getUrl());
}

private static void setPropertyIfNotAlreadyExists(ProjectDefinition definition, String propertyKey, String propertyValue) {
if (StringUtils.isBlank(definition.properties().get(propertyKey))) {
definition.setProperty(propertyKey, StringUtils.defaultString(propertyValue));
}
}

public void synchronizeFileSystem(MavenProject pom, ProjectDefinition into) {
into.setBaseDir(pom.getBasedir());
File buildDir = getBuildDir(pom);
if (buildDir != null) {
into.setBuildDir(buildDir);
into.setWorkDir(getSonarWorkDir(pom));
}
into.setSourceDirs(toPaths(mainDirs(pom)));
into.setTestDirs(toPaths(testDirs(pom)));
File binaryDir = resolvePath(pom.getBuild().getOutputDirectory(), pom.getBasedir());
if (binaryDir != null) {
into.addBinaryDir(binaryDir);
}
}

public static File getSonarWorkDir(MavenProject pom) {
return new File(getBuildDir(pom), "sonar");
}

private static File getBuildDir(MavenProject pom) {
return resolvePath(pom.getBuild().getDirectory(), pom.getBasedir());
}

static File resolvePath(@Nullable String path, File basedir) {
if (path != null) {
File file = new File(StringUtils.trim(path));
if (!file.isAbsolute()) {
try {
file = new File(basedir, path).getCanonicalFile();
} catch (IOException e) {
throw new IllegalStateException("Unable to resolve path '" + path + "'", e);
}
}
return file;
}
return null;
}

static List<File> resolvePaths(List<String> paths, File basedir) {
List<File> result = Lists.newArrayList();
for (String path : paths) {
File dir = resolvePath(path, basedir);
if (dir != null) {
result.add(dir);
}
}
return result;
}

private List<File> mainDirs(MavenProject pom) {
return sourceDirs(pom, ProjectDefinition.SOURCE_DIRS_PROPERTY, pom.getCompileSourceRoots());
}

private List<File> testDirs(MavenProject pom) {
return sourceDirs(pom, ProjectDefinition.TEST_DIRS_PROPERTY, pom.getTestCompileSourceRoots());
}

private List<File> sourceDirs(MavenProject pom, String propertyKey, List mavenDirs) {
List<String> paths;
String prop = pom.getProperties().getProperty(propertyKey);
if (prop != null) {
paths = Arrays.asList(StringUtils.split(prop, ","));
// do not remove dirs that do not exist. They must be kept in order to
// notify users that value of sonar.sources has a typo.
return existingDirsOrFail(resolvePaths(paths, pom.getBasedir()), pom, propertyKey);
}

List<File> dirs = resolvePaths(mavenDirs, pom.getBasedir());

// Maven provides some directories that do not exist. They
// should be removed
return keepExistingDirs(dirs);
}

private List<File> existingDirsOrFail(List<File> dirs, MavenProject pom, String propertyKey) {
for (File dir : dirs) {
if (!dir.isDirectory() || !dir.exists()) {
throw MessageException.of(String.format(
"The directory '%s' does not exist for Maven module %s. Please check the property %s",
dir.getAbsolutePath(), pom.getId(), propertyKey));
}
}
return dirs;
}

private static List<File> keepExistingDirs(List<File> files) {
return Lists.newArrayList(Collections2.filter(files, new Predicate<File>() {
@Override
public boolean apply(File dir) {
return dir != null && dir.exists() && dir.isDirectory();
}
}));
}

private static String[] toPaths(Collection<File> dirs) {
Collection<String> paths = Collections2.transform(dirs, new Function<File, String>() {
@Override
public String apply(@Nonnull File dir) {
return dir.getAbsolutePath();
}
});
return paths.toArray(new String[paths.size()]);
}
}

+ 1
- 9
sonar-batch/src/main/java/org/sonar/batch/scan/ModuleScanContainer.java 查看文件

@@ -35,7 +35,6 @@ import org.sonar.batch.bootstrap.ExtensionMatcher;
import org.sonar.batch.bootstrap.ExtensionUtils;
import org.sonar.batch.deprecated.DeprecatedSensorContext;
import org.sonar.batch.deprecated.ResourceFilters;
import org.sonar.batch.deprecated.components.DefaultProjectClasspath;
import org.sonar.batch.deprecated.components.DefaultTimeMachine;
import org.sonar.batch.deprecated.perspectives.BatchPerspectives;
import org.sonar.batch.events.EventBus;
@@ -139,7 +138,6 @@ public class ModuleScanContainer extends ComponentContainer {
ComponentIndexer.class,
LanguageVerifier.class,
FileSystemLogger.class,
DefaultProjectClasspath.class,
DefaultModuleFileSystem.class,
ModuleFileSystemInitializer.class,
ProjectFileSystemAdapter.class,
@@ -193,13 +191,7 @@ public class ModuleScanContainer extends ComponentContainer {
installer.install(this, new ExtensionMatcher() {
@Override
public boolean accept(Object extension) {
if (ExtensionUtils.isBatchSide(extension) && ExtensionUtils.isInstantiationStrategy(extension, InstantiationStrategy.PER_PROJECT)) {
// Special use-case: the extension point ProjectBuilder is used in a Maven environment to define some
// new sub-projects without pom.
// Example : C# plugin adds sub-projects at runtime, even if they are not defined in root pom.
return !ExtensionUtils.isMavenExtensionOnly(extension) || module.getPom() != null;
}
return false;
return ExtensionUtils.isBatchSide(extension) && ExtensionUtils.isInstantiationStrategy(extension, InstantiationStrategy.PER_PROJECT);
}
});
}

+ 4
- 20
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/ProjectFileSystemAdapter.java 查看文件

@@ -23,18 +23,11 @@ import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.CharEncoding;
import org.apache.maven.project.MavenProject;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.resources.InputFile;
import org.sonar.api.resources.Java;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.ProjectFileSystem;
import org.sonar.api.resources.Resource;
import org.sonar.api.resources.*;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.SonarException;

import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
@@ -50,20 +43,14 @@ public class ProjectFileSystemAdapter implements ProjectFileSystem {

private final DefaultModuleFileSystem target;
private final PathResolver pathResolver = new PathResolver();
private final MavenProject pom;

public ProjectFileSystemAdapter(DefaultModuleFileSystem target, Project project, @Nullable MavenProject pom) {
public ProjectFileSystemAdapter(DefaultModuleFileSystem target, Project project) {
this.target = target;
this.pom = pom;

// previously MavenProjectBuilder was responsible for creation of ProjectFileSystem
project.setFileSystem(this);
}

public ProjectFileSystemAdapter(DefaultModuleFileSystem target, Project project) {
this(target, project, null);
}

public void start() {
// used to avoid NPE in Project#getFileSystem()
}
@@ -123,9 +110,6 @@ public class ProjectFileSystemAdapter implements ProjectFileSystem {

@Override
public File getReportOutputDir() {
if (pom != null) {
return resolvePath(pom.getReporting().getOutputDirectory());
}
// emulate Maven report output dir
return new File(getBuildDir(), "site");
}
@@ -209,7 +193,7 @@ public class ProjectFileSystemAdapter implements ProjectFileSystem {
return Lists.newArrayList((Iterable) target.inputFiles(target.predicates().and(
target.predicates().hasType(org.sonar.api.batch.fs.InputFile.Type.MAIN),
target.predicates().hasLanguages(Arrays.asList(langs))
)));
)));

}

@@ -218,7 +202,7 @@ public class ProjectFileSystemAdapter implements ProjectFileSystem {
return Lists.newArrayList((Iterable) target.inputFiles(target.predicates().and(
target.predicates().hasType(org.sonar.api.batch.fs.InputFile.Type.TEST),
target.predicates().hasLanguages(Arrays.asList(langs))
)));
)));
}

private FilePredicate newHasLanguagesPredicate(Language... languages) {

+ 0
- 73
sonar-batch/src/test/java/org/sonar/batch/maven/MavenProjectBootstrapperTest.java 查看文件

@@ -1,73 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.maven;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.MavenProject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;

import java.util.Arrays;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class MavenProjectBootstrapperTest {

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void bootstrap() {
ProjectDefinition def = mock(ProjectDefinition.class);
MavenSession session = mock(MavenSession.class);
MavenProject rootProject = new MavenProject();
rootProject.setExecutionRoot(true);
List<MavenProject> projects = Arrays.asList(rootProject);
when(session.getSortedProjects()).thenReturn(projects);

MavenProjectConverter pomConverter = mock(MavenProjectConverter.class);
when(pomConverter.configure(projects, rootProject)).thenReturn(def);
MavenProjectBootstrapper bootstrapper = new MavenProjectBootstrapper(session, pomConverter);

ProjectReactor reactor = bootstrapper.bootstrap();

assertThat(reactor).isNotNull();
verify(pomConverter).configure(projects, rootProject);
}

@Test
public void should_fail_if_no_top_level_project() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Maven session does not declare a top level project");

MavenSession session = mock(MavenSession.class);
MavenProjectConverter pomConverter = new MavenProjectConverter();
MavenProjectBootstrapper bootstrapper = new MavenProjectBootstrapper(session, pomConverter);

bootstrapper.bootstrap();
}
}

+ 0
- 245
sonar-batch/src/test/java/org/sonar/batch/maven/MavenProjectConverterTest.java 查看文件

@@ -1,245 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.maven;

import com.google.common.io.Resources;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.hamcrest.core.Is;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.bootstrap.ProjectDefinition;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Properties;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class MavenProjectConverterTest {

@Rule
public TemporaryFolder temp = new TemporaryFolder();

MavenProjectConverter converter = new MavenProjectConverter();

/**
* See SONAR-2681
*/
@Test
public void shouldThrowExceptionWhenUnableToDetermineProjectStructure() {
MavenProject root = new MavenProject();
root.setFile(new File("/foo/pom.xml"));
root.getBuild().setDirectory("target");
root.getModules().add("module/pom.xml");

try {
converter.configure(Arrays.asList(root), root);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString("Advanced Reactor Options"));
}
}

@Test
public void shouldConvertModules() throws IOException {
File basedir = temp.newFolder();

MavenProject root = newMavenProject("com.foo", "parent", "1.0-SNAPSHOT");
root.setFile(new File(basedir, "pom.xml"));
root.getBuild().setDirectory("target");
root.getBuild().setOutputDirectory("target/classes");
root.getModules().add("module/pom.xml");
MavenProject module = newMavenProject("com.foo", "moduleA", "1.0-SNAPSHOT");
module.setFile(new File(basedir, "module/pom.xml"));
module.getBuild().setDirectory("target");
module.getBuild().setOutputDirectory("target/classes");
ProjectDefinition project = converter.configure(Arrays.asList(root, module), root);

assertThat(project.getSubProjects().size(), is(1));
}

private MavenProject newMavenProject(String groupId, String artifactId, String version) {
Model model = new Model();
model.setGroupId(groupId);
model.setArtifactId(artifactId);
model.setVersion(version);
return new MavenProject(model);
}

@Test
public void shouldConvertProperties() {
MavenProject pom = new MavenProject();
pom.setGroupId("foo");
pom.setArtifactId("bar");
pom.setVersion("1.0.1");
pom.setName("Test");
pom.setDescription("just test");
pom.setFile(new File("/foo/pom.xml"));
pom.getBuild().setDirectory("target");
ProjectDefinition project = ProjectDefinition.create();
converter.merge(pom, project);

Properties properties = project.getProperties();
assertThat(properties.getProperty(CoreProperties.PROJECT_KEY_PROPERTY), is("foo:bar"));
assertThat(properties.getProperty(CoreProperties.PROJECT_VERSION_PROPERTY), is("1.0.1"));
assertThat(properties.getProperty(CoreProperties.PROJECT_NAME_PROPERTY), is("Test"));
assertThat(properties.getProperty(CoreProperties.PROJECT_DESCRIPTION_PROPERTY), is("just test"));
}

@Test
public void moduleNameShouldEqualArtifactId() throws Exception {
File rootDir = new File(Resources.getResource("org/sonar/batch/maven/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/").toURI());
MavenProject parent = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/pom.xml", true);
MavenProject module1 = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/module1/pom.xml", false);
MavenProject module2 = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/module2/pom.xml", false);

ProjectDefinition rootDef = converter.configure(Arrays.asList(parent, module1, module2), parent);

assertThat(rootDef.getSubProjects().size(), Is.is(2));
assertThat(rootDef.getKey(), Is.is("org.test:parent"));
assertNull(rootDef.getParent());
assertThat(rootDef.getBaseDir(), is(rootDir));

ProjectDefinition module1Def = rootDef.getSubProjects().get(0);
assertThat(module1Def.getKey(), Is.is("org.test:module1"));
assertThat(module1Def.getParent(), Is.is(rootDef));
assertThat(module1Def.getBaseDir(), Is.is(new File(rootDir, "module1")));
assertThat(module1Def.getSubProjects().size(), Is.is(0));
}

@Test
public void moduleNameDifferentThanArtifactId() throws Exception {
File rootDir = new File(Resources.getResource("org/sonar/batch/maven/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/").toURI());
MavenProject parent = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/pom.xml", true);
MavenProject module1 = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/path1/pom.xml", false);
MavenProject module2 = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/path2/pom.xml", false);

ProjectDefinition rootDef = converter.configure(Arrays.asList(parent, module1, module2), parent);

assertThat(rootDef.getSubProjects().size(), is(2));
assertThat(rootDef.getKey(), is("org.test:parent"));
assertNull(rootDef.getParent());
assertThat(rootDef.getBaseDir(), is(rootDir));

ProjectDefinition module1Def = rootDef.getSubProjects().get(0);
assertThat(module1Def.getKey(), Is.is("org.test:module1"));
assertThat(module1Def.getParent(), Is.is(rootDef));
assertThat(module1Def.getBaseDir(), Is.is(new File(rootDir, "path1")));
assertThat(module1Def.getSubProjects().size(), Is.is(0));
}

@Test
public void should_find_module_with_maven_project_file_naming_different_from_pom_xml() throws Exception {
File rootDir = new File(Resources.getResource("org/sonar/batch/maven/MavenProjectConverterTest/mavenProjectFileNameNotEqualsToPomXml/").toURI());
MavenProject parent = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/mavenProjectFileNameNotEqualsToPomXml/pom.xml", true);
MavenProject module = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/mavenProjectFileNameNotEqualsToPomXml/module/pom_having_different_name.xml", false);

ProjectDefinition rootDef = converter.configure(Arrays.asList(parent, module), parent);

assertThat(rootDef.getSubProjects().size(), Is.is(1));
assertThat(rootDef.getKey(), Is.is("org.test:parent"));
assertNull(rootDef.getParent());
assertThat(rootDef.getBaseDir(), is(rootDir));

ProjectDefinition module1Def = rootDef.getSubProjects().get(0);
assertThat(module1Def.getKey(), Is.is("org.test:module"));
assertThat(module1Def.getParent(), Is.is(rootDef));
assertThat(module1Def.getBaseDir(), Is.is(new File(rootDir, "module")));
assertThat(module1Def.getSubProjects().size(), Is.is(0));
}

@Test
public void testSingleProjectWithoutModules() throws Exception {
File rootDir = new File(Resources.getResource("org/sonar/batch/maven/MavenProjectConverterTest/singleProjectWithoutModules/").toURI());
MavenProject pom = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/singleProjectWithoutModules/pom.xml", true);

ProjectDefinition rootDef = converter.configure(Arrays.asList(pom), pom);

assertThat(rootDef.getKey(), is("org.test:parent"));
assertThat(rootDef.getSubProjects().size(), is(0));
assertNull(rootDef.getParent());
assertThat(rootDef.getBaseDir(), is(rootDir));
}

@Test
public void shouldConvertLinksToProperties() throws Exception {
MavenProject pom = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/projectWithLinks/pom.xml", true);

ProjectDefinition rootDef = converter.configure(Arrays.asList(pom), pom);

Properties props = rootDef.getProperties();
assertThat(props.getProperty(CoreProperties.LINKS_HOME_PAGE)).isEqualTo("http://home.com");
assertThat(props.getProperty(CoreProperties.LINKS_CI)).isEqualTo("http://ci.com");
assertThat(props.getProperty(CoreProperties.LINKS_ISSUE_TRACKER)).isEqualTo("http://issues.com");
assertThat(props.getProperty(CoreProperties.LINKS_SOURCES)).isEqualTo("http://sources.com");
assertThat(props.getProperty(CoreProperties.LINKS_SOURCES_DEV)).isEqualTo("http://sources-dev.com");
}

@Test
public void shouldNotConvertLinksToPropertiesIfPropertyAlreadyDefined() throws Exception {
MavenProject pom = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/projectWithLinksAndProperties/pom.xml", true);

ProjectDefinition rootDef = converter.configure(Arrays.asList(pom), pom);

Properties props = rootDef.getProperties();

// Those properties have been fed by the POM elements <ciManagement>, <issueManagement>, ...
assertThat(props.getProperty(CoreProperties.LINKS_CI)).isEqualTo("http://ci.com");
assertThat(props.getProperty(CoreProperties.LINKS_ISSUE_TRACKER)).isEqualTo("http://issues.com");
assertThat(props.getProperty(CoreProperties.LINKS_SOURCES_DEV)).isEqualTo("http://sources-dev.com");

// ... but those ones have been overridden by <properties> in the POM
assertThat(props.getProperty(CoreProperties.LINKS_SOURCES)).isEqualTo("http://sources.com-OVERRIDEN-BY-PROPS");
assertThat(props.getProperty(CoreProperties.LINKS_HOME_PAGE)).isEqualTo("http://home.com-OVERRIDEN-BY-PROPS");
}

@Test
public void shouldLoadSourceEncoding() throws Exception {
MavenProject pom = loadPom("/org/sonar/batch/maven/MavenProjectConverterTest/sourceEncoding/pom.xml", true);

ProjectDefinition rootDef = converter.configure(Arrays.asList(pom), pom);

assertThat(rootDef.getProperties().getProperty(CoreProperties.ENCODING_PROPERTY)).isEqualTo("Shift_JIS");
}

private MavenProject loadPom(String pomPath, boolean isRoot) throws URISyntaxException, IOException, XmlPullParserException {
File pomFile = new File(getClass().getResource(pomPath).toURI());
Model model = new MavenXpp3Reader().read(new StringReader(FileUtils.readFileToString(pomFile)));
MavenProject pom = new MavenProject(model);
pom.setFile(pomFile);
pom.getBuild().setDirectory("target");
pom.setExecutionRoot(isRoot);
return pom;
}
}

+ 0
- 82
sonar-batch/src/test/java/org/sonar/batch/maven/SonarMavenProjectBuilderTest.java 查看文件

@@ -1,82 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.maven;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.MavenProject;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.batch.bootstrap.ProjectDefinition;

import java.util.Arrays;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class SonarMavenProjectBuilderTest {

@Test
public void testSimpleProject() {
MavenSession session = mock(MavenSession.class);
MavenProject rootProject = mock(MavenProject.class);
when(rootProject.isExecutionRoot()).thenReturn(true);
when(session.getSortedProjects()).thenReturn(Arrays.asList(rootProject));

MavenProjectConverter mavenProjectConverter = mock(MavenProjectConverter.class);
ProjectDefinition projectDefinition = ProjectDefinition.create();
when(mavenProjectConverter.configure(any(List.class), any(MavenProject.class))).thenReturn(projectDefinition);
MavenProjectBootstrapper builder = new MavenProjectBootstrapper(session, mavenProjectConverter);

assertThat(builder.bootstrap().getRoot()).isEqualTo(projectDefinition);

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(mavenProjectConverter).configure(argument.capture(), eq(rootProject));
assertThat(argument.getValue()).contains(rootProject);
}

@Test
public void testMultimoduleProject() {
MavenSession session = mock(MavenSession.class);
MavenProject rootProject = mock(MavenProject.class);
MavenProject module1 = mock(MavenProject.class);
MavenProject module2 = mock(MavenProject.class);
when(rootProject.isExecutionRoot()).thenReturn(true);
when(module1.isExecutionRoot()).thenReturn(false);
when(module2.isExecutionRoot()).thenReturn(false);
when(session.getSortedProjects()).thenReturn(Arrays.asList(module1, module2, rootProject));

MavenProjectConverter mavenProjectConverter = mock(MavenProjectConverter.class);
ProjectDefinition projectDefinition = ProjectDefinition.create();
when(mavenProjectConverter.configure(any(List.class), any(MavenProject.class))).thenReturn(projectDefinition);
MavenProjectBootstrapper builder = new MavenProjectBootstrapper(session, mavenProjectConverter);

assertThat(builder.bootstrap().getRoot()).isEqualTo(projectDefinition);

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(mavenProjectConverter).configure(argument.capture(), eq(rootProject));
assertThat(argument.getValue()).contains(module1, module2, rootProject);
}

}

+ 1
- 2
sonar-batch/src/test/java/org/sonar/batch/qualitygate/GenerateQualityGateEventsTest.java 查看文件

@@ -32,7 +32,6 @@ import org.sonar.core.notification.NotificationManager;
import org.sonar.api.resources.File;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import org.sonar.api.test.ProjectTestBuilder;
import org.sonar.batch.protocol.Constants.EventCategory;
import org.sonar.batch.report.EventCache;

@@ -65,7 +64,7 @@ public class GenerateQualityGateEventsTest {
notificationManager = mock(NotificationManager.class);
eventCache = mock(EventCache.class);
decorator = new GenerateQualityGateEvents(qualityGate, timeMachine, notificationManager, eventCache);
project = new ProjectTestBuilder().build();
project = new Project("mygroup:myartifact");
when(context.getResource()).thenReturn(project);
}


+ 9
- 0
sonar-plugin-api-deps/pom.xml 查看文件

@@ -39,6 +39,15 @@
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<!-- Needed by old versions of Java plugin (JavaClasspath) -->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
</dependency>
</dependencies>

<build>

+ 0
- 14
sonar-plugin-api/pom.xml 查看文件

@@ -87,20 +87,6 @@
</dependency>


<!-- TODO remove dependencies on Maven
but for now they should be defined with scope provided
-->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>

+ 0
- 99
sonar-plugin-api/src/main/java/org/sonar/api/batch/ProjectClasspath.java 查看文件

@@ -1,99 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch;

import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.project.MavenProject;
import org.sonar.api.utils.SonarException;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
* @since 2.2
* @deprecated since 4.5 this is some Java specific stuff that should by handled by SQ Java plugin
*/
@Deprecated
@BatchSide
public class ProjectClasspath {

protected MavenProject pom;
private List<File> elements;
private URLClassLoader classloader;

public ProjectClasspath(MavenProject pom) {
this.pom = pom;
}

public URLClassLoader getClassloader() {
if (classloader == null) {
classloader = createClassLoader();
}
return classloader;
}

/**
* bytecode directory + JARs (dependencies)
*/
public List<File> getElements() {
if (elements == null) {
elements = createElements();
}
return elements;
}

protected URLClassLoader createClassLoader() {
try {
List<URL> urls = new ArrayList<>();
for (File file : getElements()) {
urls.add(file.toURI().toURL());
}
return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);

} catch (MalformedURLException e) {
throw new SonarException("Fail to create the project classloader. Classpath element is unvalid.", e);
}
}

protected List<File> createElements() {
try {
List<File> files = new ArrayList<>();
if (pom.getCompileClasspathElements() != null) {
for (String classPathString : pom.getCompileClasspathElements()) {
files.add(new File(classPathString));
}
}

if (pom.getBuild().getOutputDirectory() != null) {
File outputDirectoryFile = new File(pom.getBuild().getOutputDirectory());
if (outputDirectoryFile.exists()) {
files.add(outputDirectoryFile);
}
}
return files;
} catch (DependencyResolutionRequiredException e) {
throw new SonarException("Fail to create the project classloader", e);
}
}
}

+ 0
- 432
sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenPlugin.java 查看文件

@@ -1,432 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.maven;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
* A class to handle maven plugins
*
* @since 1.10
* @deprecated since 4.5 we don't want any dependency on Maven anymore
*/
@Deprecated
public class MavenPlugin {

private static final String CONFIGURATION_ELEMENT = "configuration";
private Plugin plugin;
private Xpp3Dom configuration;

/**
* Creates a MavenPlugin based on a Plugin
*
* @param plugin the plugin
*/
public MavenPlugin(Plugin plugin) {
this.plugin = plugin;
this.configuration = (Xpp3Dom) plugin.getConfiguration();
if (this.configuration == null) {
configuration = new Xpp3Dom(CONFIGURATION_ELEMENT);
plugin.setConfiguration(this.configuration);
}
}

/**
* Creates a Maven plugin based on artifact + group + version
*
* @param groupId the group id
* @param artifactId the artifact id
* @param version the version
*/
public MavenPlugin(String groupId, String artifactId, String version) {
this.plugin = new Plugin();
plugin.setGroupId(groupId);
plugin.setArtifactId(artifactId);
plugin.setVersion(version);
configuration = new Xpp3Dom(CONFIGURATION_ELEMENT);
plugin.setConfiguration(this.configuration);
}

/**
* @since 3.5 - see SONAR-4070
* @return the XML node <configuration> of pom
*/
public Xpp3Dom getConfigurationXmlNode() {
return configuration;
}

/**
* Sets the maven plugin version
*
* @param version the version
* @return this
*/
public MavenPlugin setVersion(String version) {
this.plugin.setVersion(version);
return this;
}

/**
* @return the underlying plugin
*/
public Plugin getPlugin() {
return plugin;
}

/**
* Gets a parameter of the plugin based on its key
*
* @param key the param key
* @return the parameter if exist, null otherwise
*/
public String getParameter(String key) {
Xpp3Dom node = findNodeWith(key);
return node == null ? null : node.getValue();
}

/**
* Gets a list of parameters of the plugin from a param key
*
* @param key param key with option-index snippet: e.g. item[0], item[1]. If no index snippet is passed, then
* 0 is default (index <=> index[0])
* @return an array of parameters if any, an empty array otherwise
*/
public String[] getParameters(String key) {
String[] keyParts = StringUtils.split(key, "/");
Xpp3Dom node = configuration;
for (int i = 0; i < keyParts.length - 1; i++) {
node = getOrCreateChild(node, keyParts[i]);
}
Xpp3Dom[] children = node.getChildren(keyParts[keyParts.length - 1]);
String[] result = new String[children.length];
for (int i = 0; i < children.length; i++) {
result[i] = children[i].getValue();
}
return result;
}

/**
* Sets a parameter for the maven plugin. This will overrides an existing parameter.
*
* @param key the param key
* @param value the param value
* @return this
*/
public MavenPlugin setParameter(String key, String value) {
checkKeyArgument(key);
String[] keyParts = StringUtils.split(key, "/");
Xpp3Dom node = configuration;
for (String keyPart : keyParts) {
node = getOrCreateChild(node, keyPart);
}
node.setValue(value);
return this;
}

/**
* Sets a parameter to the maven plugin. Overrides existing parameter only id specified.
*
* @param key the param key
* @param value the param value
* @param override whether to override existing parameter
*/
public void setParameter(String key, String value, boolean override) {
if (getParameter(key) == null || override) {
setParameter(key, value);
}
}

/**
* Removes all parameters from the maven plugin
*/
public void removeParameters() {
configuration = new Xpp3Dom(CONFIGURATION_ELEMENT);
plugin.setConfiguration(this.configuration);
}

/**
* Adds a parameter to the maven plugin
*
* @param key the param key with option-index snippet: e.g. item[0], item[1]. If no index snippet is passed, then
* 0 is default (index <=> index[0])
* @param value the param value
* @return this
*/
public MavenPlugin addParameter(String key, String value) {
String[] keyParts = StringUtils.split(key, "/");
Xpp3Dom node = configuration;
for (int i = 0; i < keyParts.length - 1; i++) {
node = getOrCreateChild(node, keyParts[i]);
}
Xpp3Dom leaf = new Xpp3Dom(keyParts[keyParts.length - 1]);
leaf.setValue(value);
node.addChild(leaf);
return this;
}

private static Xpp3Dom getOrCreateChild(Xpp3Dom node, String key) {
int childIndex = getIndex(key);

if (node.getChildren(removeIndexSnippet(key)).length <= childIndex) {
Xpp3Dom child = new Xpp3Dom(removeIndexSnippet(key));
node.addChild(child);
return child;
}
return node.getChildren(removeIndexSnippet(key))[childIndex];

}

private static int getIndex(String key) {
// parsing index-syntax (e.g. item[1])
if (key.matches(".*?\\[\\d+\\]")) {
return Integer.parseInt(StringUtils.substringBetween(key, "[", "]"));
}
// for down-compatibility of api we fallback to default 0
return 0;
}

private static String removeIndexSnippet(String key) {
return StringUtils.substringBefore(key, "[");
}

/**
* Remove a parameter from the maven plugin based on its key
*
* @param key param key with option-index snippet: e.g. item[0], item[1]. If no index snippet is passed, then
* 0 is default (index <=> index[0])
*/
public void removeParameter(String key) {
Xpp3Dom node = findNodeWith(key);
if (node != null) {
remove(node);
}
}

private Xpp3Dom findNodeWith(String key) {
checkKeyArgument(key);
String[] keyParts = key.split("/");
Xpp3Dom node = configuration;
for (String keyPart : keyParts) {

if (node.getChildren(removeIndexSnippet(keyPart)).length <= getIndex(keyPart)) {
return null;
}

node = node.getChildren(removeIndexSnippet(keyPart))[getIndex(keyPart)];
if (node == null) {
return null;
}
}
return node;
}

private static void remove(Xpp3Dom node) {
Xpp3Dom parent = node.getParent();
for (int i = 0; i < parent.getChildCount(); i++) {
Xpp3Dom child = parent.getChild(i);
if (child.equals(node)) {
parent.removeChild(i);
break;
}
}
}

/**
* @return whether the maven plugin has got configuration
*/
public boolean hasConfiguration() {
return configuration.getChildCount() > 0;
}

private static void checkKeyArgument(String key) {
if (key == null) {
throw new IllegalArgumentException("Parameter 'key' should not be null.");
}
}

/**
* Registers a plugin in a project pom
* <p/>
* <p>Adds the plugin if it does not exist or amend its version if it does exist and specified</p>
*
* @param pom the project pom
* @param groupId the plugin group id
* @param artifactId the plugin artifact id
* @param version the plugin version
* @param overrideVersion whether to override the version if the plugin is already registered
* @return the registered plugin
*/
public static MavenPlugin registerPlugin(MavenProject pom, String groupId, String artifactId, String version, boolean overrideVersion) {
MavenPlugin plugin = getPlugin(pom, groupId, artifactId);
if (plugin == null) {
plugin = new MavenPlugin(groupId, artifactId, version);

} else if (overrideVersion) {
plugin.setVersion(version);
}

// remove from pom
unregisterPlugin(pom, groupId, artifactId);

// register
pom.getBuild().addPlugin(plugin.getPlugin());

return plugin;
}

/**
* Returns a plugin from a pom based on its group id and artifact id
* <p/>
* <p>It searches in the build section, then the reporting section and finally the pluginManagement section</p>
*
* @param pom the project pom
* @param groupId the plugin group id
* @param artifactId the plugin artifact id
* @return the plugin if it exists, null otherwise
*/
public static MavenPlugin getPlugin(MavenProject pom, String groupId, String artifactId) {
if (pom == null) {
return null;
}
// look for plugin in <build> section
Plugin plugin = null;
if (pom.getBuildPlugins() != null) {
plugin = getPlugin(pom.getBuildPlugins(), groupId, artifactId);
}

// look for plugin in <report> section
if (plugin == null && pom.getReportPlugins() != null) {
plugin = getReportPlugin(pom.getReportPlugins(), groupId, artifactId);
}

// look for plugin in <pluginManagement> section
if (pom.getPluginManagement() != null) {
Plugin pluginManagement = getPlugin(pom.getPluginManagement().getPlugins(), groupId, artifactId);
if (plugin == null) {
plugin = pluginManagement;

} else if (pluginManagement != null) {
if (pluginManagement.getConfiguration() != null) {
if (plugin.getConfiguration() == null) {
plugin.setConfiguration(pluginManagement.getConfiguration());
} else {
Xpp3Dom.mergeXpp3Dom((Xpp3Dom) plugin.getConfiguration(), (Xpp3Dom) pluginManagement.getConfiguration());
}
}
if (plugin.getDependencies() == null && pluginManagement.getDependencies() != null) {
plugin.setDependencies(pluginManagement.getDependencies());
}
if (plugin.getVersion() == null) {
plugin.setVersion(pluginManagement.getVersion());
}
}
}

if (plugin != null) {
return new MavenPlugin(plugin);
}
return null;
}

private static Plugin getPlugin(Collection<Plugin> plugins, String groupId, String artifactId) {
if (plugins == null) {
return null;
}

for (Plugin plugin : plugins) {
if (MavenUtils.equals(plugin, groupId, artifactId)) {
return plugin;
}
}
return null;
}

private static Plugin getReportPlugin(Collection<ReportPlugin> plugins, String groupId, String artifactId) {
if (plugins == null) {
return null;
}

for (ReportPlugin plugin : plugins) {
if (MavenUtils.equals(plugin, groupId, artifactId)) {
return cloneReportPluginToPlugin(plugin);
}
}
return null;
}

private static Plugin cloneReportPluginToPlugin(ReportPlugin reportPlugin) {
Plugin plugin = new Plugin();
plugin.setGroupId(reportPlugin.getGroupId());
plugin.setArtifactId(reportPlugin.getArtifactId());
plugin.setVersion(reportPlugin.getVersion());
plugin.setConfiguration(reportPlugin.getConfiguration());
return plugin;
}

private static void unregisterPlugin(MavenProject pom, String groupId, String artifactId) {
if (pom.getPluginManagement() != null && pom.getPluginManagement().getPlugins() != null) {
unregisterPlugin(pom.getPluginManagement().getPlugins(), groupId, artifactId);
}
List plugins = pom.getBuildPlugins();
if (plugins != null) {
unregisterPlugin(plugins, groupId, artifactId);
}
plugins = pom.getReportPlugins();
if (plugins != null) {
unregisterReportPlugin(plugins, groupId, artifactId);
}
}

private static void unregisterPlugin(List<Plugin> plugins, String groupId, String artifactId) {
for (Iterator<Plugin> iterator = plugins.iterator(); iterator.hasNext();) {
Plugin p = iterator.next();
if (MavenUtils.equals(p, groupId, artifactId)) {
iterator.remove();
}
}
}

private static void unregisterReportPlugin(List<ReportPlugin> plugins, String groupId, String artifactId) {
for (Iterator<ReportPlugin> iterator = plugins.iterator(); iterator.hasNext();) {
ReportPlugin p = iterator.next();
if (MavenUtils.equals(p, groupId, artifactId)) {
iterator.remove();
}
}
}

@Override
public String toString() {
return new ToStringBuilder(this)
.append("groupId", plugin.getGroupId())
.append("artifactId", plugin.getArtifactId())
.append("version", plugin.getVersion())
.toString();
}
}

+ 0
- 51
sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenSurefireUtils.java 查看文件

@@ -1,51 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.maven;

import org.sonar.api.resources.Project;

/**
* @since 1.10
* @deprecated since 4.5 we don't want any dependency on Maven anymore
*/
@Deprecated
public final class MavenSurefireUtils {

public static final String GROUP_ID = MavenUtils.GROUP_ID_APACHE_MAVEN;
public static final String ARTIFACT_ID = "maven-surefire-plugin";
public static final String VERSION = "2.4.3";

private MavenSurefireUtils() {
}

/**
* Configures the project POM with base required surefire settings
*
* @param project the project currently analyzed
* @return the configured surefire MavenPlugin object instance, cannot be null
*/
public static MavenPlugin configure(Project project) {
MavenPlugin surefire = MavenPlugin.registerPlugin(project.getPom(), GROUP_ID, ARTIFACT_ID, VERSION, false);
surefire.setParameter("disableXmlReport", "false");
surefire.setParameter("testFailureIgnore", "true");
return surefire;
}

}

+ 0
- 150
sonar-plugin-api/src/main/java/org/sonar/api/batch/maven/MavenUtils.java 查看文件

@@ -1,150 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.maven;

import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.project.MavenProject;
import org.sonar.api.utils.log.Loggers;

import java.nio.charset.Charset;
import java.util.Collection;

/**
* An utility class to manipulate Maven concepts
*
* @since 1.10
* @deprecated since 4.5 we don't want any dependency on Maven anymore
*/
@Deprecated
public final class MavenUtils {

private static final String MAVEN_COMPILER_PLUGIN = "maven-compiler-plugin";
public static final String GROUP_ID_APACHE_MAVEN = "org.apache.maven.plugins";
public static final String GROUP_ID_CODEHAUS_MOJO = "org.codehaus.mojo";

private MavenUtils() {
// utility class with only static methods
}

/**
* Returns the version of Java used by the maven compiler plugin
*
* @param pom the project pom
* @return the java version
*/
public static String getJavaVersion(MavenProject pom) {
MavenPlugin compilerPlugin = MavenPlugin.getPlugin(pom, GROUP_ID_APACHE_MAVEN, MAVEN_COMPILER_PLUGIN);
if (compilerPlugin != null) {
return compilerPlugin.getParameter("target");
}
return null;
}

public static String getJavaSourceVersion(MavenProject pom) {
MavenPlugin compilerPlugin = MavenPlugin.getPlugin(pom, GROUP_ID_APACHE_MAVEN, MAVEN_COMPILER_PLUGIN);
if (compilerPlugin != null) {
return compilerPlugin.getParameter("source");
}
return null;
}

/**
* Queries a collection of plugins based on a group id and an artifact id and returns the plugin if it exists
*
* @param plugins the plugins collection
* @param groupId the group id
* @param artifactId the artifact id
* @return the corresponding plugin if it exists, null otherwise
*/
public static Plugin getPlugin(Collection<Plugin> plugins, String groupId, String artifactId) {
if (plugins != null) {
for (Plugin plugin : plugins) {
if (equals(plugin, groupId, artifactId)) {
return plugin;
}
}
}
return null;
}

/**
* Tests whether a plugin has got a given artifact id and group id
*
* @param plugin the plugin to test
* @param groupId the group id
* @param artifactId the artifact id
* @return whether the plugin has got group + artifact ids
*/
public static boolean equals(Plugin plugin, String groupId, String artifactId) {
if (plugin != null && plugin.getArtifactId().equals(artifactId)) {
if (plugin.getGroupId() == null) {
return groupId == null || groupId.equals(MavenUtils.GROUP_ID_APACHE_MAVEN) || groupId.equals(MavenUtils.GROUP_ID_CODEHAUS_MOJO);
}
return plugin.getGroupId().equals(groupId);
}
return false;
}

/**
* Tests whether a ReportPlugin has got a given artifact id and group id
*
* @param plugin the ReportPlugin to test
* @param groupId the group id
* @param artifactId the artifact id
* @return whether the ReportPlugin has got group + artifact ids
*/
public static boolean equals(ReportPlugin plugin, String groupId, String artifactId) {
if (plugin != null && plugin.getArtifactId().equals(artifactId)) {
if (plugin.getGroupId() == null) {
return groupId == null || groupId.equals(MavenUtils.GROUP_ID_APACHE_MAVEN) || groupId.equals(MavenUtils.GROUP_ID_CODEHAUS_MOJO);
}
return plugin.getGroupId().equals(groupId);
}
return false;
}

/**
* @return source encoding
*/
public static String getSourceEncoding(MavenProject pom) {
return pom.getProperties().getProperty("project.build.sourceEncoding");
}

/**
* Returns the charset of a pom
*
* @param pom the project pom
* @return the charset
*/
public static Charset getSourceCharset(MavenProject pom) {
String encoding = getSourceEncoding(pom);
if (StringUtils.isNotEmpty(encoding)) {
try {
return Charset.forName(encoding);

} catch (Exception e) {
Loggers.get(MavenUtils.class).warn("Can not get project charset", e);
}
}
return Charset.defaultCharset();
}
}

+ 5
- 64
sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java 查看文件

@@ -19,21 +19,18 @@
*/
package org.sonar.api.resources;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.maven.project.MavenProject;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.component.Component;
import org.sonar.api.config.Settings;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* A class that manipulates Projects in the Sonar way.
*
@@ -74,12 +71,10 @@ public class Project extends Resource implements Component {
}
}

private MavenProject pom;
private String branch;
private ProjectFileSystem fileSystem;
private String name;
private String description;
private String packaging;
private Language language;
private Date analysisDate;
private AnalysisType analysisType;
@@ -122,23 +117,6 @@ public class Project extends Resource implements Component {
return this;
}

/**
* For internal use only.
*/
public final Project setPom(MavenProject pom) {
this.pom = pom;
return this;
}

/**
* @return the project's packaging
* @deprecated in 2.8. See http://jira.sonarsource.com/browse/SONAR-2341
*/
@Deprecated
public String getPackaging() {
return packaging;
}

@Override
public String getName() {
return name;
@@ -170,17 +148,6 @@ public class Project extends Resource implements Component {
return this;
}

/**
* For internal use only.
*
* @deprecated in 2.8. See http://jira.sonarsource.com/browse/SONAR-2341
*/
@Deprecated
public Project setPackaging(String packaging) {
this.packaging = packaging;
return this;
}

/**
* @return whether the current project is root project
*/
@@ -393,32 +360,6 @@ public class Project extends Resource implements Component {
return this;
}

/**
* @deprecated since 2.5. See http://jira.sonarsource.com/browse/SONAR-2011
*/
@Deprecated
public String getGroupId() {
return pom.getGroupId();
}

/**
* @deprecated since 2.5. See http://jira.sonarsource.com/browse/SONAR-2011
*/
@Deprecated
public String getArtifactId() {
return pom.getArtifactId();
}

/**
* @return the underlying Maven project
* @deprecated since 2.5. See http://jira.sonarsource.com/browse/SONAR-2011 ,
* MavenProject can be retrieved as an IoC dependency
*/
@Deprecated
public MavenProject getPom() {
return pom;
}

public static Project createFromMavenIds(String groupId, String artifactId) {
return createFromMavenIds(groupId, artifactId, null);
}

+ 0
- 305
sonar-plugin-api/src/test/java/org/sonar/api/batch/maven/MavenPluginTest.java 查看文件

@@ -1,305 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.maven;

import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.test.MavenTestUtils;

import static org.assertj.core.api.Assertions.assertThat;


public class MavenPluginTest {

private MavenPlugin fakePlugin;

@Before
public void initPlugin() {
fakePlugin = new MavenPlugin("foo", "bar", "1.0");
}

@Test
public void getConfigurationXmlNode() {
assertThat(fakePlugin.getConfigurationXmlNode()).isNotNull();
assertThat(fakePlugin.getConfigurationXmlNode().getName()).isEqualTo("configuration");
}

@Test
public void removeParameters() {
fakePlugin
.setParameter("foo", "bar")
.setParameter("hello", "world")
.removeParameters();

assertThat(fakePlugin.getParameter("foo")).isNull();
assertThat(fakePlugin.getParameter("hello")).isNull();
assertThat(fakePlugin.hasConfiguration()).isFalse();
}

@Test
public void shouldWriteAndReadSimpleConfiguration() {
fakePlugin.setParameter("abc", "test");
assertThat(fakePlugin.getParameter("abc")).isEqualTo("test");
}

@Test
public void shouldWriteAndReadComplexConfiguration() {
fakePlugin.setParameter("abc/def/ghi", "test");
assertThat(fakePlugin.getParameter("abc/def/ghi")).isEqualTo("test");
}

@Test
public void shouldReturnNullWhenChildNotFound() {
assertThat(fakePlugin.getParameter("abc/def/ghi")).isNull();
}

@Test(expected = IllegalArgumentException.class)
public void getChildValueShouldThrowExceptionWhenKeyIsNull() {
fakePlugin.getParameter(null);
}

@Test(expected = IllegalArgumentException.class)
public void setChildValueShouldThrowExceptionWhenKeyIsNull() {
fakePlugin.setParameter(null, null);
}

@Test
public void shouldRemoveParameter() {
fakePlugin.setParameter("abc", "1");
assertThat(fakePlugin.getParameter("abc")).isNotNull();

fakePlugin.removeParameter("abc");
assertThat(fakePlugin.getParameter("abc")).isNull();
}

@Test
public void shouldRemoveNestedParameter() {
fakePlugin.setParameter("abc/def", "1");
assertThat(fakePlugin.getParameter("abc/def")).isNotNull();

fakePlugin.removeParameter("abc/def");

assertThat(fakePlugin.getParameter("abc/def")).isNull();
}

@Test
public void shouldRemoveNestedParameterButLeaveTheParent() {
fakePlugin.setParameter("abc/x", "1");
fakePlugin.setParameter("abc/y", "2");

fakePlugin.removeParameter("abc/x");

assertThat(fakePlugin.getParameter("abc/y")).isNotNull();
}

@Test
public void shouldRemoveUnfoundChildWithoutError() {
fakePlugin.removeParameter("abc/def");
}


@Test
public void shouldSetParameter() {
fakePlugin.addParameter("exclude", "abc");
assertThat(fakePlugin.getParameter("exclude")).isEqualTo("abc");
assertThat(fakePlugin.getParameters("exclude")).containsOnly("abc");
}

@Test
public void shouldOverrideNestedParameter() {
fakePlugin.setParameter("excludes/exclude", "abc");
fakePlugin.setParameter("excludes/exclude", "overridden");
assertThat(fakePlugin.getParameter("excludes/exclude")).isEqualTo("overridden");
assertThat(fakePlugin.getParameters("excludes/exclude")).containsOnly("overridden");
}

@Test
public void shouldOverriddeParameter() {
fakePlugin.setParameter("exclude", "abc");
fakePlugin.setParameter("exclude", "overridden");
assertThat(fakePlugin.getParameter("exclude")).isEqualTo("overridden");
assertThat(fakePlugin.getParameters("exclude")).containsOnly("overridden");
}

@Test
public void shouldAddNestedParameter() {
fakePlugin.addParameter("excludes/exclude", "abc");
assertThat(fakePlugin.getParameter("excludes/exclude")).isEqualTo("abc");
assertThat(fakePlugin.getParameters("excludes/exclude")).containsOnly("abc");
}

@Test
public void shouldAddManyValuesToTheSameParameter() {
fakePlugin.addParameter("excludes/exclude", "abc");
fakePlugin.addParameter("excludes/exclude", "def");
assertThat(fakePlugin.getParameters("excludes/exclude")).containsOnly("abc", "def");
}

@Test
public void defaultParameterIndexIsZero() {
fakePlugin.addParameter("items/item/entry", "value1");
fakePlugin.addParameter("items/item/entry", "value2");

assertThat(fakePlugin.getParameters("items/item/entry")).containsOnly("value1", "value2");
assertThat(fakePlugin.getParameters("items/item[0]/entry")).containsOnly("value1", "value2");
}


@Test
public void addIndexedParameters() {
fakePlugin.addParameter("items/item[0]/entry", "value1");
fakePlugin.addParameter("items/item[1]/entry", "value2");

assertThat(fakePlugin.getParameter("items/item[0]/entry")).isEqualTo("value1");
assertThat(fakePlugin.getParameters("items/item[0]/entry")).containsOnly("value1");

assertThat(fakePlugin.getParameter("items/item[1]/entry")).isEqualTo("value2");
assertThat(fakePlugin.getParameters("items/item[1]/entry")).containsOnly("value2");

//ensure that indexes aren't serialized to real configuration
assertThat(fakePlugin.getPlugin().getConfiguration().toString()).doesNotContain("item[0]");
assertThat(fakePlugin.getPlugin().getConfiguration().toString()).doesNotContain("item[1]");
}

@Test
public void removeIndexedParameter() {
fakePlugin.addParameter("items/item[0]/entry", "value1");
fakePlugin.addParameter("items/item[1]/entry", "value2");

fakePlugin.removeParameter("items/item[1]");
fakePlugin.removeParameter("items/notExists");

assertThat(fakePlugin.getParameter("items/item[0]/entry")).isNotNull();
assertThat(fakePlugin.getParameter("items/item[1]/entry")).isNull();
assertThat(fakePlugin.getParameter("items/notExists")).isNull();
}

@Test
public void registerNewPlugin() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "registerNewPlugin.xml");
MavenPlugin mavenPlugin = MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", true);

assertThat(mavenPlugin).isNotNull();
Plugin plugin = MavenUtils.getPlugin(pom.getBuildPlugins(), "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getVersion()).isEqualTo("1.0");
}

@Test
public void overridePluginManagementSection() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "overridePluginManagementSection.xml");
MavenPlugin mavenPlugin = MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", true);
assertThat(mavenPlugin).isNotNull();

Plugin plugin = MavenUtils.getPlugin(pom.getBuildPlugins(), "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getVersion()).isEqualTo("1.0");

Plugin pluginManagement = MavenUtils.getPlugin(pom.getPluginManagement().getPlugins(), "mygroup", "my.artifact");
assertThat(pluginManagement).isNull();
}

@Test
public void doNotOverrideVersionFromPluginManagementSection() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "overridePluginManagementSection.xml");
MavenPlugin mavenPlugin = MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", false);
assertThat(mavenPlugin).isNotNull();

Plugin plugin = MavenUtils.getPlugin(pom.getBuildPlugins(), "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getVersion()).isEqualTo("0.9");

Plugin pluginManagement = MavenUtils.getPlugin(pom.getPluginManagement().getPlugins(), "mygroup", "my.artifact");
assertThat(pluginManagement).isNull();
}

@Test
public void keepPluginManagementDependencies() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "keepPluginManagementDependencies.xml");
MavenPlugin mavenPlugin = MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", false);
assertThat(mavenPlugin).isNotNull();

Plugin plugin = MavenUtils.getPlugin(pom.getBuildPlugins(), "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getVersion()).isEqualTo("0.9");
assertThat(plugin.getDependencies().size()).isEqualTo(1);
}

@Test
public void keepPluginDependencies() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "keepPluginDependencies.xml");
MavenPlugin mavenPlugin = MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", false);
assertThat(mavenPlugin).isNotNull();

Plugin plugin = MavenUtils.getPlugin(pom.getBuildPlugins(), "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getVersion()).isEqualTo("0.9");
assertThat(plugin.getDependencies().size()).isEqualTo(1);
}

@Test
public void mergeSettings() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "mergeSettings.xml");
MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", false);

MavenPlugin plugin = MavenPlugin.getPlugin(pom, "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getPlugin().getVersion()).isEqualTo("0.9");
assertThat(plugin.getParameter("foo")).isEqualTo("bar");
}

@Test
public void overrideVersionFromPluginManagement() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "overrideVersionFromPluginManagement.xml");
MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", true);

MavenPlugin plugin = MavenPlugin.getPlugin(pom, "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getPlugin().getVersion()).isEqualTo("1.0");
assertThat(plugin.getParameter("foo")).isEqualTo("bar");
}

@Test
public void overrideVersion() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "overrideVersion.xml");
MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", true);

MavenPlugin plugin = MavenPlugin.getPlugin(pom, "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getPlugin().getVersion()).isEqualTo("1.0");
assertThat(plugin.getParameter("foo")).isEqualTo("bar");
}

@Test
public void getConfigurationFromReport() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "getConfigurationFromReport.xml");
MavenPlugin.registerPlugin(pom, "mygroup", "my.artifact", "1.0", true);

assertThat(pom.getBuildPlugins().size()).isEqualTo(1);
assertThat(pom.getReportPlugins().size()).isEqualTo(0);

MavenPlugin plugin = MavenPlugin.getPlugin(pom, "mygroup", "my.artifact");
assertThat(plugin).isNotNull();
assertThat(plugin.getPlugin().getVersion()).isEqualTo("1.0");
assertThat(plugin.getParameter("foo")).isEqualTo("bar");
}
}

+ 0
- 42
sonar-plugin-api/src/test/java/org/sonar/api/batch/maven/MavenSurefireUtilsTest.java 查看文件

@@ -1,42 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.maven;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.sonar.api.resources.Project;
import org.sonar.api.test.MavenTestUtils;

public class MavenSurefireUtilsTest {

@Test
public void shouldConfigureProject() {
Project prj = mock(Project.class);
when(prj.getPom()).thenReturn(MavenTestUtils.loadPom("/org/sonar/api/batch/maven/MavenSurefireUtilsTest/MavenPom.xml"));

MavenPlugin configuredPlugin = MavenSurefireUtils.configure(prj);
assertEquals("true", configuredPlugin.getParameter("testFailureIgnore"));
assertEquals("false", configuredPlugin.getParameter("disableXmlReport"));
assertEquals(MavenSurefireUtils.VERSION, configuredPlugin.getPlugin().getVersion());
}

}

+ 0
- 64
sonar-plugin-api/src/test/java/org/sonar/api/batch/maven/MavenUtilsTest.java 查看文件

@@ -1,64 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.maven;

import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.test.MavenTestUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

public class MavenUtilsTest {
private MavenProject pom;

@Before
public void setUp() {
pom = MavenTestUtils.loadPom("/org/sonar/api/batch/maven/MavenPom.xml");
}

@Test
public void getJavaVersion() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "getJavaVersion.xml");
assertThat(MavenUtils.getJavaVersion(pom), is("1.4"));
}

@Test
public void getJavaVersionFromPluginManagement() {
MavenProject pom = MavenTestUtils.loadPom(getClass(), "getJavaVersionFromPluginManagement.xml");
assertThat(MavenUtils.getJavaVersion(pom), is("1.4"));
}

@Test
public void testDefaultSourceEncoding() {
assertEquals(MavenUtils.getSourceCharset(pom), Charset.defaultCharset());
}

@Test
public void testSourceEncoding() {
MavenProject pom = MavenTestUtils.loadPom("/org/sonar/api/batch/maven/MavenPomWithSourceEncoding.xml");
assertEquals(MavenUtils.getSourceCharset(pom), StandardCharsets.UTF_16);
}
}

+ 0
- 11
sonar-plugin-api/src/test/java/org/sonar/api/resources/ProjectTest.java 查看文件

@@ -20,22 +20,11 @@
package org.sonar.api.resources;

import org.junit.Test;
import org.sonar.api.test.MavenTestUtils;

import static org.assertj.core.api.Assertions.assertThat;

public class ProjectTest {

@Test
public void equalsProject() {
Project project1 = MavenTestUtils.loadProjectFromPom(getClass(), "equalsProject/pom.xml");
Project project2 = MavenTestUtils.loadProjectFromPom(getClass(), "equalsProject/pom.xml");

assertThat(project1).isEqualTo(project2);
assertThat(project1).isNotEqualTo("foo:bar");
assertThat(project1.hashCode()).isEqualTo(project2.hashCode());
}

@Test
public void effectiveKeyShouldEqualKey() {
assertThat(new Project("my:project").getEffectiveKey()).isEqualTo("my:project");

+ 0
- 190
sonar-plugin-api/src/test/java/org/sonar/api/test/MavenTestUtils.java 查看文件

@@ -1,190 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.test;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.sonar.api.batch.maven.MavenUtils;
import org.sonar.api.resources.InputFile;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.ProjectFileSystem;
import org.sonar.api.resources.Resource;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.SonarException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public final class MavenTestUtils {

public static MavenProject loadPom(Class clazz, String path) {
String fullpath = "/" + clazz.getName().replaceAll("\\.", "/") + "/" + path;
return loadPom(fullpath);
}

public static MavenProject loadPom(String pomUrlInClasspath) {
FileReader fileReader = null;
try {
File pomFile = new File(MavenTestUtils.class.getResource(pomUrlInClasspath).toURI());
MavenXpp3Reader pomReader = new MavenXpp3Reader();
fileReader = new FileReader(pomFile);
Model model = pomReader.read(fileReader);
MavenProject project = new MavenProject(model);
project.setFile(pomFile);
project.getBuild().setDirectory(pomFile.getParentFile().getPath());
project.addCompileSourceRoot(pomFile.getParentFile().getPath() + "/src/main/java");
project.addTestCompileSourceRoot(pomFile.getParentFile().getPath() + "/src/test/java");
return project;
} catch (Exception e) {
throw new SonarException("Failed to read Maven project file : " + pomUrlInClasspath, e);

} finally {
IOUtils.closeQuietly(fileReader);
}
}

public static Project loadProjectFromPom(Class clazz, String path) {
MavenProject pom = loadPom(clazz, path);
Project project = new Project(pom.getGroupId() + ":" + pom.getArtifactId())
.setPom(pom);
// configuration.setProperty("sonar.java.source", MavenUtils.getJavaSourceVersion(pom));
// configuration.setProperty("sonar.java.target", MavenUtils.getJavaVersion(pom));
// configuration.setProperty(CoreProperties.ENCODING_PROPERTY, MavenUtils.getSourceEncoding(pom));

project.setFileSystem(new MavenModuleFileSystem(pom));
return project;
}

public static MavenProject mockPom(String packaging) {
MavenProject mavenProject = mock(MavenProject.class);
when(mavenProject.getPackaging()).thenReturn(packaging);
return mavenProject;
}

static class MavenModuleFileSystem implements ProjectFileSystem {
private MavenProject pom;

MavenModuleFileSystem(MavenProject pom) {
this.pom = pom;
}

public Charset getSourceCharset() {
return Charset.forName(MavenUtils.getSourceEncoding(pom));
}

public File getBasedir() {
return pom.getBasedir();
}

public File getBuildDir() {
return new File(pom.getBuild().getDirectory());
}

public File getBuildOutputDir() {
return new File(pom.getBuild().getOutputDirectory());
}

public List<File> getSourceDirs() {
return Arrays.asList(new File(pom.getBuild().getSourceDirectory()));
}

public ProjectFileSystem addSourceDir(File dir) {
throw new UnsupportedOperationException();
}

public List<File> getTestDirs() {
return null;
}

public ProjectFileSystem addTestDir(File dir) {
throw new UnsupportedOperationException();
}

public File getReportOutputDir() {
return null;
}

public File getSonarWorkingDirectory() {
File dir = new File(getBuildDir(), "sonar");
try {
FileUtils.forceMkdir(dir);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return dir;
}

public File resolvePath(String path) {
return new PathResolver().relativeFile(getBasedir(), path);
}

public List<File> getSourceFiles(Language... langs) {
return new ArrayList(FileUtils.listFiles(getSourceDirs().get(0), new String[] {"java"}, true));
}

public List<File> getJavaSourceFiles() {
return getSourceFiles();
}

public boolean hasJavaSourceFiles() {
return !getJavaSourceFiles().isEmpty();
}

public List<File> getTestFiles(Language... langs) {
return new ArrayList(FileUtils.listFiles(getTestDirs().get(0), new String[] {"java"}, true));
}

public boolean hasTestFiles(Language lang) {
return !getTestFiles(lang).isEmpty();
}

public File writeToWorkingDirectory(String content, String fileName) throws IOException {
throw new UnsupportedOperationException();
}

public File getFileFromBuildDirectory(String filename) {
throw new UnsupportedOperationException();
}

public Resource toResource(File file) {
throw new UnsupportedOperationException();
}

public List<InputFile> mainFiles(String... langs) {
throw new UnsupportedOperationException();
}

public List<InputFile> testFiles(String... langs) {
throw new UnsupportedOperationException();
}
}
}

+ 0
- 37
sonar-plugin-api/src/test/java/org/sonar/api/test/ProjectTestBuilder.java 查看文件

@@ -1,37 +0,0 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.test;

import org.apache.maven.project.MavenProject;
import org.sonar.api.resources.Project;

import static org.mockito.Mockito.when;

public class ProjectTestBuilder {

private MavenProject pom = MavenTestUtils.mockPom("jar");

public Project build() {
when(pom.getGroupId()).thenReturn("mygroup");
when(pom.getArtifactId()).thenReturn("myartifact");
when(pom.isExecutionRoot()).thenReturn(true);
return new Project("mygroup:myartifact").setPom(pom);
}
}

+ 0
- 7
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/pom.xml 查看文件

@@ -1,7 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>foo</artifactId>

</project>

+ 0
- 1
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/src/main/java/.hidden 查看文件

@@ -1 +0,0 @@
this is an hidden file

+ 0
- 1
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/src/main/java/.hiddendir/file_in_hidden_dir.txt 查看文件

@@ -1 +0,0 @@
file in hidden dir

+ 0
- 0
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/hidden-files/src/main/java/foo.sql 查看文件


+ 0
- 26
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/japanese-project/pom.xml 查看文件

@@ -1,26 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>foo</artifactId>
<packaging>jar</packaging>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<encoding>Shift_JIS</encoding>
</configuration>
</plugin>
</plugins>
</build>

<properties>
<project.build.sourceEncoding>Shift_JIS</project.build.sourceEncoding>
</properties>

</project>

+ 0
- 8
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/nonexistent-dirs/pom.xml 查看文件

@@ -1,8 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>foo</artifactId>
<packaging>jar</packaging>

</project>

+ 0
- 0
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/nonexistent-dirs/src/main/java 查看文件


+ 0
- 7
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample-with-different-suffixes/pom.xml 查看文件

@@ -1,7 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>foo</artifactId>
<packaging>jar</packaging>
</project>

+ 0
- 1
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample-with-different-suffixes/src/main/java/foo.c 查看文件

@@ -1 +0,0 @@
// some C code

+ 0
- 1
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample-with-different-suffixes/src/main/java/foo.sql 查看文件

@@ -1 +0,0 @@
select * from foo;

+ 0
- 8
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/pom.xml 查看文件

@@ -1,8 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>foo</artifactId>
<packaging>jar</packaging>

</project>

+ 0
- 4
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/src/main/java/foo/Bar.java 查看文件

@@ -1,4 +0,0 @@
package foo;

public class Bar {
}

+ 0
- 4
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/src/main/java/foo/Whizz.java 查看文件

@@ -1,4 +0,0 @@
package foo;

public class Whizz {
}

+ 0
- 6
sonar-plugin-api/src/test/resources/org/sonar/api/resources/DefaultProjectFileSystemTest/sample/src/test/java/foo/BarTest.java 查看文件

@@ -1,6 +0,0 @@
package foo;

import org.junit.Ignore;

public abstract class BarTest {
}

+ 0
- 8
sonar-plugin-api/src/test/resources/org/sonar/api/resources/ProjectTest/equalsProject/pom.xml 查看文件

@@ -1,8 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<packaging>jar</packaging>

</project>

+ 0
- 11
sonar-plugin-api/src/test/resources/org/sonar/api/resources/ProjectTest/keyContainsBranch/pom.xml 查看文件

@@ -1,11 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<packaging>jar</packaging>

<properties>
<sonar.branch>BRANCH-1.X</sonar.branch>
</properties>
</project>

正在加载...
取消
保存