]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-3895 allow to exclude plugins during dry run mode
authorSimon Brandhof <simon.brandhof@gmail.com>
Tue, 6 Nov 2012 17:43:55 +0000 (18:43 +0100)
committerSimon Brandhof <simon.brandhof@gmail.com>
Tue, 6 Nov 2012 17:44:07 +0000 (18:44 +0100)
48 files changed:
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/batch/IndexProjectPostJob.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/security/ApplyProjectRolesDecorator.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/sensors/ReviewWorkflowDecorator.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/sensors/VersionEventsSensor.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/AbstractNewCoverageFileAnalyzer.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/TendencyDecorator.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/TimeMachineConfigurationPersister.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/ViolationPersisterDecorator.java
plugins/sonar-dbcleaner-plugin/src/main/java/org/sonar/plugins/dbcleaner/ProjectPurgePostJob.java
sonar-batch/src/main/java/org/sonar/batch/ServerMetadata.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchDatabase.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchModule.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchPluginRepository.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BatchSettings.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BootstrapModule.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/BootstrapSettings.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/DatabaseCompatibility.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/DryRun.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/bootstrap/DryRunDatabase.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/bootstrap/ExtensionUtils.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/JdbcDriverHolder.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/ServerClient.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/ServerMetadata.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/local/DryRunExporter.java
sonar-batch/src/main/java/org/sonar/batch/phases/UpdateStatusJob.java
sonar-batch/src/test/java/org/sonar/batch/ServerMetadataTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/BatchDatabaseTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/BatchPluginRepositoryTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/BatchSettingsTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/BootstrapSettingsTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/DatabaseCompatibilityTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/DryRunDatabaseTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/bootstrap/DryRunTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/bootstrap/ExtensionUtilsTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/JdbcDriverHolderTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/ServerClientTest.java
sonar-batch/src/test/java/org/sonar/batch/bootstrap/ServerMetadataTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/local/DryRunDatabaseTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/local/DryRunExporterTest.java
sonar-batch/src/test/java/org/sonar/batch/phases/UpdateStatusJobTest.java
sonar-core/src/main/java/org/sonar/core/DryRunIncompatible.java [new file with mode: 0644]
sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/DryRunIncompatible.java [deleted file]
sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java
sonar-server/src/main/webapp/WEB-INF/app/controllers/batch_bootstrap_controller.rb
sonar-ws-client/src/main/java/org/sonar/wsclient/connectors/HttpClient4Connector.java

index 5512d60ecd255d9f2fbfb21737b1b80223f248bf..1713209d4ea96ae26a775e5cf466b9d1e5076982 100644 (file)
@@ -323,6 +323,8 @@ import java.util.List;
     global = false,
     defaultValue = CoreProperties.TIMEMACHINE_DEFAULT_PERIOD_5,
     category = CoreProperties.CATEGORY_DIFFERENTIAL_VIEWS),
+  @Property(key = CoreProperties.DRY_RUN, defaultValue = "false", name = "Dry Run", type = PropertyType.BOOLEAN, global = false, project = false),
+  @Property(key = "sonar.dryRun.export.path", defaultValue = "dryRun.json", name = "Dry Run Results Export File", type = PropertyType.STRING, global = false, project = false),
 
   // SERVER-SIDE TECHNICAL PROPERTIES
 
@@ -367,116 +369,116 @@ public final class CorePlugin extends SonarPlugin {
   @SuppressWarnings("unchecked")
   public List getExtensions() {
     return ImmutableList.of(
-        DefaultResourceTypes.class,
-        UserManagedMetrics.class,
-        ProjectFileSystemLogger.class,
-        DatabaseSemaphoreImpl.class,
+      DefaultResourceTypes.class,
+      UserManagedMetrics.class,
+      ProjectFileSystemLogger.class,
+      DatabaseSemaphoreImpl.class,
 
-        // maven
-        MavenInitializer.class,
+      // maven
+      MavenInitializer.class,
 
-        // languages
-        Java.class,
+      // languages
+      Java.class,
 
-        // pages
-        TestsViewerDefinition.class,
-        Lcom4Viewer.class,
+      // pages
+      TestsViewerDefinition.class,
+      Lcom4Viewer.class,
 
-        // filters
-        ProjectFilter.class,
-        TreeMapFilter.class,
-        MyFavouritesFilter.class,
+      // filters
+      ProjectFilter.class,
+      TreeMapFilter.class,
+      MyFavouritesFilter.class,
 
-        // widgets
-        AlertsWidget.class,
-        CoverageWidget.class,
-        ItCoverageWidget.class,
-        CommentsDuplicationsWidget.class,
-        DescriptionWidget.class,
-        ComplexityWidget.class,
-        RulesWidget.class,
-        SizeWidget.class,
-        EventsWidget.class,
-        CustomMeasuresWidget.class,
-        TimelineWidget.class,
-        TimeMachineWidget.class,
-        HotspotMetricWidget.class,
-        HotspotMostViolatedResourcesWidget.class,
-        HotspotMostViolatedRulesWidget.class,
-        MyReviewsWidget.class,
-        ProjectReviewsWidget.class,
-        FalsePositiveReviewsWidget.class,
-        ReviewsPerDeveloperWidget.class,
-        PlannedReviewsWidget.class,
-        UnplannedReviewsWidget.class,
-        ActionPlansWidget.class,
-        ReviewsMetricsWidget.class,
-        TreemapWidget.class,
-        FilterWidget.class,
+      // widgets
+      AlertsWidget.class,
+      CoverageWidget.class,
+      ItCoverageWidget.class,
+      CommentsDuplicationsWidget.class,
+      DescriptionWidget.class,
+      ComplexityWidget.class,
+      RulesWidget.class,
+      SizeWidget.class,
+      EventsWidget.class,
+      CustomMeasuresWidget.class,
+      TimelineWidget.class,
+      TimeMachineWidget.class,
+      HotspotMetricWidget.class,
+      HotspotMostViolatedResourcesWidget.class,
+      HotspotMostViolatedRulesWidget.class,
+      MyReviewsWidget.class,
+      ProjectReviewsWidget.class,
+      FalsePositiveReviewsWidget.class,
+      ReviewsPerDeveloperWidget.class,
+      PlannedReviewsWidget.class,
+      UnplannedReviewsWidget.class,
+      ActionPlansWidget.class,
+      ReviewsMetricsWidget.class,
+      TreemapWidget.class,
+      FilterWidget.class,
 
-        // dashboards
-        DefaultDashboard.class,
-        HotspotsDashboard.class,
-        ReviewsDashboard.class,
-        TimeMachineDashboard.class,
-        ProjectsDashboard.class,
-        TreemapDashboard.class,
-        MyFavouritesDashboard.class,
+      // dashboards
+      DefaultDashboard.class,
+      HotspotsDashboard.class,
+      ReviewsDashboard.class,
+      TimeMachineDashboard.class,
+      ProjectsDashboard.class,
+      TreemapDashboard.class,
+      MyFavouritesDashboard.class,
 
-        // chart
-        XradarChart.class,
-        DistributionBarChart.class,
-        DistributionAreaChart.class,
+      // chart
+      XradarChart.class,
+      DistributionBarChart.class,
+      DistributionAreaChart.class,
 
-        // colorizers
-        JavaColorizerFormat.class,
+      // colorizers
+      JavaColorizerFormat.class,
 
-        // batch
-        ProfileSensor.class,
-        ProfileEventsSensor.class,
-        ProjectLinksSensor.class,
-        UnitTestDecorator.class,
-        VersionEventsSensor.class,
-        CheckAlertThresholds.class,
-        GenerateAlertEvents.class,
-        ViolationsDecorator.class,
-        WeightedViolationsDecorator.class,
-        ViolationsDensityDecorator.class,
-        LineCoverageDecorator.class,
-        CoverageDecorator.class,
-        BranchCoverageDecorator.class,
-        ItLineCoverageDecorator.class,
-        ItCoverageDecorator.class,
-        ItBranchCoverageDecorator.class,
-        OverallLineCoverageDecorator.class,
-        OverallCoverageDecorator.class,
-        OverallBranchCoverageDecorator.class,
-        DefaultResourcePermissions.class,
-        ApplyProjectRolesDecorator.class,
-        ExcludedResourceFilter.class,
-        CommentDensityDecorator.class,
-        NoSonarFilter.class,
-        DirectoriesDecorator.class,
-        FilesDecorator.class,
-        ReviewNotifications.class,
-        ReviewWorkflowDecorator.class,
-        ReferenceAnalysis.class,
-        ManualMeasureDecorator.class,
-        ManualViolationInjector.class,
-        ViolationSeverityUpdater.class,
-        IndexProjectPostJob.class,
-        ReviewsMeasuresDecorator.class,
+      // batch
+      ProfileSensor.class,
+      ProfileEventsSensor.class,
+      ProjectLinksSensor.class,
+      UnitTestDecorator.class,
+      VersionEventsSensor.class,
+      CheckAlertThresholds.class,
+      GenerateAlertEvents.class,
+      ViolationsDecorator.class,
+      WeightedViolationsDecorator.class,
+      ViolationsDensityDecorator.class,
+      LineCoverageDecorator.class,
+      CoverageDecorator.class,
+      BranchCoverageDecorator.class,
+      ItLineCoverageDecorator.class,
+      ItCoverageDecorator.class,
+      ItBranchCoverageDecorator.class,
+      OverallLineCoverageDecorator.class,
+      OverallCoverageDecorator.class,
+      OverallBranchCoverageDecorator.class,
+      DefaultResourcePermissions.class,
+      ApplyProjectRolesDecorator.class,
+      ExcludedResourceFilter.class,
+      CommentDensityDecorator.class,
+      NoSonarFilter.class,
+      DirectoriesDecorator.class,
+      FilesDecorator.class,
+      ReviewNotifications.class,
+      ReviewWorkflowDecorator.class,
+      ReferenceAnalysis.class,
+      ManualMeasureDecorator.class,
+      ManualViolationInjector.class,
+      ViolationSeverityUpdater.class,
+      IndexProjectPostJob.class,
+      ReviewsMeasuresDecorator.class,
 
-        // time machine
-        TendencyDecorator.class,
-        VariationDecorator.class,
-        ViolationTrackingDecorator.class,
-        ViolationPersisterDecorator.class,
-        NewViolationsDecorator.class,
-        TimeMachineConfigurationPersister.class,
-        NewCoverageFileAnalyzer.class,
-        NewItCoverageFileAnalyzer.class,
-        NewOverallCoverageFileAnalyzer.class,
-        NewCoverageAggregator.class);
+      // time machine
+      TendencyDecorator.class,
+      VariationDecorator.class,
+      ViolationTrackingDecorator.class,
+      ViolationPersisterDecorator.class,
+      NewViolationsDecorator.class,
+      TimeMachineConfigurationPersister.class,
+      NewCoverageFileAnalyzer.class,
+      NewItCoverageFileAnalyzer.class,
+      NewOverallCoverageFileAnalyzer.class,
+      NewCoverageAggregator.class);
   }
 }
index 9e9c79948e0fa6614436b939e03b54c4967db6aa..9ce6070eba458e32c6bd0dd5570f152e2b1c9327 100644 (file)
@@ -19,7 +19,7 @@
  */
 package org.sonar.plugins.core.batch;
 
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.batch.PostJob;
 import org.sonar.api.batch.SensorContext;
 import org.sonar.api.resources.Project;
index d2a4e7b3f81b431c1d4e54e5b58a15b43faa2b3d..2742ce00a7054c57b7aab486aab5bd2f67a3c925 100644 (file)
@@ -23,7 +23,7 @@ import com.google.common.collect.ImmutableSet;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.batch.Decorator;
 import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.resources.Resource;
index 16f4a37bdbcca250e3921c87c6e178705266c7fe..ae26ca6d7d4200a5900cf8e0962fee0ca721d6fb 100644 (file)
@@ -34,6 +34,7 @@ import org.sonar.api.resources.ResourceUtils;
 import org.sonar.api.rules.Violation;
 import org.sonar.api.violations.ViolationQuery;
 import org.sonar.batch.index.ResourcePersister;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.core.review.ReviewDao;
 import org.sonar.core.review.ReviewDto;
 
index dabbbb682dcee17faca63e04ea35e2e8c0fe3abd..2085c374c72a13915ff5a1deffbbefcb5eecf9ba 100644 (file)
@@ -20,7 +20,7 @@
 package org.sonar.plugins.core.sensors;
 
 import org.apache.commons.lang.StringUtils;
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.batch.Event;
 import org.sonar.api.batch.Sensor;
 import org.sonar.api.batch.SensorContext;
index d007f5fa8cdd7561df535a2eef5e8c68006c9c7f..14a1f4198fe2693058c0e37c2647521d02305a14 100644 (file)
@@ -33,6 +33,7 @@ import org.sonar.api.resources.Scopes;
 import org.sonar.api.utils.KeyValueFormat;
 import org.sonar.batch.components.PastSnapshot;
 import org.sonar.batch.components.TimeMachineConfiguration;
+import org.sonar.core.DryRunIncompatible;
 
 import java.util.Arrays;
 import java.util.Date;
index e5046a5f2f10fb801ee668e148f5b9496e2a66cc..b189505eb50887db3905ceff82a04575df8d13f2 100644 (file)
@@ -32,6 +32,7 @@ import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.resources.Scopes;
 import org.sonar.batch.components.TimeMachineConfiguration;
+import org.sonar.core.DryRunIncompatible;
 
 import java.util.List;
 
index 77b3d874175b37e4c1e95fc2321ff0c3a3b02e84..54165af632ff75dff0a1deb73dd588f6b9400d17 100644 (file)
@@ -21,7 +21,7 @@ package org.sonar.plugins.core.timemachine;
 
 import org.sonar.api.batch.Decorator;
 import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.resources.Project;
index f4801867d279d94c7036dc4d0b543b54e4d7f29f..54dbe64fefc2d25c0cbf5a6fcb4b4a538e6ce8c7 100644 (file)
@@ -30,6 +30,7 @@ import org.sonar.api.rules.RuleFinder;
 import org.sonar.api.rules.Violation;
 import org.sonar.api.violations.ViolationQuery;
 import org.sonar.batch.index.ResourcePersister;
+import org.sonar.core.DryRunIncompatible;
 
 import java.util.List;
 
index c092927f4bcf87b843cdf6791110c13a5e40ea6a..530a629b462b6b8ca9ba11c1bac56396c1ac1a00 100644 (file)
@@ -19,7 +19,7 @@
  */
 package org.sonar.plugins.dbcleaner;
 
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.batch.PostJob;
 import org.sonar.api.batch.SensorContext;
 import org.sonar.api.resources.Project;
index 5bba17f69055041085d1260b4f006f7917a80f5f..769ef13e95b78ba5be0ebc561d640ab23d7bdc1c 100644 (file)
 package org.sonar.batch;
 
 import org.sonar.api.BatchComponent;
-import org.sonar.api.platform.Server;
-import org.sonar.batch.bootstrap.ServerClient;
 
 import java.util.Date;
 
 /**
- * @deprecated replaced by ServerClient since version 3.4. Plugins should use org.sonar.api.platform.Server
+ * @deprecated replaced by org.sonar.batch.bootstrap.ServerMetadata since version 3.4. Plugins should use org.sonar.api.platform.Server.
  */
 @Deprecated
-public class ServerMetadata extends Server implements BatchComponent {
-  private ServerClient server;
+public class ServerMetadata implements BatchComponent {
+  private org.sonar.batch.bootstrap.ServerMetadata metadata;
 
-  public ServerMetadata(ServerClient server) {
-    this.server = server;
+  public ServerMetadata(org.sonar.batch.bootstrap.ServerMetadata metadata) {
+    this.metadata = metadata;
   }
 
-  @Override
   public String getId() {
-    return server.getId();
+    return metadata.getId();
   }
 
-  @Override
   public String getVersion() {
-    return server.getVersion();
+    return metadata.getVersion();
   }
 
-  @Override
   public Date getStartedAt() {
-    return server.getStartedAt();
+    return metadata.getStartedAt();
   }
 
-  /**
-   * @return the server URL when executed from batch, else null.
-   * @since 2.4
-   */
-  @Override
   public String getURL() {
-    return server.getURL();
+    return metadata.getURL();
   }
 
-  /**
-   * @since 2.10
-   */
-  @Override
   public String getPermanentServerId() {
-    return server.getPermanentServerId();
+    return metadata.getPermanentServerId();
   }
 }
index 9171f213788849b9343a19c5a1f63c29e731f3d0..4d64d5523c65faaa0adccec3cd5ac5ce69507b6d 100644 (file)
@@ -20,7 +20,6 @@
 package org.sonar.batch.bootstrap;
 
 import org.sonar.api.config.Settings;
-import org.sonar.batch.local.DryRunDatabase;
 import org.sonar.core.persistence.DefaultDatabase;
 
 import java.util.Properties;
index 85901d68b746d5ae646db51439aa50c02ddfa40c..4974e73cb1e5d898c6be81922a418035f61e0b22 100644 (file)
@@ -43,7 +43,6 @@ import org.sonar.batch.index.LinkPersister;
 import org.sonar.batch.index.MeasurePersister;
 import org.sonar.batch.index.MemoryOptimizer;
 import org.sonar.batch.index.SourcePersister;
-import org.sonar.batch.local.DryRunDatabase;
 import org.sonar.core.i18n.I18nManager;
 import org.sonar.core.i18n.RuleI18nManager;
 import org.sonar.core.metric.CacheMetricFinder;
@@ -70,7 +69,6 @@ public class BatchModule extends Module {
   }
 
   private void registerCoreComponents() {
-    container.addSingleton(BatchSettings.class);
     container.addSingleton(EmailSettings.class);
     container.addSingleton(I18nManager.class);
     container.addSingleton(RuleI18nManager.class);
index 2adca6754bb08d8c9f31ef6709a67b9008f7d27f..8f40cd8d07e423374b4dd7e8d7411ec871c33d4b 100644 (file)
@@ -50,20 +50,12 @@ public class BatchPluginRepository implements PluginRepository {
   private PluginDownloader pluginDownloader;
   private Map<String, Plugin> pluginsByKey;
   private Map<String, PluginMetadata> metadataByKey;
-  private Set<String> whiteList = null;
-  private Set<String> blackList = null;
+  private Settings settings;
   private PluginClassloaders classLoaders;
 
   public BatchPluginRepository(PluginDownloader pluginDownloader, Settings settings) {
     this.pluginDownloader = pluginDownloader;
-    if (settings.hasKey(CoreProperties.BATCH_INCLUDE_PLUGINS)) {
-      whiteList = Sets.newTreeSet(Arrays.asList(settings.getStringArray(CoreProperties.BATCH_INCLUDE_PLUGINS)));
-      LOG.info("Include plugins: " + Joiner.on(", ").join(whiteList));
-    }
-    if (settings.hasKey(CoreProperties.BATCH_EXCLUDE_PLUGINS)) {
-      blackList = Sets.newTreeSet(Arrays.asList(settings.getStringArray(CoreProperties.BATCH_EXCLUDE_PLUGINS)));
-      LOG.info("Exclude plugins: " + Joiner.on(", ").join(blackList));
-    }
+    this.settings = settings;
   }
 
   public void start() {
@@ -72,14 +64,17 @@ public class BatchPluginRepository implements PluginRepository {
   }
 
   void doStart(List<RemotePlugin> remotePlugins) {
+    Set<String> whiteList = initWhiteList();
+    Set<String> blackList = initBlackList();
+
     PluginInstaller extractor = new PluginInstaller();
     metadataByKey = Maps.newHashMap();
     for (RemotePlugin remote : remotePlugins) {
-      if (isAccepted(remote.getKey())) {
+      if (isAccepted(remote.getKey(), whiteList, blackList)) {
         List<File> pluginFiles = pluginDownloader.downloadPlugin(remote);
         List<File> extensionFiles = pluginFiles.subList(1, pluginFiles.size());
         PluginMetadata metadata = extractor.installInSameLocation(pluginFiles.get(0), remote.isCore(), extensionFiles);
-        if (StringUtils.isBlank(metadata.getBasePlugin()) || isAccepted(metadata.getBasePlugin())) {
+        if (StringUtils.isBlank(metadata.getBasePlugin()) || isAccepted(metadata.getBasePlugin(), whiteList, blackList)) {
           LOG.debug("Excluded plugin: " + metadata.getKey());
           metadataByKey.put(metadata.getKey(), metadata);
         }
@@ -89,6 +84,24 @@ public class BatchPluginRepository implements PluginRepository {
     pluginsByKey = classLoaders.init(metadataByKey.values());
   }
 
+  private Set<String> initBlackList() {
+    Set<String> blackList = null;
+    if (settings.hasKey(CoreProperties.BATCH_EXCLUDE_PLUGINS)) {
+      blackList = Sets.newTreeSet(Arrays.asList(settings.getStringArray(CoreProperties.BATCH_EXCLUDE_PLUGINS)));
+      LOG.info("Exclude plugins: " + Joiner.on(", ").join(blackList));
+    }
+    return blackList;
+  }
+
+  private Set<String> initWhiteList() {
+    Set<String> whiteList = null;
+    if (settings.hasKey(CoreProperties.BATCH_INCLUDE_PLUGINS)) {
+      whiteList = Sets.newTreeSet(Arrays.asList(settings.getStringArray(CoreProperties.BATCH_INCLUDE_PLUGINS)));
+      LOG.info("Include plugins: " + Joiner.on(", ").join(whiteList));
+    }
+    return whiteList;
+  }
+
   public void stop() {
     if (classLoaders != null) {
       classLoaders.clean();
@@ -108,7 +121,7 @@ public class BatchPluginRepository implements PluginRepository {
     return metadataByKey.get(pluginKey);
   }
 
-  boolean isAccepted(String pluginKey) {
+  static boolean isAccepted(String pluginKey, Set<String> whiteList, Set<String> blackList) {
     if (CORE_PLUGIN.equals(pluginKey) || ENGLISH_PACK_PLUGIN.equals(pluginKey)) {
       return true;
     }
index f620b6d0e7bf78db236aeb92e205b16395f003db..a637b45659c37aa991586a28dbdfe95d4fc0e6ac 100644 (file)
@@ -26,6 +26,7 @@ import org.json.simple.JSONValue;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.CoreProperties;
 import org.sonar.api.batch.bootstrap.ProjectReactor;
+import org.sonar.api.config.PropertyDefinitions;
 import org.sonar.api.config.Settings;
 
 import javax.annotation.Nullable;
@@ -40,9 +41,9 @@ public class BatchSettings extends Settings {
   // module key -> <key,val>
   private Map<String, Map<String, String>> moduleProperties = Maps.newHashMap();
 
-  public BatchSettings(BootstrapSettings bootstrapSettings, ProjectReactor reactor, ServerClient client,
-                       Configuration deprecatedConfiguration) {
-    super(bootstrapSettings.getDefinitions());
+  public BatchSettings(BootstrapSettings bootstrapSettings, PropertyDefinitions propertyDefinitions, ProjectReactor reactor,
+                       ServerClient client, Configuration deprecatedConfiguration) {
+    super(propertyDefinitions);
     this.deprecatedConfiguration = deprecatedConfiguration;
     init(bootstrapSettings, reactor, client);
   }
@@ -50,7 +51,7 @@ public class BatchSettings extends Settings {
   private void init(BootstrapSettings bootstrapSettings, ProjectReactor reactor, ServerClient client) {
     LoggerFactory.getLogger(BatchSettings.class).info("Load project settings");
 
-    String branch = bootstrapSettings.getString(CoreProperties.PROJECT_BRANCH_PROPERTY);
+    String branch = bootstrapSettings.getProperty(CoreProperties.PROJECT_BRANCH_PROPERTY);
     String projectKey = reactor.getRoot().getKey();
     if (StringUtils.isNotBlank(branch)) {
       projectKey = String.format("%s:%s", projectKey, branch);
index 31d7fcb58462e94b0bdb859f7f5c748eec4a7074..ee8b60c2058ba18233e489a63ccd235d0bab8a02 100644 (file)
@@ -25,7 +25,6 @@ import org.sonar.api.utils.HttpDownloader;
 import org.sonar.api.utils.UriReader;
 import org.sonar.batch.FakeMavenPluginExecutor;
 import org.sonar.batch.MavenPluginExecutor;
-import org.sonar.batch.ServerMetadata;
 import org.sonar.core.config.Logback;
 
 /**
@@ -46,12 +45,13 @@ public class BootstrapModule extends Module {
     container.addSingleton(reactor);
     container.addSingleton(new PropertiesConfiguration());
     container.addSingleton(BootstrapSettings.class);
+    container.addSingleton(ServerClient.class);
+    container.addSingleton(BatchSettings.class);
     container.addSingleton(BatchPluginRepository.class);
     container.addSingleton(ExtensionInstaller.class);
-    container.addSingleton(DryRun.class);
     container.addSingleton(Logback.class);
-    container.addSingleton(ServerClient.class);
     container.addSingleton(ServerMetadata.class);
+    container.addSingleton(org.sonar.batch.ServerMetadata.class);
     container.addSingleton(TempDirectories.class);
     container.addSingleton(HttpDownloader.class);
     container.addSingleton(UriReader.class);
index ccd87b921766a7817ca7a52913a588ae50614782..b09b33bddca01c1274a0a998519d499b1974e21e 100644 (file)
  */
 package org.sonar.batch.bootstrap;
 
-import org.apache.commons.configuration.Configuration;
+import com.google.common.collect.Maps;
+import org.codehaus.plexus.util.StringUtils;
 import org.sonar.api.batch.bootstrap.ProjectReactor;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.Settings;
 
-import javax.annotation.Nullable;
+import java.util.Map;
+import java.util.Properties;
 
 /**
  * @since 2.12
  */
-public class BootstrapSettings extends Settings {
-  private Configuration deprecatedConfiguration;
-  private ProjectReactor reactor;
+public class BootstrapSettings {
+  private Map<String, String> properties;
 
-  public BootstrapSettings(PropertyDefinitions propertyDefinitions, ProjectReactor reactor, Configuration deprecatedConfiguration) {
-    super(propertyDefinitions);
-    this.reactor = reactor;
-    this.deprecatedConfiguration = deprecatedConfiguration;
-    init();
+  public BootstrapSettings(ProjectReactor reactor) {
+    init(reactor);
   }
 
-  private void init() {
+  private void init(ProjectReactor reactor) {
+    properties = Maps.newHashMap();
+
     // order is important -> bottom-up. The last one overrides all the others.
     addProperties(reactor.getRoot().getProperties());
-    addEnvironmentVariables();
-    addSystemProperties();
+    properties.putAll(System.getenv());
+    addProperties(System.getProperties());
+  }
+
+  private void addProperties(Properties p) {
+    for (Map.Entry<Object, Object> entry : p.entrySet()) {
+      if (entry.getValue() != null) {
+        properties.put(entry.getKey().toString(), entry.getValue().toString());
+      }
+    }
   }
 
-  @Override
-  protected void doOnSetProperty(String key, @Nullable String value) {
-    deprecatedConfiguration.setProperty(key, value);
+  public Map<String, String> getProperties() {
+    return properties;
   }
 
-  @Override
-  protected void doOnRemoveProperty(String key) {
-    deprecatedConfiguration.clearProperty(key);
+  public String getProperty(String key) {
+    return properties.get(key);
   }
 
-  @Override
-  protected void doOnClearProperties() {
-    deprecatedConfiguration.clear();
+  public String getProperty(String key, String defaultValue) {
+    return StringUtils.defaultString(properties.get(key), defaultValue);
   }
 }
index 3d1c06ec5799cb5659039a5c05025f998db10540..d1b0e6ee75313c515b5c8202958894fddc9d675a 100644 (file)
@@ -33,9 +33,9 @@ public class DatabaseCompatibility implements BatchComponent {
 
   private DatabaseVersion version;
   private Settings settings;
-  private ServerClient server;
+  private ServerMetadata server;
 
-  public DatabaseCompatibility(DatabaseVersion version, ServerClient server, Settings settings) {
+  public DatabaseCompatibility(DatabaseVersion version, ServerMetadata server, Settings settings) {
     this.version = version;
     this.server = server;
     this.settings = settings;
diff --git a/sonar-batch/src/main/java/org/sonar/batch/bootstrap/DryRun.java b/sonar-batch/src/main/java/org/sonar/batch/bootstrap/DryRun.java
deleted file mode 100644 (file)
index 531f2c7..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2012 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar 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.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
- */
-package org.sonar.batch.bootstrap;
-
-import org.slf4j.LoggerFactory;
-import org.sonar.api.BatchComponent;
-import org.sonar.api.Properties;
-import org.sonar.api.Property;
-import org.sonar.api.PropertyType;
-import org.sonar.api.config.Settings;
-
-@Properties({
-  @Property(key = "sonar.dryRun", defaultValue = "false", name = "Dry Run", type = PropertyType.BOOLEAN, global = false, project = false),
-  @Property(key = "sonar.dryRun.export.path", defaultValue = "dryRun.json", name = "Dry Run Results Export File", type = PropertyType.STRING, global = false, project = false)
-})
-public class DryRun implements BatchComponent {
-  private Settings settings;
-
-  public DryRun(Settings settings) {
-    this.settings = settings;
-  }
-
-  public boolean isEnabled() {
-    return settings.getBoolean("sonar.dryRun");
-  }
-
-  public String getExportPath() {
-    return settings.getString("sonar.dryRun.export.path");
-  }
-
-  public void start() {
-    if (isEnabled()) {
-      LoggerFactory.getLogger(DryRun.class).info("Dry run");
-    }
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/bootstrap/DryRunDatabase.java b/sonar-batch/src/main/java/org/sonar/batch/bootstrap/DryRunDatabase.java
new file mode 100644 (file)
index 0000000..b281dd0
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.batch.bootstrap;
+
+import com.google.common.base.Throwables;
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.BatchComponent;
+import org.sonar.api.batch.bootstrap.ProjectReactor;
+import org.sonar.api.config.Settings;
+import org.sonar.api.database.DatabaseProperties;
+import org.sonar.api.utils.SonarException;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+/**
+ * @since 3.4
+ */
+public class DryRunDatabase implements BatchComponent {
+  private static final Logger LOG = LoggerFactory.getLogger(DryRunDatabase.class);
+
+  private static final String DIALECT = "h2";
+  private static final String DRIVER = "org.h2.Driver";
+  private static final String URL = "jdbc:h2:";
+  private static final String USER = "sonar";
+  private static final String PASSWORD = "sonar";
+
+  private final Settings settings;
+  private final ServerClient server;
+  private final TempDirectories tempDirectories;
+  private final ProjectReactor reactor;
+
+  public DryRunDatabase(Settings settings, ServerClient server, TempDirectories tempDirectories, ProjectReactor reactor,
+                        // project reactor must be completely built
+                        ProjectReactorReady reactorReady) {
+    this.settings = settings;
+    this.server = server;
+    this.tempDirectories = tempDirectories;
+    this.reactor = reactor;
+  }
+
+  public void start() {
+    if (settings.getBoolean("sonar.dryRun")) {
+      LOG.info("Dry run");
+      File databaseFile = tempDirectories.getFile("dry_run", "db.h2.db");
+      downloadDatabase(reactor.getRoot().getKey(), databaseFile);
+
+      String databasePath = StringUtils.removeEnd(databaseFile.getAbsolutePath(), ".h2.db");
+      replaceSettings(databasePath);
+    }
+  }
+
+  private void downloadDatabase(String projectKey, File toFile) {
+    try {
+      server.download("/batch_bootstrap/db?project=" + projectKey, toFile);
+    } catch (SonarException e) {
+      Throwable rootCause = Throwables.getRootCause(e);
+      if (rootCause instanceof FileNotFoundException) {
+        throw new SonarException(String.format("Project [%s] doesn't exist on server", projectKey), e);
+      } else if ((rootCause instanceof IOException) && (StringUtils.contains(rootCause.getMessage(), "401"))) {
+        throw new SonarException(String.format("You don't have access rights to project [%s]", projectKey), e);
+      }
+      throw e;
+    }
+  }
+
+  private void replaceSettings(String databasePath) {
+    settings
+      .removeProperty("sonar.jdbc.schema")
+      .setProperty(DatabaseProperties.PROP_DIALECT, DIALECT)
+      .setProperty(DatabaseProperties.PROP_DRIVER, DRIVER)
+      .setProperty(DatabaseProperties.PROP_USER, USER)
+      .setProperty(DatabaseProperties.PROP_PASSWORD, PASSWORD)
+      .setProperty(DatabaseProperties.PROP_URL, URL + databasePath);
+  }
+}
index 1c850db0212711fde3b0a03c509a1d573e32cf24..65d50ae8c41d993149588074bc2d4ec500b3a4ef 100644 (file)
@@ -22,7 +22,7 @@ package org.sonar.batch.bootstrap;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.BatchExtension;
 import org.sonar.api.Extension;
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.batch.InstantiationStrategy;
 import org.sonar.api.batch.SupportedEnvironment;
 import org.sonar.api.utils.AnnotationUtils;
index 3b8142654210053afac7dbdd0208cac8152e3cdc..74c091e4de33cbde25a87642b07d7d45647e3da9 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.batch.bootstrap;
 import com.google.common.annotations.VisibleForTesting;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.sonar.api.config.Settings;
 import org.sonar.api.utils.SonarException;
 
 import java.io.File;
@@ -41,19 +42,19 @@ public class JdbcDriverHolder {
 
   private TempDirectories tempDirectories;
   private ServerClient serverClient;
+  private Settings settings;
 
   // initialized in start()
   private JdbcDriverClassLoader classLoader = null;
-  private DryRun dryRun;
 
-  public JdbcDriverHolder(DryRun dryRun, TempDirectories tempDirectories, ServerClient serverClient) {
+  public JdbcDriverHolder(Settings settings, TempDirectories tempDirectories, ServerClient serverClient) {
     this.tempDirectories = tempDirectories;
     this.serverClient = serverClient;
-    this.dryRun = dryRun;
+    this.settings = settings;
   }
 
   public void start() {
-    if (!dryRun.isEnabled()) {
+    if (!settings.getBoolean("sonar.dryRun")) {
       LOG.info("Install JDBC driver");
       File jdbcDriver = new File(tempDirectories.getRoot(), "jdbc-driver.jar");
       serverClient.download("/deploy/jdbc-driver.jar", jdbcDriver);
@@ -106,7 +107,7 @@ public class JdbcDriverHolder {
   public void stop() {
     if (classLoader != null) {
       classLoader.clearReferencesJdbc();
-      if (Thread.currentThread().getContextClassLoader()==classLoader) {
+      if (Thread.currentThread().getContextClassLoader() == classLoader) {
         Thread.currentThread().setContextClassLoader(classLoader.getParent());
       }
       classLoader = null;
index e10fc311e2eec23974b2d9321519cbea573ee4fd..e06c2f53cea4c3b3c35a7356c31b66c72f170b4d 100644 (file)
  */
 package org.sonar.batch.bootstrap;
 
-import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.common.io.Files;
 import com.google.common.io.InputSupplier;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang.StringUtils;
-import org.slf4j.LoggerFactory;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
 import org.sonar.api.utils.HttpDownloader;
 import org.sonar.api.utils.SonarException;
 import org.sonar.batch.bootstrapper.EnvironmentInformation;
@@ -38,9 +35,6 @@ import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URI;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
 
 /**
  * TODO extends Server when removing the deprecated org.sonar.batch.ServerMetadata
@@ -48,53 +42,16 @@ import java.util.Date;
  * @since 3.4
  */
 public class ServerClient implements BatchComponent {
-  private Settings settings;
+  private BootstrapSettings settings;
   private HttpDownloader.BaseHttpDownloader downloader;
 
-  public ServerClient(Settings settings, EnvironmentInformation env) {
+  public ServerClient(BootstrapSettings settings, EnvironmentInformation env) {
     this.settings = settings;
-    this.downloader = new HttpDownloader.BaseHttpDownloader(settings, env.toString());
-  }
-
-  public String getId() {
-    return settings.getString(CoreProperties.SERVER_ID);
-  }
-
-  public String getVersion() {
-    return settings.getString(CoreProperties.SERVER_VERSION);
-  }
-
-  public Date getStartedAt() {
-    String dateString = settings.getString(CoreProperties.SERVER_STARTTIME);
-    if (dateString != null) {
-      try {
-        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateString);
-
-      } catch (ParseException e) {
-        LoggerFactory.getLogger(getClass()).error("The property " + CoreProperties.SERVER_STARTTIME + " is badly formatted.", e);
-      }
-    }
-    return null;
+    this.downloader = new HttpDownloader.BaseHttpDownloader(settings.getProperties(), env.toString());
   }
 
   public String getURL() {
-    return StringUtils.removeEnd(StringUtils.defaultIfBlank(settings.getString("sonar.host.url"), "http://localhost:9000"), "/");
-  }
-
-  public String getPermanentServerId() {
-    return settings.getString(CoreProperties.PERMANENT_SERVER_ID);
-  }
-
-  public String getServerId() {
-    String remoteServerInfo = request("/api/server");
-    // don't use JSON utilities to extract ID from such a small string
-    return extractServerId(remoteServerInfo);
-  }
-
-  @VisibleForTesting
-  String extractServerId(String remoteServerInfo) {
-    String partialId = StringUtils.substringAfter(remoteServerInfo, "\"id\":\"");
-    return StringUtils.substringBefore(partialId, "\"");
+    return StringUtils.removeEnd(settings.getProperty("sonar.host.url", "http://localhost:9000"), "/");
   }
 
   public void download(String pathStartingWithSlash, File toFile) {
@@ -119,14 +76,14 @@ public class ServerClient implements BatchComponent {
     Preconditions.checkArgument(pathStartingWithSlash.startsWith("/"), "Path must start with slash /");
 
     URI uri = URI.create(getURL() + pathStartingWithSlash);
-    String login = settings.getString(CoreProperties.LOGIN);
+    String login = settings.getProperty(CoreProperties.LOGIN);
 
     try {
       InputSupplier<InputStream> inputSupplier;
       if (Strings.isNullOrEmpty(login)) {
         inputSupplier = downloader.newInputSupplier(uri);
       } else {
-        inputSupplier = downloader.newInputSupplier(uri, login, settings.getString(CoreProperties.PASSWORD));
+        inputSupplier = downloader.newInputSupplier(uri, login, settings.getProperty(CoreProperties.PASSWORD));
       }
       return inputSupplier;
     } catch (Exception e) {
diff --git a/sonar-batch/src/main/java/org/sonar/batch/bootstrap/ServerMetadata.java b/sonar-batch/src/main/java/org/sonar/batch/bootstrap/ServerMetadata.java
new file mode 100644 (file)
index 0000000..fbcf864
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.batch.bootstrap;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.BatchComponent;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.config.Settings;
+import org.sonar.api.platform.Server;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * @since 3.4. Replaces the deprecated org.sonar.batch.ServerMetadata
+ */
+public class ServerMetadata extends Server implements BatchComponent {
+
+  private Settings settings;
+  private ServerClient client;
+
+  public ServerMetadata(Settings settings, ServerClient client) {
+    this.settings = settings;
+    this.client = client;
+  }
+
+  @Override
+  public String getId() {
+    return settings.getString(CoreProperties.SERVER_ID);
+  }
+
+  @Override
+  public String getVersion() {
+    return settings.getString(CoreProperties.SERVER_VERSION);
+  }
+
+  @Override
+  public Date getStartedAt() {
+    String dateString = settings.getString(CoreProperties.SERVER_STARTTIME);
+    if (dateString != null) {
+      try {
+        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateString);
+
+      } catch (ParseException e) {
+        LoggerFactory.getLogger(getClass()).error("The property " + CoreProperties.SERVER_STARTTIME + " is badly formatted.", e);
+      }
+    }
+    return null;
+  }
+
+  @Override
+  public String getURL() {
+    return client.getURL();
+  }
+
+  @Override
+  public String getPermanentServerId() {
+    return settings.getString(CoreProperties.PERMANENT_SERVER_ID);
+  }
+
+  public String getServerId() {
+    String remoteServerInfo = client.request("/api/server");
+    // don't use JSON utilities to extract ID from such a small string
+    return extractServerId(remoteServerInfo);
+  }
+
+  @VisibleForTesting
+  String extractServerId(String remoteServerInfo) {
+    String partialId = StringUtils.substringAfter(remoteServerInfo, "\"id\":\"");
+    return StringUtils.substringBefore(partialId, "\"");
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java b/sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java
deleted file mode 100644 (file)
index 9e51156..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2012 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar 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.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
- */
-package org.sonar.batch.local;
-
-import com.google.common.base.Throwables;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.BatchComponent;
-import org.sonar.api.batch.bootstrap.ProjectReactor;
-import org.sonar.api.config.Settings;
-import org.sonar.api.database.DatabaseProperties;
-import org.sonar.api.utils.SonarException;
-import org.sonar.batch.bootstrap.DryRun;
-import org.sonar.batch.bootstrap.ProjectReactorReady;
-import org.sonar.batch.bootstrap.ServerClient;
-import org.sonar.batch.bootstrap.TempDirectories;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-/**
- * @since 3.4
- */
-public class DryRunDatabase implements BatchComponent {
-  private static final Logger LOG = LoggerFactory.getLogger(DryRunDatabase.class);
-
-  private static final String DIALECT = "h2";
-  private static final String DRIVER = "org.h2.Driver";
-  private static final String URL = "jdbc:h2:";
-  private static final String USER = "sonar";
-  private static final String PASSWORD = "sonar";
-
-  private final DryRun dryRun;
-  private final Settings settings;
-  private final ServerClient server;
-  private final TempDirectories tempDirectories;
-  private final ProjectReactor reactor;
-
-  public DryRunDatabase(DryRun dryRun, Settings settings, ServerClient server, TempDirectories tempDirectories, ProjectReactor reactor,
-                        // project reactor must be completely built
-                        ProjectReactorReady reactorReady) {
-    this.dryRun = dryRun;
-    this.settings = settings;
-    this.server = server;
-    this.tempDirectories = tempDirectories;
-    this.reactor = reactor;
-  }
-
-  public void start() {
-    if (!dryRun.isEnabled()) {
-      return;
-    }
-
-    LOG.info("Install dry run database");
-    File databaseFile = tempDirectories.getFile("dry_run", "db.h2.db");
-    downloadDatabase(reactor.getRoot().getKey(), databaseFile);
-
-    String databasePath = StringUtils.removeEnd(databaseFile.getAbsolutePath(), ".h2.db");
-    replaceSettings(databasePath);
-  }
-
-  private void downloadDatabase(String projectKey, File toFile) {
-    try {
-      server.download("/batch_bootstrap/db?project=" + projectKey, toFile);
-    } catch (SonarException e) {
-      Throwable rootCause = Throwables.getRootCause(e);
-      if (rootCause instanceof FileNotFoundException) {
-        throw new SonarException(String.format("Project [%s] doesn't exist on server", projectKey), e);
-      } else if ((rootCause instanceof IOException) && (StringUtils.contains(rootCause.getMessage(), "401"))) {
-        throw new SonarException(String.format("You don't have access rights to project [%s]", projectKey), e);
-      }
-      throw e;
-    }
-  }
-
-  private void replaceSettings(String databasePath) {
-    settings
-      .setProperty("sonar.jdbc.schema", "")
-      .setProperty(DatabaseProperties.PROP_DIALECT, DIALECT)
-      .setProperty(DatabaseProperties.PROP_DRIVER, DRIVER)
-      .setProperty(DatabaseProperties.PROP_USER, USER)
-      .setProperty(DatabaseProperties.PROP_PASSWORD, PASSWORD)
-      .setProperty(DatabaseProperties.PROP_URL, URL + databasePath);
-  }
-}
index c292007b31808b6769a4188b0403278a811c467f..4edb28f633adcec3ab18eaebcc53b2148affa387 100644 (file)
@@ -25,14 +25,15 @@ import com.google.gson.stream.JsonWriter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.BatchComponent;
+import org.sonar.api.CoreProperties;
 import org.sonar.api.batch.SensorContext;
+import org.sonar.api.config.Settings;
 import org.sonar.api.platform.Server;
 import org.sonar.api.resources.ProjectFileSystem;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.rules.Violation;
 import org.sonar.api.utils.SonarException;
-import org.sonar.batch.bootstrap.DryRun;
 import org.sonar.batch.index.DefaultIndex;
 import org.sonar.core.i18n.RuleI18nManager;
 
@@ -51,14 +52,14 @@ import java.util.Locale;
 public class DryRunExporter implements BatchComponent {
   private static final Logger LOG = LoggerFactory.getLogger(DryRunExporter.class);
 
-  private final DryRun dryRun;
+  private final Settings settings;
   private final DefaultIndex sonarIndex;
   private final ProjectFileSystem projectFileSystem;
   private final Server server;
   private final RuleI18nManager ruleI18nManager;
 
-  public DryRunExporter(DryRun dryRun, DefaultIndex sonarIndex, ProjectFileSystem projectFileSystem, Server server, RuleI18nManager ruleI18nManager) {
-    this.dryRun = dryRun;
+  public DryRunExporter(Settings settings, DefaultIndex sonarIndex, ProjectFileSystem projectFileSystem, Server server, RuleI18nManager ruleI18nManager) {
+    this.settings = settings;
     this.sonarIndex = sonarIndex;
     this.projectFileSystem = projectFileSystem;
     this.server = server;
@@ -66,15 +67,13 @@ public class DryRunExporter implements BatchComponent {
   }
 
   public void execute(SensorContext context) {
-    if (!dryRun.isEnabled()) {
-      return;
+    if (settings.getBoolean(CoreProperties.DRY_RUN)) {
+      exportResults(sonarIndex.getResources());
     }
-
-    exportResults(sonarIndex.getResources());
   }
 
   private void exportResults(Collection<Resource> resources) {
-    File exportFile = new File(projectFileSystem.getSonarWorkingDirectory(), dryRun.getExportPath());
+    File exportFile = new File(projectFileSystem.getSonarWorkingDirectory(), settings.getString("sonar.dryRun.export.path"));
 
     LOG.info("Exporting DryRun results to " + exportFile.getAbsolutePath());
     Writer output = null;
@@ -96,9 +95,9 @@ public class DryRunExporter implements BatchComponent {
       json.setSerializeNulls(false);
 
       json.beginObject()
-          .name("version").value(server.getVersion())
-          .name("violations_per_resource")
-          .beginObject();
+        .name("version").value(server.getVersion())
+        .name("violations_per_resource")
+        .beginObject();
 
       for (Resource resource : resources) {
         List<Violation> violations = getViolations(resource);
@@ -107,25 +106,25 @@ public class DryRunExporter implements BatchComponent {
         }
 
         json.name(resource.getKey())
-            .beginArray();
+          .beginArray();
 
         for (Violation violation : violations) {
           json.beginObject()
-              .name("line").value(violation.getLineId())
-              .name("message").value(violation.getMessage())
-              .name("severity").value(violation.getSeverity().name())
-              .name("rule_key").value(violation.getRule().getKey())
-              .name("rule_repository").value(violation.getRule().getRepositoryKey())
-              .name("rule_name").value(name(violation.getRule()))
-              .endObject();
+            .name("line").value(violation.getLineId())
+            .name("message").value(violation.getMessage())
+            .name("severity").value(violation.getSeverity().name())
+            .name("rule_key").value(violation.getRule().getKey())
+            .name("rule_repository").value(violation.getRule().getRepositoryKey())
+            .name("rule_name").value(name(violation.getRule()))
+            .endObject();
         }
 
         json.endArray();
       }
 
       json.endObject()
-          .endObject()
-          .flush();
+        .endObject()
+        .flush();
     } catch (IOException e) {
       throw new SonarException("Unable to export results", e);
     } finally {
index 177bba664539d5202f36b02eee6cdaee905ae499..ffa46451e02f274877e726717b4cc572f16fae3e 100644 (file)
@@ -21,7 +21,8 @@ package org.sonar.batch.phases;
 
 import org.slf4j.LoggerFactory;
 import org.sonar.api.BatchComponent;
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.config.Settings;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.resources.Scopes;
@@ -32,19 +33,20 @@ import javax.persistence.Query;
 
 import java.util.List;
 
-@DryRunIncompatible
 public class UpdateStatusJob implements BatchComponent {
 
   private DatabaseSession session;
   private ServerClient server;
   private Snapshot snapshot; // TODO remove this component
   private ResourcePersister resourcePersister;
+  private Settings settings;
 
-  public UpdateStatusJob(ServerClient server, DatabaseSession session, ResourcePersister resourcePersister, Snapshot snapshot) {
+  public UpdateStatusJob(Settings settings, ServerClient server, DatabaseSession session, ResourcePersister resourcePersister, Snapshot snapshot) {
     this.session = session;
     this.server = server;
     this.resourcePersister = resourcePersister;
     this.snapshot = snapshot;
+    this.settings = settings;
   }
 
   public void execute() {
@@ -70,7 +72,9 @@ public class UpdateStatusJob implements BatchComponent {
     Snapshot previousLastSnapshot = resourcePersister.getLastSnapshot(snapshot, false);
     boolean isLast = (previousLastSnapshot == null || previousLastSnapshot.getCreatedAt().before(snapshot.getCreatedAt()));
     setFlags(snapshot, isLast, Snapshot.STATUS_PROCESSED);
-    LoggerFactory.getLogger(getClass()).info("ANALYSIS SUCCESSFUL, you can browse {}", server.getURL());
+    if (!settings.getBoolean(CoreProperties.DRY_RUN)) {
+      LoggerFactory.getLogger(getClass()).info("ANALYSIS SUCCESSFUL, you can browse {}", server.getURL());
+    }
   }
 
   private void setFlags(Snapshot snapshot, boolean last, String status) {
index 0dbf698a05730afb478277ad53476e3b9cd02e9d..89031110121752641765dbd8a942ceb3cf4c815e 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.batch;
 
 import org.junit.Test;
 import org.sonar.api.utils.DateUtils;
-import org.sonar.batch.bootstrap.ServerClient;
 
 import java.util.Date;
 
@@ -31,8 +30,8 @@ import static org.mockito.Mockito.when;
 
 public class ServerMetadataTest {
   @Test
-  public void should_proxy_server_client() {
-    ServerClient client = mock(ServerClient.class);
+  public void should_proxy_target() {
+    org.sonar.batch.bootstrap.ServerMetadata client = mock(org.sonar.batch.bootstrap.ServerMetadata.class);
     when(client.getId()).thenReturn("id1");
     when(client.getPermanentServerId()).thenReturn("pid1");
     Date startedAt = DateUtils.parseDate("2012-05-18");
index 4399f2bfde87cc5d0507b4955419310ad70a6b80..aad1cf2a7fc64f1197804984fc5d8b659fac88b6 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.batch.bootstrap;
 
 import org.junit.Test;
 import org.sonar.api.config.Settings;
-import org.sonar.batch.local.DryRunDatabase;
 
 import java.util.Properties;
 
index c1a56e96f06f33bc51b949c14b225d56e2e34a1a..e58d334c104206b6181bc9ad1c2ed9af978fcdeb 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.batch.bootstrap;
 
 import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
 import org.codehaus.plexus.util.FileUtils;
 import org.hamcrest.Matchers;
 import org.junit.After;
@@ -33,6 +34,7 @@ import java.io.File;
 import java.io.IOException;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 
 import static org.hamcrest.Matchers.not;
 import static org.hamcrest.core.IsNull.nullValue;
@@ -140,64 +142,57 @@ public class BatchPluginRepositoryTest {
   @Test
   public void shouldAlwaysAcceptIfNoWhiteListAndBlackList() {
     repository = new BatchPluginRepository(mock(PluginDownloader.class), new Settings());
-    assertThat(repository.isAccepted("pmd"), Matchers.is(true));
+    assertThat(repository.isAccepted("pmd", null, null), Matchers.is(true));
   }
 
   @Test
   public void whiteListShouldTakePrecedenceOverBlackList() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.BATCH_INCLUDE_PLUGINS, "checkstyle,pmd,findbugs");
-    settings.setProperty(CoreProperties.BATCH_EXCLUDE_PLUGINS, "cobertura,pmd");
-    repository = new BatchPluginRepository(mock(PluginDownloader.class), settings);
-
-    assertThat(repository.isAccepted("pmd"), Matchers.is(true));
+    Set<String> whiteList = Sets.newHashSet("checkstyle", "pmd", "findbugs");
+    Set<String> blackList = Sets.newHashSet("cobertura", "pmd");
+    assertThat(BatchPluginRepository.isAccepted("pmd", whiteList, blackList), Matchers.is(true));
   }
 
   @Test
   public void corePluginShouldAlwaysBeInWhiteList() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.BATCH_INCLUDE_PLUGINS, "checkstyle,pmd,findbugs");
-    repository = new BatchPluginRepository(mock(PluginDownloader.class), settings);
-    assertThat(repository.isAccepted("core"), Matchers.is(true));
+    Set<String> whiteList = Sets.newHashSet("checkstyle", "pmd", "findbugs");
+    Set<String> blackList = null;
+
+    assertThat(BatchPluginRepository.isAccepted("core", whiteList, blackList), Matchers.is(true));
   }
 
   @Test
   public void corePluginShouldNeverBeInBlackList() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.BATCH_EXCLUDE_PLUGINS, "core,findbugs");
-    repository = new BatchPluginRepository(mock(PluginDownloader.class), settings);
-    assertThat(repository.isAccepted("core"), Matchers.is(true));
+    Set<String> whiteList = null;
+    Set<String> blackList = Sets.newHashSet("core", "findbugs");
+
+    assertThat(BatchPluginRepository.isAccepted("core", whiteList, blackList), Matchers.is(true));
   }
 
   // English Pack plugin should never be blacklisted as it is mandatory for the I18nManager on batch side
   @Test
   public void englishPackPluginShouldNeverBeInBlackList() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.BATCH_EXCLUDE_PLUGINS, "l10nen,findbugs");
-    repository = new BatchPluginRepository(mock(PluginDownloader.class), settings);
-    assertThat(repository.isAccepted("l10nen"), Matchers.is(true));
+    Set<String> whiteList = null;
+    Set<String> blackList = Sets.newHashSet("l10nen", "findbugs");
+    assertThat(BatchPluginRepository.isAccepted("l10nen", whiteList, blackList), Matchers.is(true));
   }
 
   @Test
   public void shouldCheckWhitelist() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.BATCH_INCLUDE_PLUGINS, "checkstyle,pmd,findbugs");
-    repository = new BatchPluginRepository(mock(PluginDownloader.class), settings);
+    Set<String> whiteList = Sets.newHashSet("checkstyle", "pmd", "findbugs");
+    Set<String> blackList = null;
 
-    assertThat(repository.isAccepted("checkstyle"), Matchers.is(true));
-    assertThat(repository.isAccepted("pmd"), Matchers.is(true));
-    assertThat(repository.isAccepted("cobertura"), Matchers.is(false));
+    assertThat(BatchPluginRepository.isAccepted("checkstyle", whiteList, blackList), Matchers.is(true));
+    assertThat(BatchPluginRepository.isAccepted("pmd", whiteList, blackList), Matchers.is(true));
+    assertThat(BatchPluginRepository.isAccepted("cobertura", whiteList, blackList), Matchers.is(false));
   }
 
   @Test
   public void shouldCheckBlackListIfNoWhiteList() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.BATCH_EXCLUDE_PLUGINS, "checkstyle,pmd,findbugs");
-    repository = new BatchPluginRepository(mock(PluginDownloader.class), settings);
-
-    assertThat(repository.isAccepted("checkstyle"), Matchers.is(false));
-    assertThat(repository.isAccepted("pmd"), Matchers.is(false));
-    assertThat(repository.isAccepted("cobertura"), Matchers.is(true));
+    Set<String> whiteList = null;
+    Set<String> blackList = Sets.newHashSet("checkstyle", "pmd", "findbugs");
+    assertThat(BatchPluginRepository.isAccepted("checkstyle", whiteList, blackList), Matchers.is(false));
+    assertThat(BatchPluginRepository.isAccepted("pmd", whiteList, blackList), Matchers.is(false));
+    assertThat(BatchPluginRepository.isAccepted("cobertura", whiteList, blackList), Matchers.is(true));
   }
 
 }
index 501a7dfbc8eddee24ac68d82ee310d88b684169b..59b85e28bfa99790403a452d85fab8834f1a8026 100644 (file)
@@ -53,38 +53,38 @@ public class BatchSettingsTest {
         "{\"k\":\"sonar.java.coveragePlugin\",\"v\":\"jacoco\",\"p\":\"struts\"}," +
         "{\"k\":\"sonar.java.coveragePlugin\",\"v\":\"cobertura\",\"p\":\"struts-core\"}]"
     );
-    bootstrapSettings = new BootstrapSettings(new PropertyDefinitions(), reactor, deprecatedConf);
+    bootstrapSettings = new BootstrapSettings(reactor);
   }
 
   @Test
   public void should_load_system_props() {
     System.setProperty("BatchSettingsTest.testSystemProp", "system");
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
     assertThat(batchSettings.getString("BatchSettingsTest.testSystemProp")).isEqualTo("system");
   }
 
   @Test
   public void should_load_build_props() {
     project.setProperty("build.prop", "build");
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
     assertThat(batchSettings.getString("build.prop")).isEqualTo("build");
   }
 
   @Test
   public void should_load_global_settings() {
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
     assertThat(batchSettings.getBoolean("sonar.cpd.cross")).isTrue();
   }
 
   @Test
   public void should_load_project_root_settings() {
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
     assertThat(batchSettings.getString("sonar.java.coveragePlugin")).isEqualTo("jacoco");
   }
 
   @Test
   public void should_keep_module_settings_for_later() {
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
     Map<String, String> moduleSettings = batchSettings.getModuleProperties("struts-core");
     assertThat(moduleSettings).hasSize(1);
     assertThat(moduleSettings.get("sonar.java.coveragePlugin")).isEqualTo("cobertura");
@@ -94,13 +94,13 @@ public class BatchSettingsTest {
   public void system_props_should_override_build_props() {
     System.setProperty("BatchSettingsTest.testSystemProp", "system");
     project.setProperty("BatchSettingsTest.testSystemProp", "build");
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
     assertThat(batchSettings.getString("BatchSettingsTest.testSystemProp")).isEqualTo("system");
   }
 
   @Test
   public void should_forward_to_deprecated_commons_configuration() {
-    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, reactor, client, deprecatedConf);
+    BatchSettings batchSettings = new BatchSettings(bootstrapSettings, new PropertyDefinitions(), reactor, client, deprecatedConf);
 
     assertThat(deprecatedConf.getString("sonar.cpd.cross")).isEqualTo("true");
     assertThat(deprecatedConf.getString("sonar.java.coveragePlugin")).isEqualTo("jacoco");
index df01592816bed4e6cd0d8e0f250429d7acf601e3..9f2d807bff8863032083c4373b11a3508545e0a7 100644 (file)
  */
 package org.sonar.batch.bootstrap;
 
-import org.apache.commons.configuration.BaseConfiguration;
 import org.junit.Test;
 import org.sonar.api.batch.bootstrap.ProjectDefinition;
 import org.sonar.api.batch.bootstrap.ProjectReactor;
-import org.sonar.api.config.PropertyDefinitions;
 
 import static org.fest.assertions.Assertions.assertThat;
 
@@ -36,9 +34,9 @@ public class BootstrapSettingsTest {
     project.setProperty("foo", "bar");
 
     ProjectReactor reactor = new ProjectReactor(project);
-    BootstrapSettings settings = new BootstrapSettings(new PropertyDefinitions(), reactor, new BaseConfiguration());
+    BootstrapSettings settings = new BootstrapSettings(reactor);
 
-    assertThat(settings.getString("foo")).isEqualTo("bar");
+    assertThat(settings.getProperty("foo")).isEqualTo("bar");
   }
 
   @Test
@@ -48,29 +46,8 @@ public class BootstrapSettingsTest {
     System.setProperty("BootstrapSettingsTest.testEnv", "env");
 
     ProjectReactor reactor = new ProjectReactor(project);
-    BootstrapSettings settings = new BootstrapSettings(new PropertyDefinitions(), reactor, new BaseConfiguration());
+    BootstrapSettings settings = new BootstrapSettings(reactor);
 
-    assertThat(settings.getString("BootstrapSettingsTest.testEnv")).isEqualTo("env");
-  }
-
-  @Test
-  public void shouldForwardToCommonsConfiguration() {
-    ProjectDefinition project = ProjectDefinition.create();
-    project.setProperty("hello", "world");
-    project.setProperty("foo", "bar");
-    ProjectReactor reactor = new ProjectReactor(project);
-    BaseConfiguration deprecatedConfiguration = new BaseConfiguration();
-    BootstrapSettings settings = new BootstrapSettings(new PropertyDefinitions(), reactor, deprecatedConfiguration);
-
-    assertThat(deprecatedConfiguration.getString("hello")).isEqualTo("world");
-    assertThat(deprecatedConfiguration.getString("foo")).isEqualTo("bar");
-
-    settings.removeProperty("foo");
-    assertThat(deprecatedConfiguration.getString("foo")).isNull();
-    assertThat(deprecatedConfiguration.getString("hello")).isEqualTo("world");
-
-    settings.clear();
-    assertThat(deprecatedConfiguration.getString("foo")).isNull();
-    assertThat(deprecatedConfiguration.getString("hello")).isNull();
+    assertThat(settings.getProperty("BootstrapSettingsTest.testEnv")).isEqualTo("env");
   }
 }
index 41489b7b530c5ff7636824e362d3869f3077f96e..5ed24eb4fb15da1f9613e976698dbe7303bb6ea2 100644 (file)
@@ -38,12 +38,12 @@ public class DatabaseCompatibilityTest {
   public ExpectedException thrown = ExpectedException.none();
 
   DatabaseVersion databaseVersion;
-  ServerClient server;
+  ServerMetadata server;
   Settings settings;
 
   @Before
   public void init() {
-    server = mock(ServerClient.class);
+    server = mock(ServerMetadata.class);
     when(server.getURL()).thenReturn("http://localhost:9000");
     when(server.getServerId()).thenReturn("123456");
 
diff --git a/sonar-batch/src/test/java/org/sonar/batch/bootstrap/DryRunDatabaseTest.java b/sonar-batch/src/test/java/org/sonar/batch/bootstrap/DryRunDatabaseTest.java
new file mode 100644 (file)
index 0000000..86133b6
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.junit.Before;
+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 org.sonar.api.config.Settings;
+import org.sonar.api.database.DatabaseProperties;
+import org.sonar.api.utils.SonarException;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import static org.fest.assertions.Assertions.assertThat;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+public class DryRunDatabaseTest {
+  DryRunDatabase dryRunDatabase;
+
+  Settings settings = new Settings();
+  ServerClient server = mock(ServerClient.class);
+  TempDirectories tempDirectories = mock(TempDirectories.class);
+  ProjectReactor projectReactor = new ProjectReactor(ProjectDefinition.create().setKey("group:project"));
+
+  @Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  @Before
+  public void setUp() {
+    settings.setProperty("sonar.dryRun", true);
+    dryRunDatabase = new DryRunDatabase(settings, server, tempDirectories, projectReactor, mock(ProjectReactorReady.class));
+  }
+
+  @Test
+  public void should_be_disabled_if_not_dry_run() {
+    settings.setProperty("sonar.dryRun", false);
+    dryRunDatabase.start();
+
+    verifyZeroInteractions(tempDirectories, server);
+  }
+
+  @Test
+  public void should_download_database() {
+    File databaseFile = new File("/tmp/dry_run/db.h2.db");
+    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(databaseFile);
+
+    dryRunDatabase.start();
+
+    verify(server).download("/batch_bootstrap/db?project=group:project", databaseFile);
+  }
+
+  @Test
+  public void should_replace_database_settings() {
+    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
+
+    dryRunDatabase.start();
+
+    assertThat(settings.getString(DatabaseProperties.PROP_DIALECT)).isEqualTo("h2");
+    assertThat(settings.getString(DatabaseProperties.PROP_DRIVER)).isEqualTo("org.h2.Driver");
+    assertThat(settings.getString(DatabaseProperties.PROP_USER)).isEqualTo("sonar");
+    assertThat(settings.getString(DatabaseProperties.PROP_PASSWORD)).isEqualTo("sonar");
+    assertThat(settings.getString(DatabaseProperties.PROP_URL)).isEqualTo("jdbc:h2:/tmp/dry_run/db");
+  }
+
+  @Test
+  public void should_fail_on_unknown_project() {
+    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
+    doThrow(new SonarException(new FileNotFoundException())).when(server).download("/batch_bootstrap/db?project=group:project", new File("/tmp/dry_run/db.h2.db"));
+
+    thrown.expect(SonarException.class);
+    thrown.expectMessage("Project [group:project] doesn't exist on server");
+
+    dryRunDatabase.start();
+  }
+
+  @Test
+  public void should_fail_on_invalid_role() {
+    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
+    doThrow(new SonarException(new IOException("HTTP 401"))).when(server).download("/batch_bootstrap/db?project=group:project", new File("/tmp/dry_run/db.h2.db"));
+
+    thrown.expect(SonarException.class);
+    thrown.expectMessage("You don't have access rights to project [group:project]");
+
+    dryRunDatabase.start();
+  }
+
+  @Test
+  public void should_fail() {
+    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
+    doThrow(new SonarException("BUG")).when(server).download("/batch_bootstrap/db?project=group:project", new File("/tmp/dry_run/db.h2.db"));
+
+    thrown.expect(SonarException.class);
+    thrown.expectMessage("BUG");
+
+    dryRunDatabase.start();
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/bootstrap/DryRunTest.java b/sonar-batch/src/test/java/org/sonar/batch/bootstrap/DryRunTest.java
deleted file mode 100644 (file)
index b671deb..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2012 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar 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.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
- */
-package org.sonar.batch.bootstrap;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.Settings;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-public class DryRunTest {
-  DryRun dryRun;
-  Settings settings;
-
-  @Before
-  public void setUp() {
-    settings = new Settings(new PropertyDefinitions(DryRun.class));
-
-    dryRun = new DryRun(settings);
-  }
-
-  @Test
-  public void should_be_disabled() {
-    dryRun.start();
-
-    assertThat(dryRun.isEnabled()).isFalse();
-  }
-
-  @Test
-  public void should_enable() {
-    settings.setProperty("sonar.dryRun", "true");
-
-    dryRun.start();
-
-    assertThat(dryRun.isEnabled()).isTrue();
-  }
-
-  @Test
-  public void should_get_default_export_path() {
-    String exportPath = dryRun.getExportPath();
-
-    assertThat(exportPath).isEqualTo("dryRun.json");
-  }
-
-  @Test
-  public void should_get_custom_export_path() {
-    settings.setProperty("sonar.dryRun.export.path", "export.json");
-
-    String exportPath = dryRun.getExportPath();
-
-    assertThat(exportPath).isEqualTo("export.json");
-  }
-}
index 3ce49c8a4b9ab1bfa6aeb332aa0ef0d9782bf40e..35136e685706e98692bcafd9f9171fd38314176b 100644 (file)
@@ -22,7 +22,7 @@ package org.sonar.batch.bootstrap;
 import org.junit.Test;
 import org.sonar.api.BatchExtension;
 import org.sonar.api.ServerExtension;
-import org.sonar.api.batch.DryRunIncompatible;
+import org.sonar.core.DryRunIncompatible;
 import org.sonar.api.batch.InstantiationStrategy;
 import org.sonar.api.batch.SupportedEnvironment;
 import org.sonar.batch.bootstrapper.EnvironmentInformation;
index ffa5cec799fca6974270d7b1e52e85ba07ae3c48..8f70ea1e3bde13448b6af778c13ed50a4b8ca511 100644 (file)
@@ -22,9 +22,10 @@ package org.sonar.batch.bootstrap;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.config.Settings;
 
 import java.io.File;
-import java.net.URL;
 
 import static org.fest.assertions.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
@@ -34,7 +35,7 @@ import static org.mockito.Mockito.when;
 
 public class JdbcDriverHolderTest {
 
-  private ClassLoader initialThreadClassloader;
+  ClassLoader initialThreadClassloader;
 
   @Before
   public void before() {
@@ -56,7 +57,7 @@ public class JdbcDriverHolderTest {
     when(tempDirectories.getRoot()).thenReturn(fakeDriver.getParentFile());
     ServerClient server = mock(ServerClient.class);
 
-    JdbcDriverHolder holder = new JdbcDriverHolder(mock(DryRun.class), tempDirectories, server);
+    JdbcDriverHolder holder = new JdbcDriverHolder(new Settings(), tempDirectories, server);
     holder.start();
 
     verify(server).download("/deploy/jdbc-driver.jar", fakeDriver);
@@ -71,10 +72,9 @@ public class JdbcDriverHolderTest {
 
   @Test
   public void should_be_disabled_if_dry_run() {
-    DryRun dryRun = mock(DryRun.class);
-    when(dryRun.isEnabled()).thenReturn(true);
+    Settings settings = new Settings().setProperty(CoreProperties.DRY_RUN, true);
     ServerClient server = mock(ServerClient.class);
-    JdbcDriverHolder holder = new JdbcDriverHolder(dryRun, mock(TempDirectories.class), server);
+    JdbcDriverHolder holder = new JdbcDriverHolder(settings, mock(TempDirectories.class), server);
 
     holder.start();
 
index e907cc2fe0d7a78a3b59cbe7407e414acea1fb91..baf74ae58c41fd5c29304cd561c27c4392386fdd 100644 (file)
 package org.sonar.batch.bootstrap;
 
 import org.junit.Test;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
 import org.sonar.batch.bootstrapper.EnvironmentInformation;
 
 import static org.fest.assertions.Assertions.assertThat;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 public class ServerClientTest {
 
-  @Test
-  public void shouldExtractId() throws Exception {
-    ServerClient server = new ServerClient(new Settings(), mock(EnvironmentInformation.class));
-    assertThat(server.extractServerId("{\"id\":\"123456\",\"version\":\"3.1\",\"status\":\"UP\"}")).isEqualTo("123456");
-  }
-
   @Test
   public void shouldRemoveUrlEndingSlash() throws Exception {
-    Settings settings = new Settings();
-    settings.setProperty("sonar.host.url", "http://localhost:8080/sonar/");
+    BootstrapSettings settings = mock(BootstrapSettings.class);
+    when(settings.getProperty(eq("sonar.host.url"), anyString())).thenReturn("http://localhost:8080/sonar/");
+
     ServerClient server = new ServerClient(settings, new EnvironmentInformation("Junit", "4"));
 
     assertThat(server.getURL()).isEqualTo("http://localhost:8080/sonar");
   }
-
-  @Test
-  public void shouldLoadServerProperties() {
-    Settings settings = new Settings();
-    settings.setProperty(CoreProperties.SERVER_ID, "123");
-    settings.setProperty(CoreProperties.SERVER_VERSION, "2.2");
-    settings.setProperty(CoreProperties.SERVER_STARTTIME, "2010-05-18T17:59:00+0000");
-    settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, "abcde");
-    settings.setProperty("sonar.host.url", "http://foo.com");
-
-    ServerClient server = new ServerClient(settings, mock(EnvironmentInformation.class));
-
-    assertThat(server.getId()).isEqualTo("123");
-    assertThat(server.getVersion()).isEqualTo("2.2");
-    assertThat(server.getStartedAt().getDate()).isEqualTo(18);
-    assertThat(server.getURL()).isEqualTo("http://foo.com");
-    assertThat(server.getPermanentServerId()).isEqualTo("abcde");
-  }
 }
diff --git a/sonar-batch/src/test/java/org/sonar/batch/bootstrap/ServerMetadataTest.java b/sonar-batch/src/test/java/org/sonar/batch/bootstrap/ServerMetadataTest.java
new file mode 100644 (file)
index 0000000..bfbbfdf
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.junit.Test;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.config.Settings;
+
+import static org.fest.assertions.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class ServerMetadataTest {
+
+  @Test
+  public void shouldExtractId() throws Exception {
+    ServerMetadata metadata = new ServerMetadata(new Settings(), mock(ServerClient.class));
+    assertThat(metadata.extractServerId("{\"id\":\"123456\",\"version\":\"3.1\",\"status\":\"UP\"}")).isEqualTo("123456");
+  }
+
+  @Test
+  public void shouldLoadServerProperties() {
+    Settings settings = new Settings();
+    settings.setProperty(CoreProperties.SERVER_ID, "123");
+    settings.setProperty(CoreProperties.SERVER_VERSION, "2.2");
+    settings.setProperty(CoreProperties.SERVER_STARTTIME, "2010-05-18T17:59:00+0000");
+    settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, "abcde");
+    ServerClient client = mock(ServerClient.class);
+    when(client.getURL()).thenReturn("http://foo.com");
+
+    ServerMetadata metadata = new ServerMetadata(settings, client);
+
+    assertThat(metadata.getId()).isEqualTo("123");
+    assertThat(metadata.getVersion()).isEqualTo("2.2");
+    assertThat(metadata.getStartedAt().getDate()).isEqualTo(18);
+    assertThat(metadata.getURL()).isEqualTo("http://foo.com");
+    assertThat(metadata.getPermanentServerId()).isEqualTo("abcde");
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/local/DryRunDatabaseTest.java b/sonar-batch/src/test/java/org/sonar/batch/local/DryRunDatabaseTest.java
deleted file mode 100644 (file)
index e3cb4ce..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2012 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar 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.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
- */
-package org.sonar.batch.local;
-
-import org.junit.Before;
-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 org.sonar.api.config.Settings;
-import org.sonar.api.database.DatabaseProperties;
-import org.sonar.api.utils.SonarException;
-import org.sonar.batch.bootstrap.DryRun;
-import org.sonar.batch.bootstrap.ProjectReactorReady;
-import org.sonar.batch.bootstrap.ServerClient;
-import org.sonar.batch.bootstrap.TempDirectories;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-import static org.fest.assertions.Assertions.assertThat;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-public class DryRunDatabaseTest {
-  DryRunDatabase dryRunDatabase;
-
-  DryRun dryRun = mock(DryRun.class);
-  Settings settings = new Settings();
-  ServerClient server = mock(ServerClient.class);
-  TempDirectories tempDirectories = mock(TempDirectories.class);
-  ProjectReactor projectReactor = new ProjectReactor(ProjectDefinition.create().setKey("group:project"));
-
-  @Rule
-  public ExpectedException thrown = ExpectedException.none();
-
-  @Before
-  public void setUp() {
-    dryRunDatabase = new DryRunDatabase(dryRun, settings, server, tempDirectories, projectReactor, mock(ProjectReactorReady.class));
-  }
-
-  @Test
-  public void should_disable_if_no_dry_run() {
-    dryRunDatabase.start();
-
-    verifyZeroInteractions(tempDirectories, server);
-  }
-
-  @Test
-  public void should_download_database() {
-    File databaseFile = new File("/tmp/dry_run/db.h2.db");
-    when(dryRun.isEnabled()).thenReturn(true);
-    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(databaseFile);
-
-    dryRunDatabase.start();
-
-    verify(server).download("/batch_bootstrap/db?project=group:project", databaseFile);
-  }
-
-  @Test
-  public void should_replace_database_settings() {
-    when(dryRun.isEnabled()).thenReturn(true);
-    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
-
-    dryRunDatabase.start();
-
-    assertThat(settings.getString(DatabaseProperties.PROP_DIALECT)).isEqualTo("h2");
-    assertThat(settings.getString(DatabaseProperties.PROP_DRIVER)).isEqualTo("org.h2.Driver");
-    assertThat(settings.getString(DatabaseProperties.PROP_USER)).isEqualTo("sonar");
-    assertThat(settings.getString(DatabaseProperties.PROP_PASSWORD)).isEqualTo("sonar");
-    assertThat(settings.getString(DatabaseProperties.PROP_URL)).isEqualTo("jdbc:h2:/tmp/dry_run/db");
-  }
-
-  @Test
-  public void should_fail_on_unknown_project() {
-    when(dryRun.isEnabled()).thenReturn(true);
-    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
-    doThrow(new SonarException(new FileNotFoundException())).when(server).download("/batch_bootstrap/db?project=group:project", new File("/tmp/dry_run/db.h2.db"));
-
-    thrown.expect(SonarException.class);
-    thrown.expectMessage("Project [group:project] doesn't exist on server");
-
-    dryRunDatabase.start();
-  }
-
-  @Test
-  public void should_fail_on_invalid_role() {
-    when(dryRun.isEnabled()).thenReturn(true);
-    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
-    doThrow(new SonarException(new IOException("HTTP 401"))).when(server).download("/batch_bootstrap/db?project=group:project", new File("/tmp/dry_run/db.h2.db"));
-
-    thrown.expect(SonarException.class);
-    thrown.expectMessage("You don't have access rights to project [group:project]");
-
-    dryRunDatabase.start();
-  }
-
-  @Test
-  public void should_fail() {
-    when(dryRun.isEnabled()).thenReturn(true);
-    when(tempDirectories.getFile("dry_run", "db.h2.db")).thenReturn(new File("/tmp/dry_run/db.h2.db"));
-    doThrow(new SonarException("BUG")).when(server).download("/batch_bootstrap/db?project=group:project", new File("/tmp/dry_run/db.h2.db"));
-
-    thrown.expect(SonarException.class);
-    thrown.expectMessage("BUG");
-
-    dryRunDatabase.start();
-  }
-}
index 733893f9860e7f1c0a226d84aae488c9e62928f2..c434b09afb3cf3be5e350be998de2f79729d23d4 100644 (file)
@@ -23,14 +23,15 @@ import com.google.common.collect.ImmutableSet;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
+import org.sonar.api.CoreProperties;
 import org.sonar.api.batch.SensorContext;
+import org.sonar.api.config.Settings;
 import org.sonar.api.platform.Server;
 import org.sonar.api.resources.ProjectFileSystem;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.rules.RulePriority;
 import org.sonar.api.rules.Violation;
-import org.sonar.batch.bootstrap.DryRun;
 import org.sonar.batch.index.DefaultIndex;
 import org.sonar.core.i18n.RuleI18nManager;
 import org.sonar.java.api.JavaClass;
@@ -50,8 +51,6 @@ import static org.mockito.Mockito.when;
 
 public class DryRunExporterTest {
   DryRunExporter dryRunExporter;
-
-  DryRun dryRun = mock(DryRun.class);
   DefaultIndex sonarIndex = mock(DefaultIndex.class);
   SensorContext sensorContext = mock(SensorContext.class);
   Resource resource = JavaClass.create("KEY");
@@ -59,17 +58,21 @@ public class DryRunExporterTest {
   ProjectFileSystem projectFileSystem = mock(ProjectFileSystem.class);
   Server server = mock(Server.class);
   RuleI18nManager ruleI18nManager = mock(RuleI18nManager.class);
+  Settings settings;
 
   @org.junit.Rule
   public TemporaryFolder temporaryFolder = new TemporaryFolder();
 
   @Before
   public void setUp() {
-    dryRunExporter = spy(new DryRunExporter(dryRun, sonarIndex, projectFileSystem, server, ruleI18nManager));
+    settings = new Settings();
+    settings.setProperty(CoreProperties.DRY_RUN, true);
+    dryRunExporter = spy(new DryRunExporter(settings, sonarIndex, projectFileSystem, server, ruleI18nManager));
   }
 
   @Test
-  public void should_disable_if_no_dry_run() {
+  public void should_be_disabled_if_not_dry_run() {
+    settings.setProperty(CoreProperties.DRY_RUN, false);
     dryRunExporter.execute(sensorContext);
 
     verifyZeroInteractions(sensorContext, sonarIndex);
@@ -77,7 +80,6 @@ public class DryRunExporterTest {
 
   @Test
   public void should_export_violations() {
-    when(dryRun.isEnabled()).thenReturn(true);
     when(server.getVersion()).thenReturn("3.4");
     when(violation.getResource()).thenReturn(resource);
     when(violation.getLineId()).thenReturn(1);
@@ -92,13 +94,12 @@ public class DryRunExporterTest {
     String json = output.toString();
 
     assertThat(json)
-        .isEqualTo(
-            "{\"version\":\"3.4\",\"violations_per_resource\":{\"KEY\":[{\"line\":1,\"message\":\"VIOLATION\",\"severity\":\"INFO\",\"rule_key\":\"RULE_KEY\",\"rule_repository\":\"pmd\",\"rule_name\":\"RULE_NAME\"}]}}");
+      .isEqualTo(
+        "{\"version\":\"3.4\",\"violations_per_resource\":{\"KEY\":[{\"line\":1,\"message\":\"VIOLATION\",\"severity\":\"INFO\",\"rule_key\":\"RULE_KEY\",\"rule_repository\":\"pmd\",\"rule_name\":\"RULE_NAME\"}]}}");
   }
 
   @Test
   public void should_export_violation_with_no_line() {
-    when(dryRun.isEnabled()).thenReturn(true);
     when(server.getVersion()).thenReturn("3.4");
     when(violation.getResource()).thenReturn(resource);
     when(violation.getLineId()).thenReturn(null);
@@ -113,14 +114,13 @@ public class DryRunExporterTest {
     String json = output.toString();
 
     assertThat(json).isEqualTo(
-        "{\"version\":\"3.4\",\"violations_per_resource\":{\"KEY\":[{\"message\":\"VIOLATION\",\"severity\":\"INFO\",\"rule_key\":\"RULE_KEY\",\"rule_repository\":\"pmd\",\"rule_name\":\"RULE_NAME\"}]}}");
+      "{\"version\":\"3.4\",\"violations_per_resource\":{\"KEY\":[{\"message\":\"VIOLATION\",\"severity\":\"INFO\",\"rule_key\":\"RULE_KEY\",\"rule_repository\":\"pmd\",\"rule_name\":\"RULE_NAME\"}]}}");
   }
 
   @Test
   public void should_ignore_resources_without_violations() {
-    when(dryRun.isEnabled()).thenReturn(true);
     when(server.getVersion()).thenReturn("3.4");
-    doReturn(Arrays.<Violation> asList()).when(dryRunExporter).getViolations(resource);
+    doReturn(Arrays.<Violation>asList()).when(dryRunExporter).getViolations(resource);
 
     StringWriter output = new StringWriter();
     dryRunExporter.writeJson(ImmutableSet.of(resource), output);
@@ -132,11 +132,9 @@ public class DryRunExporterTest {
   @Test
   public void should_export_violations_to_file() throws IOException {
     File sonarDirectory = temporaryFolder.newFolder("sonar");
-    when(dryRun.isEnabled()).thenReturn(true);
-    when(dryRun.isEnabled()).thenReturn(true);
     when(server.getVersion()).thenReturn("3.4");
-    doReturn(Arrays.<Violation> asList()).when(dryRunExporter).getViolations(resource);
-    when(dryRun.getExportPath()).thenReturn("output.json");
+    doReturn(Arrays.<Violation>asList()).when(dryRunExporter).getViolations(resource);
+    settings.setProperty("sonar.dryRun.export.path", "output.json");
     when(projectFileSystem.getSonarWorkingDirectory()).thenReturn(sonarDirectory);
 
     dryRunExporter.execute(sensorContext);
index 0018727b44523fc9ae30b6988704b71d05434b96..923eb3a98cecbe60c9cd45136ffc42aee1f377c3 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.batch.phases;
 
 import org.junit.Test;
+import org.sonar.api.config.Settings;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.database.model.Snapshot;
 import org.sonar.batch.bootstrap.ServerClient;
@@ -51,7 +52,7 @@ public class UpdateStatusJobTest extends AbstractDbUnitTestCase {
     setupData("sharedFixture", fixture);
 
     DatabaseSession session = getSession();
-    UpdateStatusJob sensor = new UpdateStatusJob(mock(ServerClient.class), session, new DefaultResourcePersister(session), loadSnapshot(snapshotId));
+    UpdateStatusJob sensor = new UpdateStatusJob(new Settings(), mock(ServerClient.class), session, new DefaultResourcePersister(session), loadSnapshot(snapshotId));
     sensor.execute();
 
     checkTables(fixture, "snapshots");
diff --git a/sonar-core/src/main/java/org/sonar/core/DryRunIncompatible.java b/sonar-core/src/main/java/org/sonar/core/DryRunIncompatible.java
new file mode 100644 (file)
index 0000000..70814e8
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2012 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar 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.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
+ */
+package org.sonar.core;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * The presence of this annotation on an extension class indicates that the extension
+ * may be disabled when the dry-run mode is enabled (-Dsonar.dryRun=true).
+ * It's generally used by the extensions that push data to external systems, for example :
+ * <ul>
+ *   <li>Send emails</li>
+ *   <li>Create a JIRA issue</li>
+ * </ul>
+ *
+ *
+ * @since 3.4
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface DryRunIncompatible {
+}
index ba1bc4331877bc4f84c993bbe71df3c74ec7ddce..88e87de56616c7de0e6f1db8a94b4ad25c8ee1f3 100644 (file)
@@ -343,4 +343,9 @@ public interface CoreProperties {
    * @since 3.4
    */
   String PASSWORD = "sonar.password";
+
+  /**
+   * @since 3.4
+   */
+  String DRY_RUN = "sonar.dryRun";
 }
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DryRunIncompatible.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/DryRunIncompatible.java
deleted file mode 100644 (file)
index aa113c4..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2012 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar 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.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
- */
-package org.sonar.api.batch;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * The presence of this annotation on an extension class indicates that the extension
- * may be disabled when the dry-run mode is enabled (-Dsonar.dryRun=true).
- * It's generally used by the extensions that push data to external systems, for example :
- * <ul>
- *   <li>Send emails</li>
- *   <li>Create a JIRA issue</li>
- * </ul>
- *
- *
- * @since 3.4
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-public @interface DryRunIncompatible {
-}
index 0f29541dc300ed86541e36c1795f3147cc6da317..6e9bb112de47279690fa94d8b472bb5eca835ccf 100644 (file)
@@ -47,6 +47,7 @@ import java.net.ProxySelector;
 import java.net.URI;
 import java.nio.charset.Charset;
 import java.util.List;
+import java.util.Map;
 
 /**
  * This component downloads HTTP files
@@ -59,11 +60,11 @@ public class HttpDownloader extends UriReader.SchemeProcessor implements BatchCo
   private final BaseHttpDownloader downloader;
 
   public HttpDownloader(Server server, Settings settings) {
-    downloader = new BaseHttpDownloader(settings, server.getVersion());
+    downloader = new BaseHttpDownloader(settings.getProperties(), server.getVersion());
   }
 
   public HttpDownloader(Settings settings) {
-    downloader = new BaseHttpDownloader(settings, null);
+    downloader = new BaseHttpDownloader(settings.getProperties(), null);
   }
 
   @Override
@@ -73,7 +74,7 @@ public class HttpDownloader extends UriReader.SchemeProcessor implements BatchCo
 
   @Override
   String[] getSupportedSchemes() {
-    return new String[] {"http", "https"};
+    return new String[]{"http", "https"};
   }
 
   @Override
@@ -129,17 +130,17 @@ public class HttpDownloader extends UriReader.SchemeProcessor implements BatchCo
 
   public static class BaseHttpDownloader {
     private static final List<String> PROXY_SETTINGS = ImmutableList.of(
-        "http.proxyHost", "http.proxyPort", "http.nonProxyHosts",
-        "http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort");
+      "http.proxyHost", "http.proxyPort", "http.nonProxyHosts",
+      "http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort");
 
     private String userAgent;
 
-    public BaseHttpDownloader(Settings settings, String userAgent) {
+    public BaseHttpDownloader(Map<String, String> settings, String userAgent) {
       initProxy(settings);
       initUserAgent(userAgent);
     }
 
-    private void initProxy(Settings settings) {
+    private void initProxy(Map<String, String> settings) {
       propagateProxySystemProperties(settings);
       if (requiresProxyAuthentication(settings)) {
         registerProxyCredentials(settings);
@@ -172,20 +173,20 @@ public class HttpDownloader extends UriReader.SchemeProcessor implements BatchCo
       return Joiner.on(", ").join(descriptions);
     }
 
-    private void registerProxyCredentials(Settings settings) {
+    private void registerProxyCredentials(Map<String, String> settings) {
       Authenticator.setDefault(new ProxyAuthenticator(
-          settings.getString("http.proxyUser"),
-          settings.getString("http.proxyPassword")));
+        settings.get("http.proxyUser"),
+        settings.get("http.proxyPassword")));
     }
 
-    private boolean requiresProxyAuthentication(Settings settings) {
-      return settings.getString("http.proxyUser") != null;
+    private boolean requiresProxyAuthentication(Map<String, String> settings) {
+      return settings.containsKey("http.proxyUser");
     }
 
-    private void propagateProxySystemProperties(Settings settings) {
+    private void propagateProxySystemProperties(Map<String, String> settings) {
       for (String key : PROXY_SETTINGS) {
-        if (settings.getString(key) != null) {
-          System.setProperty(key, settings.getString(key));
+        if (settings.containsKey(key)) {
+          System.setProperty(key, settings.get(key));
         }
       }
     }
index 9ba5f005c2c22b08b776e83a82ef0e80110d722a..cf89bddff6bf665df427def0d96c328ca312e618 100644 (file)
@@ -34,17 +34,18 @@ class BatchBootstrapController < ApplicationController
   def properties
     require_parameters :project
 
-    json_properties=Property.find(:all, :conditions => ['user_id is null and resource_id is null']).map{|property| to_json_property(property)}
+    json_properties=Property.find(:all, :conditions => ['user_id is null and resource_id is null']).map { |property| to_json_property(property) }
 
     root_project = load_project()
     if root_project
       Project.find(:all, :select => 'id,kee', :conditions => ['enabled=? and (root_id=? or id=?)', true, root_project.id, root_project.id]).each do |project|
-        json_properties.concat(Property.find(:all, :conditions => ['user_id is null and resource_id=?', project.id]).map{|property| to_json_property(property, project.kee)})
+        json_properties.concat(Property.find(:all, :conditions => ['user_id is null and resource_id=?', project.id]).map { |property| to_json_property(property, project.kee) })
       end
     end
 
+    has_user_role=has_role?(:user, root_project)
     has_admin_role=has_role?(:admin, root_project)
-    json_properties=json_properties.select{|prop| allowed?(prop[:k], has_admin_role)}
+    json_properties=json_properties.select { |prop| allowed?(prop[:k], has_user_role, has_admin_role) }
 
     render :json => JSON(json_properties)
   end
@@ -63,7 +64,11 @@ class BatchBootstrapController < ApplicationController
     hash
   end
 
-  def allowed?(property_key, has_admin_role)
-    !property_key.end_with?('.secured') || has_admin_role
+  def allowed?(property_key, has_user_role, has_admin_role)
+    if property_key.end_with?('.secured')
+      property_key.include?('.license') ? has_user_role : has_admin_role
+    else
+      true
+    end
   end
 end
\ No newline at end of file
index 8f025b2b1ad47d9e23c515d8bc7687a21ae82641..905f2ef7ba5a0653ed548f48198ceb14585ca0f5 100644 (file)
@@ -67,14 +67,14 @@ import java.io.UnsupportedEncodingException;
 public class HttpClient4Connector extends Connector {
 
   private Host server;
-  private AbstractHttpClient client;
+  private DefaultHttpClient client;
 
   public HttpClient4Connector(Host server) {
     this.server = server;
     initClient();
   }
 
-  public HttpClient getHttpClient() {
+  public DefaultHttpClient getHttpClient() {
     return client;
   }
 
@@ -141,7 +141,7 @@ public class HttpClient4Connector extends Connector {
     }
   }
 
-  private BasicHttpContext createLocalContext(AbstractHttpClient client) {
+  private BasicHttpContext createLocalContext(DefaultHttpClient client) {
     BasicHttpContext localcontext = new BasicHttpContext();
 
     if (server.getUsername() != null) {