]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-6015 Produce Json report
authorJulien HENRY <julien.henry@sonarsource.com>
Mon, 12 Jan 2015 10:05:31 +0000 (11:05 +0100)
committerJulien HENRY <julien.henry@sonarsource.com>
Tue, 13 Jan 2015 14:55:37 +0000 (15:55 +0100)
14 files changed:
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchPluginRepository.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BootstrapContainer.java
sonar-batch/src/main/java/org/sonar/batch/phases/PreviewPhaseExecutor.java
sonar-batch/src/main/java/org/sonar/batch/referential/DefaultProjectReferentialsLoader.java
sonar-batch/src/main/java/org/sonar/batch/rule/RuleFinderCompatibility.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/scan/ModuleScanContainer.java
sonar-batch/src/main/java/org/sonar/batch/scan/ProjectScanContainer.java
sonar-batch/src/main/java/org/sonar/batch/scan/measure/MeasureCache.java
sonar-batch/src/main/java/org/sonar/batch/scan/report/JsonReport.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/DefaultPluginsReferentialTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/bootstrap/PluginDownloaderTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/scan/measure/MeasureCacheTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/report/JsonReportTest.java

index a29327a1f5e93826216f7642120a34285947446e..68275cb247a12eccf3e6d83ac73ee76502f0d392 100644 (file)
@@ -25,7 +25,6 @@ import org.sonar.api.Properties;
 import org.sonar.api.Property;
 import org.sonar.api.PropertyType;
 import org.sonar.api.SonarPlugin;
-import org.sonar.api.checks.NoSonarFilter;
 import org.sonar.core.timemachine.Periods;
 import org.sonar.plugins.core.charts.DistributionAreaChart;
 import org.sonar.plugins.core.charts.DistributionBarChart;
@@ -373,7 +372,6 @@ public final class CorePlugin extends SonarPlugin {
       CoverageMeasurementFilter.class,
       ApplyProjectRolesDecorator.class,
       CommentDensityDecorator.class,
-      NoSonarFilter.class,
       DirectoriesDecorator.class,
       FilesDecorator.class,
       ManualMeasureDecorator.class,
index 0ecd4d2b0aeac051f77305ee2004ccbdd66d63d8..909c3a057ca0e3994d6dd73abad12971ce5bba9e 100644 (file)
@@ -134,8 +134,10 @@ public class BatchPluginRepository implements PluginRepository {
   static class PluginFilter {
     private static final String PROPERTY_IS_DEPRECATED_MSG = "Property {0} is deprecated. Please use {1} instead.";
     Set<String> whites = newHashSet(), blacks = newHashSet();
+    private AnalysisMode mode;
 
     PluginFilter(Settings settings, AnalysisMode mode) {
+      this.mode = mode;
       if (settings.hasKey(CoreProperties.BATCH_INCLUDE_PLUGINS)) {
         whites.addAll(Arrays.asList(settings.getStringArray(CoreProperties.BATCH_INCLUDE_PLUGINS)));
       }
@@ -177,7 +179,7 @@ public class BatchPluginRepository implements PluginRepository {
 
     boolean accepts(String pluginKey) {
       if (CORE_PLUGIN.equals(pluginKey)) {
-        return true;
+        return !mode.isSensorMode();
       }
 
       List<String> mergeList = newArrayList(blacks);
index dd49c4e9a1298cfc9dae9dbbc8c99332e81b42c8..ca174d3a80a41676f18a7cd78a81e1d456ca2a36 100644 (file)
@@ -83,6 +83,7 @@ public class BootstrapContainer extends ComponentContainer {
       addDatabaseComponents();
       addCoreComponents();
     }
+
   }
 
   private void addBootstrapComponents() {
index 15cf37b1899545728eb485227f7252f3104f158f..1e8dde4fc8bb3098482bd05df885af6d608ce555 100644 (file)
@@ -32,6 +32,7 @@ import org.sonar.batch.rule.QProfileVerifier;
 import org.sonar.batch.scan.filesystem.DefaultModuleFileSystem;
 import org.sonar.batch.scan.filesystem.FileSystemLogger;
 import org.sonar.batch.scan.maven.MavenPluginsConfigurator;
+import org.sonar.batch.scan.report.JsonReport;
 
 public final class PreviewPhaseExecutor implements PhaseExecutor {
 
@@ -50,12 +51,13 @@ public final class PreviewPhaseExecutor implements PhaseExecutor {
   private final QProfileVerifier profileVerifier;
   private final IssueExclusionsLoader issueExclusionsLoader;
   private final AnalysisMode analysisMode;
+  private final JsonReport jsonReport;
 
   public PreviewPhaseExecutor(Phases phases,
     MavenPluginsConfigurator mavenPluginsConfigurator, InitializersExecutor initializersExecutor,
     SensorsExecutor sensorsExecutor,
     SensorContext sensorContext, DefaultIndex index,
-    EventBus eventBus, ProjectInitializer pi, FileSystemLogger fsLogger, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier,
+    EventBus eventBus, ProjectInitializer pi, FileSystemLogger fsLogger, JsonReport jsonReport, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier,
     IssueExclusionsLoader issueExclusionsLoader, AnalysisMode analysisMode) {
     this.phases = phases;
     this.mavenPluginsConfigurator = mavenPluginsConfigurator;
@@ -66,6 +68,7 @@ public final class PreviewPhaseExecutor implements PhaseExecutor {
     this.eventBus = eventBus;
     this.pi = pi;
     this.fsLogger = fsLogger;
+    this.jsonReport = jsonReport;
     this.fs = fs;
     this.profileVerifier = profileVerifier;
     this.issueExclusionsLoader = issueExclusionsLoader;
@@ -98,6 +101,10 @@ public final class PreviewPhaseExecutor implements PhaseExecutor {
       sensorsExecutor.execute(sensorContext);
     }
 
+    if (module.isRoot()) {
+      jsonReport.execute();
+    }
+
     cleanMemory();
     eventBus.fireEvent(new ProjectAnalysisEvent(module, false));
   }
index bf2957084ce31db8f4819a0c378a2e1c078f7652..78f085c3541574b98db4ae2eeb844dfeb164cdff 100644 (file)
@@ -71,6 +71,13 @@ public class DefaultProjectReferentialsLoader implements ProjectReferentialsLoad
     this.dao = dao;
   }
 
+  public DefaultProjectReferentialsLoader(ServerClient serverClient, AnalysisMode analysisMode) {
+    this.session = null;
+    this.serverClient = serverClient;
+    this.analysisMode = analysisMode;
+    this.dao = null;
+  }
+
   @Override
   public ProjectReferentials load(ProjectReactor reactor, TaskProperties taskProperties) {
     String projectKey = reactor.getRoot().getKeyWithBranch();
@@ -83,29 +90,31 @@ public class DefaultProjectReferentialsLoader implements ProjectReferentialsLoad
     url += "&preview=" + analysisMode.isPreview();
     ProjectReferentials ref = ProjectReferentials.fromJson(serverClient.request(url));
 
-    for (ProjectDefinition module : reactor.getProjects()) {
-
-      for (Map.Entry<String, String> hashByPaths : hashByRelativePath(module.getKeyWithBranch()).entrySet()) {
-        String path = hashByPaths.getKey();
-        String hash = hashByPaths.getValue();
-        String lastCommits = null;
-        String revisions = null;
-        String authors = null;
-        List<Object[]> measuresByKey = query(projectKey + ":" + path, CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY, CoreMetrics.SCM_REVISIONS_BY_LINE_KEY,
-          CoreMetrics.SCM_AUTHORS_BY_LINE_KEY);
-        for (Object[] measureByKey : measuresByKey) {
-          if (measureByKey[0].equals(CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY)) {
-            lastCommits = ((MeasureModel) measureByKey[1]).getData(CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE);
-          } else if (measureByKey[0].equals(CoreMetrics.SCM_REVISIONS_BY_LINE_KEY)) {
-            revisions = ((MeasureModel) measureByKey[1]).getData(CoreMetrics.SCM_REVISIONS_BY_LINE);
-          } else if (measureByKey[0].equals(CoreMetrics.SCM_AUTHORS_BY_LINE_KEY)) {
-            authors = ((MeasureModel) measureByKey[1]).getData(CoreMetrics.SCM_AUTHORS_BY_LINE);
+    if (session != null) {
+      for (ProjectDefinition module : reactor.getProjects()) {
+
+        for (Map.Entry<String, String> hashByPaths : hashByRelativePath(module.getKeyWithBranch()).entrySet()) {
+          String path = hashByPaths.getKey();
+          String hash = hashByPaths.getValue();
+          String lastCommits = null;
+          String revisions = null;
+          String authors = null;
+          List<Object[]> measuresByKey = query(projectKey + ":" + path, CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY, CoreMetrics.SCM_REVISIONS_BY_LINE_KEY,
+            CoreMetrics.SCM_AUTHORS_BY_LINE_KEY);
+          for (Object[] measureByKey : measuresByKey) {
+            if (measureByKey[0].equals(CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY)) {
+              lastCommits = ((MeasureModel) measureByKey[1]).getData(CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE);
+            } else if (measureByKey[0].equals(CoreMetrics.SCM_REVISIONS_BY_LINE_KEY)) {
+              revisions = ((MeasureModel) measureByKey[1]).getData(CoreMetrics.SCM_REVISIONS_BY_LINE);
+            } else if (measureByKey[0].equals(CoreMetrics.SCM_AUTHORS_BY_LINE_KEY)) {
+              authors = ((MeasureModel) measureByKey[1]).getData(CoreMetrics.SCM_AUTHORS_BY_LINE);
+            }
           }
+          ref.addFileData(module.getKeyWithBranch(), path, new FileData(hash, lastCommits, revisions, authors));
         }
-        ref.addFileData(module.getKeyWithBranch(), path, new FileData(hash, lastCommits, revisions, authors));
       }
+      ref.setLastAnalysisDate(lastSnapshotCreationDate(projectKey));
     }
-    ref.setLastAnalysisDate(lastSnapshotCreationDate(projectKey));
     return ref;
   }
 
diff --git a/sonar-batch/src/main/java/org/sonar/batch/rule/RuleFinderCompatibility.java b/sonar-batch/src/main/java/org/sonar/batch/rule/RuleFinderCompatibility.java
new file mode 100644 (file)
index 0000000..2fe3dc1
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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.rule;
+
+import org.sonar.api.batch.rule.ActiveRule;
+import org.sonar.api.batch.rule.ActiveRules;
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RuleFinder;
+import org.sonar.api.rules.RuleQuery;
+
+import java.util.Collection;
+
+public class RuleFinderCompatibility implements RuleFinder {
+
+  private final ActiveRules activeRules;
+
+  public RuleFinderCompatibility(ActiveRules activeRules) {
+    this.activeRules = activeRules;
+  }
+
+  @Override
+  public Rule findById(int ruleId) {
+    throw new UnsupportedOperationException("Unable to find rule by id");
+  }
+
+  @Override
+  public Rule findByKey(String repositoryKey, String key) {
+    return findByKey(RuleKey.of(repositoryKey, key));
+  }
+
+  @Override
+  public Rule findByKey(RuleKey key) {
+    ActiveRule ar = activeRules.find(key);
+    return ar == null ? null : Rule.create(key.repository(), key.rule());
+  }
+
+  @Override
+  public Rule find(RuleQuery query) {
+    throw new UnsupportedOperationException("Unable to find rule by query");
+  }
+
+  @Override
+  public Collection<Rule> findAll(RuleQuery query) {
+    throw new UnsupportedOperationException("Unable to find rule by query");
+  }
+
+}
index 5a7ae64760cc436028d30aa4987a3ec86ced19b4..af680789d8021b77592be79267c31b67d199496c 100644 (file)
@@ -26,6 +26,7 @@ import org.sonar.api.CoreProperties;
 import org.sonar.api.batch.InstantiationStrategy;
 import org.sonar.api.batch.bootstrap.ProjectDefinition;
 import org.sonar.api.batch.rule.CheckFactory;
+import org.sonar.api.checks.NoSonarFilter;
 import org.sonar.api.platform.ComponentContainer;
 import org.sonar.api.resources.Project;
 import org.sonar.api.scan.filesystem.FileExclusions;
@@ -78,6 +79,7 @@ import org.sonar.batch.rule.QProfileDecorator;
 import org.sonar.batch.rule.QProfileEventsDecorator;
 import org.sonar.batch.rule.QProfileSensor;
 import org.sonar.batch.rule.QProfileVerifier;
+import org.sonar.batch.rule.RuleFinderCompatibility;
 import org.sonar.batch.rule.RulesProfileProvider;
 import org.sonar.batch.scan.filesystem.ComponentIndexer;
 import org.sonar.batch.scan.filesystem.DefaultModuleFileSystem;
@@ -133,7 +135,8 @@ public class ModuleScanContainer extends ComponentContainer {
     if (!sensorMode) {
       add(DefaultPhaseExecutor.class);
     } else {
-      add(PreviewPhaseExecutor.class);
+      add(RuleFinderCompatibility.class,
+        PreviewPhaseExecutor.class);
     }
 
     add(
@@ -201,6 +204,7 @@ public class ModuleScanContainer extends ComponentContainer {
       IssueExclusionsLoader.class,
       EnforceIssuesFilter.class,
       IgnoreIssuesFilter.class,
+      NoSonarFilter.class,
 
       ScanPerspectives.class);
   }
index 1b1230f0a509bf845b1ccea0bea859e2514d68c7..a1f115568b64f072cf95078c900e55b90efd8c1b 100644 (file)
@@ -147,7 +147,6 @@ public class ProjectScanContainer extends ComponentContainer {
       ResourceCache.class,
       ComponentDataCache.class,
       FileHashesPersister.class,
-      DefaultUserFinder.class,
 
       // file system
       InputPathCache.class,
@@ -176,9 +175,6 @@ public class ProjectScanContainer extends ComponentContainer {
       HighlightableBuilder.class,
       SymbolizableBuilder.class,
 
-      // technical debt
-      DefaultTechnicalDebtModel.class,
-
       // Differential periods
       PeriodsDefinition.class,
 
@@ -205,10 +201,15 @@ public class ProjectScanContainer extends ComponentContainer {
       SourcePersister.class,
       ResourceKeyMigration.class,
 
+      DefaultUserFinder.class,
+
       // Rules
       new RulesProvider(),
       new DebtModelProvider(),
 
+      // technical debt
+      DefaultTechnicalDebtModel.class,
+
       ProjectLock.class);
   }
 
index 3a796c0f03a1ded18f60bab01fdc717ebb67d201..5cf7ce73f755784704658dfcfc1a125313f19f53 100644 (file)
@@ -43,6 +43,11 @@ public class MeasureCache implements BatchComponent {
     cache = caches.createCache("measures");
   }
 
+  public MeasureCache(Caches caches, MetricFinder metricFinder) {
+    caches.registerValueCoder(Measure.class, new MeasureValueCoder(metricFinder, null));
+    cache = caches.createCache("measures");
+  }
+
   public Iterable<Entry<Measure>> entries() {
     return cache.entries();
   }
index c5c967de7084697a4f8e7010492342ac4f6de98f..c094a13c9a42a3a38841724ed862b2767ea10d2f 100644 (file)
@@ -31,13 +31,13 @@ import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.InputPath;
 import org.sonar.api.batch.fs.internal.DefaultInputDir;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
+import org.sonar.api.batch.rule.ActiveRules;
+import org.sonar.api.batch.rule.internal.DefaultActiveRule;
 import org.sonar.api.config.Settings;
 import org.sonar.api.issue.internal.DefaultIssue;
 import org.sonar.api.platform.Server;
 import org.sonar.api.resources.Project;
 import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleFinder;
 import org.sonar.api.user.User;
 import org.sonar.api.user.UserFinder;
 import org.sonar.api.utils.SonarException;
@@ -55,6 +55,7 @@ import java.io.IOException;
 import java.io.OutputStreamWriter;
 import java.io.Writer;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 
@@ -70,7 +71,7 @@ public class JsonReport implements BatchComponent {
   private final Settings settings;
   private final FileSystem fileSystem;
   private final Server server;
-  private final RuleFinder ruleFinder;
+  private final ActiveRules activeRules;
   private final IssueCache issueCache;
   private final EventBus eventBus;
   private final AnalysisMode analysisMode;
@@ -78,12 +79,12 @@ public class JsonReport implements BatchComponent {
   private final InputPathCache fileCache;
   private final Project rootModule;
 
-  public JsonReport(Settings settings, FileSystem fileSystem, Server server, RuleFinder ruleFinder, IssueCache issueCache,
+  public JsonReport(Settings settings, FileSystem fileSystem, Server server, ActiveRules activeRules, IssueCache issueCache,
     EventBus eventBus, AnalysisMode analysisMode, UserFinder userFinder, Project rootModule, InputPathCache fileCache) {
     this.settings = settings;
     this.fileSystem = fileSystem;
     this.server = server;
-    this.ruleFinder = ruleFinder;
+    this.activeRules = activeRules;
     this.issueCache = issueCache;
     this.eventBus = eventBus;
     this.analysisMode = analysisMode;
@@ -92,16 +93,31 @@ public class JsonReport implements BatchComponent {
     this.fileCache = fileCache;
   }
 
+  public JsonReport(Settings settings, FileSystem fileSystem, Server server, ActiveRules activeRules, IssueCache issueCache,
+    EventBus eventBus, AnalysisMode analysisMode, Project rootModule, InputPathCache fileCache) {
+    this.settings = settings;
+    this.fileSystem = fileSystem;
+    this.server = server;
+    this.activeRules = activeRules;
+    this.issueCache = issueCache;
+    this.eventBus = eventBus;
+    this.analysisMode = analysisMode;
+    this.userFinder = null;
+    this.rootModule = rootModule;
+    this.fileCache = fileCache;
+  }
+
   public void execute() {
-    if (analysisMode.isPreview()) {
+    String exportPath = settings.getString("sonar.report.export.path");
+    if (exportPath != null && (analysisMode.isPreview() || analysisMode.isSensorMode())) {
       eventBus.fireEvent(new BatchStepEvent("JSON report", true));
-      exportResults();
+      exportResults(exportPath);
       eventBus.fireEvent(new BatchStepEvent("JSON report", false));
     }
   }
 
-  private void exportResults() {
-    File exportFile = new File(fileSystem.workDir(), settings.getString("sonar.report.export.path"));
+  private void exportResults(String exportPath) {
+    File exportFile = new File(fileSystem.workDir(), exportPath);
 
     LOG.info("Export results to " + exportFile.getAbsolutePath());
     try (Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile), Charsets.UTF_8))) {
@@ -124,7 +140,7 @@ public class JsonReport implements BatchComponent {
       writeJsonIssues(json, ruleKeys, userLogins);
       writeJsonComponents(json);
       writeJsonRules(json, ruleKeys);
-      List<User> users = userFinder.findByLogins(new ArrayList<String>(userLogins));
+      List<User> users = userFinder != null ? userFinder.findByLogins(new ArrayList<String>(userLogins)) : Collections.<User>emptyList();
       writeUsers(json, users);
       json.endObject().close();
 
@@ -235,8 +251,8 @@ public class JsonReport implements BatchComponent {
   }
 
   private String getRuleName(RuleKey ruleKey) {
-    Rule rule = ruleFinder.findByKey(ruleKey);
-    return rule != null ? rule.getName() : null;
+    DefaultActiveRule rule = (DefaultActiveRule) activeRules.find(ruleKey);
+    return rule != null ? rule.name() : null;
   }
 
   @VisibleForTesting
diff --git a/sonar-batch/src/test/java/org/sonar/batch/bootstrap/DefaultPluginsReferentialTest.java b/sonar-batch/src/test/java/org/sonar/batch/bootstrap/DefaultPluginsReferentialTest.java
new file mode 100644 (file)
index 0000000..2abff9e
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * 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.bootstrap;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.sonar.core.plugins.RemotePlugin;
+import org.sonar.home.cache.FileCache;
+
+import java.io.File;
+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.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class DefaultPluginsReferentialTest {
+
+  @Rule
+  public TemporaryFolder temp = new TemporaryFolder();
+
+  @Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  @Test
+  public void should_request_list_of_plugins() {
+    FileCache cache = mock(FileCache.class);
+    ServerClient server = mock(ServerClient.class);
+    when(server.request("/deploy/plugins/index.txt")).thenReturn("checkstyle,true\nsqale,false");
+    DefaultPluginsReferential downloader = new DefaultPluginsReferential(cache, server);
+
+    List<RemotePlugin> plugins = downloader.pluginList();
+    assertThat(plugins).hasSize(2);
+    assertThat(plugins.get(0).getKey()).isEqualTo("checkstyle");
+    assertThat(plugins.get(0).isCore()).isTrue();
+    assertThat(plugins.get(1).getKey()).isEqualTo("sqale");
+    assertThat(plugins.get(1).isCore()).isFalse();
+  }
+
+  @Test
+  public void should_download_plugin() throws Exception {
+    FileCache cache = mock(FileCache.class);
+
+    File pluginJar = temp.newFile();
+    when(cache.get(eq("checkstyle-plugin.jar"), eq("fakemd5_1"), any(FileCache.Downloader.class))).thenReturn(pluginJar);
+
+    ServerClient server = mock(ServerClient.class);
+    DefaultPluginsReferential downloader = new DefaultPluginsReferential(cache, server);
+
+    RemotePlugin plugin = new RemotePlugin("checkstyle", true)
+      .setFile("checkstyle-plugin.jar", "fakemd5_1");
+    File file = downloader.pluginFile(plugin);
+
+    assertThat(file).isEqualTo(pluginJar);
+  }
+
+  @Test
+  public void should_fail_to_get_plugin_index() throws Exception {
+    thrown.expect(IllegalStateException.class);
+
+    ServerClient server = mock(ServerClient.class);
+    doThrow(new IllegalStateException()).when(server).request("/deploy/plugins/index.txt");
+
+    new DefaultPluginsReferential(mock(FileCache.class), server).pluginList();
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/bootstrap/PluginDownloaderTest.java b/sonar-batch/src/test/java/org/sonar/batch/bootstrap/PluginDownloaderTest.java
deleted file mode 100644 (file)
index a9c8543..0000000
+++ /dev/null
@@ -1,88 +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.bootstrap;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
-import org.sonar.core.plugins.RemotePlugin;
-import org.sonar.home.cache.FileCache;
-
-import java.io.File;
-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.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class PluginDownloaderTest {
-
-  @Rule
-  public TemporaryFolder temp = new TemporaryFolder();
-
-  @Rule
-  public ExpectedException thrown = ExpectedException.none();
-
-  @Test
-  public void should_request_list_of_plugins() {
-    FileCache cache = mock(FileCache.class);
-    ServerClient server = mock(ServerClient.class);
-    when(server.request("/deploy/plugins/index.txt")).thenReturn("checkstyle,true\nsqale,false");
-    DefaultPluginsReferential downloader = new DefaultPluginsReferential(cache, server);
-
-    List<RemotePlugin> plugins = downloader.pluginList();
-    assertThat(plugins).hasSize(2);
-    assertThat(plugins.get(0).getKey()).isEqualTo("checkstyle");
-    assertThat(plugins.get(0).isCore()).isTrue();
-    assertThat(plugins.get(1).getKey()).isEqualTo("sqale");
-    assertThat(plugins.get(1).isCore()).isFalse();
-  }
-
-  @Test
-  public void should_download_plugin() throws Exception {
-    FileCache cache = mock(FileCache.class);
-
-    File pluginJar = temp.newFile();
-    when(cache.get(eq("checkstyle-plugin.jar"), eq("fakemd5_1"), any(FileCache.Downloader.class))).thenReturn(pluginJar);
-
-    ServerClient server = mock(ServerClient.class);
-    DefaultPluginsReferential downloader = new DefaultPluginsReferential(cache, server);
-
-    RemotePlugin plugin = new RemotePlugin("checkstyle", true)
-      .setFile("checkstyle-plugin.jar", "fakemd5_1");
-    File file = downloader.pluginFile(plugin);
-
-    assertThat(file).isEqualTo(pluginJar);
-  }
-
-  @Test
-  public void should_fail_to_get_plugin_index() throws Exception {
-    thrown.expect(IllegalStateException.class);
-
-    ServerClient server = mock(ServerClient.class);
-    doThrow(new IllegalStateException()).when(server).request("/deploy/plugins/index.txt");
-
-    new DefaultPluginsReferential(mock(FileCache.class), server).pluginList();
-  }
-}
index c082ce651434e218dc8aca9e6ce7df07f8b4fde9..ebb97af649278f47936bb7401a6cf85929fbfb01 100644 (file)
@@ -66,6 +66,8 @@ public class MeasureCacheTest {
 
   private TechnicalDebtModel techDebtModel;
 
+  private MeasureCache cache;
+
   @Before
   public void start() throws Exception {
     caches = CachesTest.createCacheOnTemp(temp);
@@ -73,6 +75,7 @@ public class MeasureCacheTest {
     metricFinder = mock(MetricFinder.class);
     when(metricFinder.findByKey(CoreMetrics.NCLOC_KEY)).thenReturn(CoreMetrics.NCLOC);
     techDebtModel = mock(TechnicalDebtModel.class);
+    cache = new MeasureCache(caches, metricFinder, techDebtModel);
   }
 
   @After
@@ -82,7 +85,6 @@ public class MeasureCacheTest {
 
   @Test
   public void should_add_measure() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Project p = new Project("struts");
 
     assertThat(cache.entries()).hasSize(0);
@@ -113,7 +115,6 @@ public class MeasureCacheTest {
 
   @Test
   public void should_add_measure_with_big_data() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Project p = new Project("struts");
 
     assertThat(cache.entries()).hasSize(0);
@@ -153,7 +154,6 @@ public class MeasureCacheTest {
    */
   @Test
   public void should_add_measure_with_too_big_data_for_persistit_pre_patch() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Project p = new Project("struts");
 
     assertThat(cache.entries()).hasSize(0);
@@ -189,7 +189,6 @@ public class MeasureCacheTest {
 
   @Test
   public void should_add_measure_with_too_big_data_for_persistit() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Project p = new Project("struts");
 
     assertThat(cache.entries()).hasSize(0);
@@ -212,7 +211,6 @@ public class MeasureCacheTest {
 
   @Test
   public void should_add_measure_with_same_metric() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Project p = new Project("struts");
 
     assertThat(cache.entries()).hasSize(0);
@@ -234,7 +232,6 @@ public class MeasureCacheTest {
 
   @Test
   public void should_get_measures() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Project p = new Project("struts");
     Resource dir = new Directory("foo/bar").setEffectiveKey("struts:foo/bar");
     Resource file1 = new File("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
@@ -274,7 +271,6 @@ public class MeasureCacheTest {
 
   @Test
   public void test_measure_coder() throws Exception {
-    MeasureCache cache = new MeasureCache(caches, metricFinder, techDebtModel);
     Resource file1 = new File("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
 
     Measure measure = new Measure(CoreMetrics.NCLOC, 1.786, 5);
index f815408bf48ebe28d49256904d9f4faa0486ba8d..50fdd74d274059b60307f4a72ec9ef296b88b57e 100644 (file)
@@ -32,6 +32,8 @@ import org.sonar.api.batch.fs.InputPath;
 import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 import org.sonar.api.batch.fs.internal.DefaultInputDir;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
+import org.sonar.api.batch.rule.ActiveRules;
+import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
 import org.sonar.api.config.Settings;
 import org.sonar.api.issue.Issue;
 import org.sonar.api.issue.internal.DefaultIssue;
@@ -39,8 +41,6 @@ import org.sonar.api.platform.Server;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleFinder;
 import org.sonar.api.user.User;
 import org.sonar.api.user.UserFinder;
 import org.sonar.batch.bootstrap.AnalysisMode;
@@ -73,7 +73,7 @@ public class JsonReportTest {
   Resource resource = mock(Resource.class);
   DefaultFileSystem fs = new DefaultFileSystem();
   Server server = mock(Server.class);
-  RuleFinder ruleFinder = mock(RuleFinder.class);
+  ActiveRules activeRules = mock(ActiveRules.class);
   Settings settings = new Settings();
   IssueCache issueCache = mock(IssueCache.class);
   private UserFinder userFinder;
@@ -96,7 +96,10 @@ public class JsonReportTest {
     moduleA.setParent(rootModule).setPath("core");
     Project moduleB = new Project("struts-ui");
     moduleB.setParent(rootModule).setPath("ui");
-    jsonReport = new JsonReport(settings, fs, server, ruleFinder, issueCache, mock(EventBus.class),
+    activeRules = new ActiveRulesBuilder()
+      .create(RuleKey.of("squid", "AvoidCycles")).setName("Avoid Cycles").activate()
+      .build();
+    jsonReport = new JsonReport(settings, fs, server, activeRules, issueCache, mock(EventBus.class),
       mode, userFinder, rootModule, fileCache);
   }
 
@@ -117,7 +120,6 @@ public class JsonReportTest {
       .setCreationDate(SIMPLE_DATE_FORMAT.parse("2013-04-24"))
       .setUpdateDate(SIMPLE_DATE_FORMAT.parse("2013-04-25"))
       .setNew(false);
-    when(ruleFinder.findByKey(RuleKey.of("squid", "AvoidCycles"))).thenReturn(new Rule().setName("Avoid Cycles"));
     when(jsonReport.getIssues()).thenReturn(Lists.newArrayList(issue));
     DefaultUser user1 = new DefaultUser().setLogin("julien").setName("Julien");
     DefaultUser user2 = new DefaultUser().setLogin("simon").setName("Simon");
@@ -143,7 +145,6 @@ public class JsonReportTest {
       .setUpdateDate(SIMPLE_DATE_FORMAT.parse("2013-04-25"))
       .setCloseDate(SIMPLE_DATE_FORMAT.parse("2013-04-26"))
       .setNew(false);
-    when(ruleFinder.findByKey(ruleKey)).thenReturn(Rule.create(ruleKey.repository(), ruleKey.rule()).setName("Avoid Cycles"));
     when(jsonReport.getIssues()).thenReturn(Lists.newArrayList(issue));
 
     StringWriter writer = new StringWriter();
@@ -169,8 +170,6 @@ public class JsonReportTest {
     File workDir = temporaryFolder.newFolder("sonar");
     fs.setWorkDir(workDir);
 
-    Rule rule = Rule.create("squid", "AvoidCycles").setName("Avoid Cycles");
-    when(ruleFinder.findByKey(RuleKey.of("squid", "AvoidCycles"))).thenReturn(rule);
     when(jsonReport.getIssues()).thenReturn(Collections.<DefaultIssue>emptyList());
 
     settings.setProperty("sonar.report.export.path", "output.json");