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
@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);
}
}
*/
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;
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;
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;
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;
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;
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;
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;
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;
*/
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;
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();
}
}
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;
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;
}
private void registerCoreComponents() {
- container.addSingleton(BatchSettings.class);
container.addSingleton(EmailSettings.class);
container.addSingleton(I18nManager.class);
container.addSingleton(RuleI18nManager.class);
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() {
}
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);
}
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();
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;
}
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;
// 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);
}
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);
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;
/**
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);
*/
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);
}
}
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;
+++ /dev/null
-/*
- * 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");
- }
- }
-}
--- /dev/null
+/*
+ * 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);
+ }
+}
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;
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;
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);
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;
*/
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;
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
* @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) {
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) {
--- /dev/null
+/*
+ * 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, "\"");
+ }
+}
+++ /dev/null
-/*
- * 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);
- }
-}
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;
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;
}
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;
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);
}
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 {
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;
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() {
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) {
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
-import org.sonar.batch.bootstrap.ServerClient;
import java.util.Date;
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");
import org.junit.Test;
import org.sonar.api.config.Settings;
-import org.sonar.batch.local.DryRunDatabase;
import java.util.Properties;
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;
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;
@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));
}
}
"{\"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");
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");
*/
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;
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
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");
}
}
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");
--- /dev/null
+/*
+ * 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();
+ }
+}
+++ /dev/null
-/*
- * 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");
- }
-}
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;
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;
public class JdbcDriverHolderTest {
- private ClassLoader initialThreadClassloader;
+ ClassLoader initialThreadClassloader;
@Before
public void before() {
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);
@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();
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");
- }
}
--- /dev/null
+/*
+ * 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");
+ }
+}
+++ /dev/null
-/*
- * 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();
- }
-}
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;
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");
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);
@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);
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);
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);
@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);
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;
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");
--- /dev/null
+/*
+ * 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 {
+}
* @since 3.4
*/
String PASSWORD = "sonar.password";
+
+ /**
+ * @since 3.4
+ */
+ String DRY_RUN = "sonar.dryRun";
}
+++ /dev/null
-/*
- * 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 {
-}
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;
+import java.util.Map;
/**
* This component downloads HTTP files
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
@Override
String[] getSupportedSchemes() {
- return new String[] {"http", "https"};
+ return new String[]{"http", "https"};
}
@Override
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);
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));
}
}
}
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
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
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;
}
}
}
- private BasicHttpContext createLocalContext(AbstractHttpClient client) {
+ private BasicHttpContext createLocalContext(DefaultHttpClient client) {
BasicHttpContext localcontext = new BasicHttpContext();
if (server.getUsername() != null) {