package org.sonar.ce.configuration;
import org.picocontainer.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
private final int workerCount;
- public CeConfigurationImpl(Settings settings) {
- String workerCountAsStr = settings.getString(CE_WORKERS_COUNT_PROPERTY);
+ public CeConfigurationImpl(Configuration config) {
+ String workerCountAsStr = config.get(CE_WORKERS_COUNT_PROPERTY).orElse(null);
if (workerCountAsStr == null || workerCountAsStr.isEmpty()) {
this.workerCount = DEFAULT_WORKER_COUNT;
} else {
return MessageException.of(format(
"value '%s' of property %s is invalid. It must an integer strictly greater than 0.",
workerCountAsStr,
- CE_WORKERS_COUNT_PROPERTY)
- );
+ CE_WORKERS_COUNT_PROPERTY));
}
@Override
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.MapSettings;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.MessageException;
import static java.lang.Math.abs;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
@Test
public void getWorkerCount_returns_1_when_worker_property_is_not_defined() {
- assertThat(new CeConfigurationImpl(settings).getWorkerCount()).isEqualTo(1);
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getWorkerCount()).isEqualTo(1);
}
@Test
public void getWorkerCount_returns_1_when_worker_property_is_empty() {
settings.setProperty(CE_WORKERS_COUNT_PROPERTY, "");
- assertThat(new CeConfigurationImpl(settings).getWorkerCount()).isEqualTo(1);
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getWorkerCount()).isEqualTo(1);
}
@Test
public void getWorkerCount_returns_1_when_worker_property_is_space_chars() {
settings.setProperty(CE_WORKERS_COUNT_PROPERTY, " \n ");
- assertThat(new CeConfigurationImpl(settings).getWorkerCount()).isEqualTo(1);
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getWorkerCount()).isEqualTo(1);
}
@Test
public void getWorkerCount_returns_1_when_worker_property_is_1() {
settings.setProperty(CE_WORKERS_COUNT_PROPERTY, 1);
- assertThat(new CeConfigurationImpl(settings).getWorkerCount()).isEqualTo(1);
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getWorkerCount()).isEqualTo(1);
}
@Test
int value = abs(new Random().nextInt()) + 2;
settings.setProperty(CE_WORKERS_COUNT_PROPERTY, value);
- assertThat(new CeConfigurationImpl(settings).getWorkerCount()).isEqualTo(value);
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getWorkerCount()).isEqualTo(value);
}
@Test
expectMessageException(value);
- new CeConfigurationImpl(settings);
+ new CeConfigurationImpl(settings.asConfig());
}
@Test
expectMessageException(value);
- new CeConfigurationImpl(settings);
+ new CeConfigurationImpl(settings.asConfig());
}
@Test
expectedException.expectMessage("value '" + value + "' of property " + CE_WORKERS_COUNT_PROPERTY + " is invalid. " +
"It must an integer strictly greater than 0");
- new CeConfigurationImpl(settings);
+ new CeConfigurationImpl(settings.asConfig());
}
private void expectMessageException(int value) {
@Test
public void getCleanCeTasksInitialDelay_returns_1() {
- assertThat(new CeConfigurationImpl(settings).getCleanCeTasksInitialDelay())
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getCleanCeTasksInitialDelay())
.isEqualTo(1L);
}
@Test
public void getCleanCeTasksDelay_returns_10() {
- assertThat(new CeConfigurationImpl(settings).getCleanCeTasksDelay())
+ assertThat(new CeConfigurationImpl(settings.asConfig()).getCleanCeTasksDelay())
.isEqualTo(10L);
}
}
import java.util.Set;
import java.util.concurrent.locks.Lock;
import org.picocontainer.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.process.ProcessProperties;
import static com.google.common.base.Preconditions.checkState;
@VisibleForTesting
protected HazelcastInstance hzInstance;
- public HazelcastClientWrapperImpl(Settings settings) {
- boolean clusterEnabled = settings.getBoolean(ProcessProperties.CLUSTER_ENABLED);
- String clusterName = settings.getString(ProcessProperties.CLUSTER_NAME);
- String clusterLocalEndPoint = settings.getString(ProcessProperties.CLUSTER_LOCALENDPOINT);
+ public HazelcastClientWrapperImpl(Configuration config) {
+ boolean clusterEnabled = config.getBoolean(ProcessProperties.CLUSTER_ENABLED).orElse(false);
+ String clusterName = config.get(ProcessProperties.CLUSTER_NAME).orElse(null);
+ String clusterLocalEndPoint = config.get(ProcessProperties.CLUSTER_LOCALENDPOINT).orElse(null);
checkState(clusterEnabled, "Cluster is not enabled");
checkState(isNotEmpty(clusterLocalEndPoint), "LocalEndPoint have not been set");
}
@Override
- public <K,V> Map<K,V> getReplicatedMap(String name) {
+ public <K, V> Map<K, V> getReplicatedMap(String name) {
return hzInstance.getReplicatedMap(name);
}
import org.sonar.ce.platform.ComputeEngineExtensionInstaller;
import org.sonar.ce.queue.CeQueueCleaner;
import org.sonar.ce.queue.PurgeCeActivities;
-import org.sonar.ce.settings.ProjectSettingsFactory;
+import org.sonar.ce.settings.ProjectConfigurationFactory;
import org.sonar.ce.taskprocessor.CeTaskProcessorModule;
import org.sonar.ce.user.CeUserSession;
import org.sonar.core.component.DefaultResourceTypes;
+import org.sonar.core.config.ConfigurationProvider;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.i18n.DefaultI18n;
import org.sonar.core.i18n.RuleI18nManager;
if (props.valueAsBoolean("sonar.cluster.enabled")) {
this.level4.add(
HazelcastClientWrapperImpl.class,
- CeDistributedInformationImpl.class
- );
+ CeDistributedInformationImpl.class);
} else {
this.level4.add(
- StandaloneCeDistributedInformation.class
- );
+ StandaloneCeDistributedInformation.class);
}
configureFromModules(this.level4);
ServerExtensionInstaller extensionInstaller = this.level4.getComponentByType(ServerExtensionInstaller.class);
Version apiVersion = ApiVersion.load(System2.INSTANCE);
return new Object[] {
ThreadLocalSettings.class,
+ new ConfigurationProvider(),
new SonarQubeVersion(apiVersion),
SonarRuntimeImpl.forSonarQube(ApiVersion.load(System2.INSTANCE), SonarQubeSide.COMPUTE_ENGINE),
CeProcessLogging.class,
CeTaskProcessorModule.class,
InternalPropertiesImpl.class,
- ProjectSettingsFactory.class,
+ ProjectConfigurationFactory.class,
// cleaning
CeCleaningModule.class
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.rules.Timeout;
import org.slf4j.LoggerFactory;
import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.process.NetworkUtils;
import org.sonar.process.ProcessProperties;
int port = NetworkUtils.getNextAvailablePort(InetAddress.getLoopbackAddress());
hzCluster = HazelcastTestHelper.createHazelcastCluster("cluster_with_client", port);
- Settings settings = createClusterSettings("cluster_with_client", "localhost:" + port);
- hzClient = new HazelcastClientWrapperImpl(settings);
+ MapSettings settings = createClusterSettings("cluster_with_client", "localhost:" + port);
+ hzClient = new HazelcastClientWrapperImpl(settings.asConfig());
}
@AfterClass
@Test
public void start_throws_ISE_if_LOCALENDPOINT_is_incorrect() {
- Settings settings = createClusterSettings("sonarqube", "\u4563\u1432\u1564");
- HazelcastClientWrapperImpl hzClient = new HazelcastClientWrapperImpl(settings);
+ MapSettings settings = createClusterSettings("sonarqube", "\u4563\u1432\u1564");
+ HazelcastClientWrapperImpl hzClient = new HazelcastClientWrapperImpl(settings.asConfig());
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Unable to connect to any address in the config! The following addresses were tried:");
@Test
public void constructor_throws_ISE_if_LOCALENDPOINT_is_empty() {
- Settings settings = createClusterSettings("sonarqube", "");
+ MapSettings settings = createClusterSettings("sonarqube", "");
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("LocalEndPoint have not been set");
- new HazelcastClientWrapperImpl(settings);
+ new HazelcastClientWrapperImpl(settings.asConfig());
}
@Test
public void constructor_throws_ISE_if_CLUSTER_ENABLED_is_false() {
- Settings settings = createClusterSettings("sonarqube", "localhost:9003");
+ MapSettings settings = createClusterSettings("sonarqube", "localhost:9003");
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, false);
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Cluster is not enabled");
- new HazelcastClientWrapperImpl(settings);
+ new HazelcastClientWrapperImpl(settings.asConfig());
}
@Test
public void constructor_throws_ISE_if_missing_CLUSTER_ENABLED() {
- Settings settings = createClusterSettings("sonarqube", "localhost:9003");
+ MapSettings settings = createClusterSettings("sonarqube", "localhost:9003");
settings.removeProperty(ProcessProperties.CLUSTER_ENABLED);
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Cluster is not enabled");
- new HazelcastClientWrapperImpl(settings);
+ new HazelcastClientWrapperImpl(settings.asConfig());
}
@Test
public void constructor_throws_ISE_if_missing_CLUSTER_NAME() {
- Settings settings = createClusterSettings("sonarqube", "localhost:9003");
+ MapSettings settings = createClusterSettings("sonarqube", "localhost:9003");
settings.removeProperty(ProcessProperties.CLUSTER_NAME);
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("sonar.cluster.name is missing");
- new HazelcastClientWrapperImpl(settings);
+ new HazelcastClientWrapperImpl(settings.asConfig());
}
@Test
public void constructor_throws_ISE_if_missing_CLUSTER_LOCALENDPOINT() {
- Settings settings = createClusterSettings("sonarqube", "localhost:9003");
+ MapSettings settings = createClusterSettings("sonarqube", "localhost:9003");
settings.removeProperty(ProcessProperties.CLUSTER_LOCALENDPOINT);
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("LocalEndPoint have not been set");
- new HazelcastClientWrapperImpl(settings);
+ new HazelcastClientWrapperImpl(settings.asConfig());
}
@Test
int port = NetworkUtils.getNextAvailablePort(InetAddress.getLoopbackAddress());
// Launch a fake Hazelcast instance
HazelcastInstance hzInstance = HazelcastTestHelper.createHazelcastCluster("client_must_connect_to_hazelcast", port);
- Settings settings = createClusterSettings("client_must_connect_to_hazelcast", "localhost:" + port);
+ MapSettings settings = createClusterSettings("client_must_connect_to_hazelcast", "localhost:" + port);
- HazelcastClientWrapperImpl hazelcastClientWrapperImpl = new HazelcastClientWrapperImpl(settings);
+ HazelcastClientWrapperImpl hazelcastClientWrapperImpl = new HazelcastClientWrapperImpl(settings.asConfig());
ClientListenerImpl clientListener = new ClientListenerImpl();
hzInstance.getClientService().addClientListener(clientListener);
try {
Set<String> setTest = new HashSet<>();
setTest.addAll(
- Arrays.asList(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10))
- );
- Map<String, Set<String>> replicatedMap = hzClient.getReplicatedMap("TEST1");
+ Arrays.asList(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10)));
+ Map<String, Set<String>> replicatedMap = hzClient.getReplicatedMap("TEST1");
replicatedMap.put("KEY1", ImmutableSet.copyOf(setTest));
assertThat(hzCluster.getReplicatedMap("TEST1"))
.containsOnlyKeys("KEY1");
mapTest.put("a", Arrays.asList("123", "456"));
hzCluster.getMap("TEST3").putAll(mapTest);
assertThat(hzClient.getMap("TEST3")).containsExactly(
- entry("a", Arrays.asList("123", "456"))
- );
+ entry("a", Arrays.asList("123", "456")));
} finally {
hzClient.stop();
}
}
assertThat(memoryAppender.events).isNotEmpty();
memoryAppender.events.stream().forEach(
- e -> assertThat(e.getLoggerName()).startsWith("com.hazelcast")
- );
+ e -> assertThat(e.getLoggerName()).startsWith("com.hazelcast"));
}
private class ClientListenerImpl implements ClientListener {
}
}
- private static Settings createClusterSettings(String name, String localEndPoint) {
- Properties properties = new Properties();
- properties.setProperty(ProcessProperties.CLUSTER_NAME, name);
- properties.setProperty(ProcessProperties.CLUSTER_LOCALENDPOINT, localEndPoint);
- properties.setProperty(ProcessProperties.CLUSTER_ENABLED, "true");
- return new MapSettings(new PropertyDefinitions()).addProperties(properties);
+ private static MapSettings createClusterSettings(String name, String localEndPoint) {
+ return new MapSettings(new PropertyDefinitions())
+ .setProperty(ProcessProperties.CLUSTER_NAME, name)
+ .setProperty(ProcessProperties.CLUSTER_LOCALENDPOINT, localEndPoint)
+ .setProperty(ProcessProperties.CLUSTER_ENABLED, "true");
}
private class MemoryAppender<E> extends AppenderBase<E> {
);
assertThat(picoContainer.getParent().getParent().getParent().getComponentAdapters()).hasSize(
COMPONENTS_IN_LEVEL_1_AT_CONSTRUCTION
- + 23 // level 1
+ + 24 // level 1
+ 46 // content of DaoModule
+ 3 // content of EsSearchModule
+ 58 // content of CorePropertyDefinitions
import org.dbunit.dataset.datatype.IDataTypeFactory;
import org.junit.AssumptionViolatedException;
import org.sonar.api.config.Settings;
-import org.sonar.api.config.MapSettings;
+import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.db.dialect.H2;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.sonar.api.config.Settings;
-import org.sonar.api.config.MapSettings;
+import org.sonar.api.config.internal.MapSettings;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.process.logging.LogbackHelper;
import java.util.NoSuchElementException;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.System2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.sonar.db.DaoDatabaseUtils.buildLikeValue;
-import static org.sonar.db.DaoDatabaseUtils.executeLargeInputs;
-import static org.sonar.db.DaoDatabaseUtils.executeLargeUpdates;
+import static org.sonar.db.DatabaseUtils.executeLargeInputs;
+import static org.sonar.db.DatabaseUtils.executeLargeUpdates;
import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER;
public class ComponentDao implements Dao {
import org.sonar.db.Dao;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.DbSession;
-import org.sonar.db.Pagination;
import org.sonar.db.component.ComponentMapper;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Date;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.time.DateUtils;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.System2;
import org.sonar.core.config.PurgeConstants;
this.disabledComponentUuids = disabledComponentUuids;
}
- public static PurgeConfiguration newDefaultPurgeConfiguration(Settings settings, IdUuidPair idUuidPair, Collection<String> disabledComponentUuids) {
+ public static PurgeConfiguration newDefaultPurgeConfiguration(Configuration config, IdUuidPair idUuidPair, Collection<String> disabledComponentUuids) {
String[] scopes = new String[] {Scopes.FILE};
- if (settings.getBoolean(PurgeConstants.PROPERTY_CLEAN_DIRECTORY)) {
+ if (config.getBoolean(PurgeConstants.PROPERTY_CLEAN_DIRECTORY).orElse(false)) {
scopes = new String[] {Scopes.DIRECTORY, Scopes.FILE};
}
- return new PurgeConfiguration(idUuidPair, scopes, settings.getInt(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES), System2.INSTANCE, disabledComponentUuids);
+ return new PurgeConfiguration(idUuidPair, scopes, config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES).get(), System2.INSTANCE, disabledComponentUuids);
}
public IdUuidPair rootProjectIdUuid() {
import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.List;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.db.purge.PurgeProfiler;
import org.sonar.db.purge.PurgeableAnalysisDto;
-import static org.sonar.core.util.stream.MoreCollectors.toList;
-
public class DefaultPeriodCleaner {
private static final Logger LOG = Loggers.get(DefaultPeriodCleaner.class);
this.profiler = profiler;
}
- public void clean(DbSession session, String rootUuid, Settings settings) {
- doClean(rootUuid, new Filters(settings).all(), session);
+ public void clean(DbSession session, String rootUuid, Configuration config) {
+ doClean(rootUuid, new Filters(config).all(), session);
}
@VisibleForTesting
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateUtils;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.core.config.PurgeConstants;
class Filters {
private final List<Filter> all = Lists.newArrayList();
- Filters(Settings settings) {
- Date dateToStartKeepingOneSnapshotByDay = getDateFromHours(settings, PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY);
- Date dateToStartKeepingOneSnapshotByWeek = getDateFromWeeks(settings, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK);
- Date dateToStartKeepingOneSnapshotByMonth = getDateFromWeeks(settings, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH);
- Date dateToStartDeletingAllSnapshots = getDateFromWeeks(settings, PurgeConstants.WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS);
+ Filters(Configuration config) {
+ Date dateToStartKeepingOneSnapshotByDay = getDateFromHours(config, PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY);
+ Date dateToStartKeepingOneSnapshotByWeek = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK);
+ Date dateToStartKeepingOneSnapshotByMonth = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH);
+ Date dateToStartDeletingAllSnapshots = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS);
all.add(new KeepOneFilter(dateToStartKeepingOneSnapshotByWeek, dateToStartKeepingOneSnapshotByDay, Calendar.DAY_OF_YEAR, "day"));
all.add(new KeepOneFilter(dateToStartKeepingOneSnapshotByMonth, dateToStartKeepingOneSnapshotByWeek, Calendar.WEEK_OF_YEAR, "week"));
all.add(new DeleteAllFilter(dateToStartDeletingAllSnapshots));
}
- static Date getDateFromWeeks(Settings settings, String propertyKey) {
- int weeks = settings.getInt(propertyKey);
+ static Date getDateFromWeeks(Configuration config, String propertyKey) {
+ int weeks = config.getInt(propertyKey).get();
return DateUtils.addWeeks(new Date(), -weeks);
}
- static Date getDateFromHours(Settings settings, String propertyKey) {
- int hours = settings.getInt(propertyKey);
+ static Date getDateFromHours(Configuration config, String propertyKey) {
+ int hours = config.getInt(propertyKey).get();
return DateUtils.addHours(new Date(), -hours);
}
import org.sonar.db.organization.OrganizationDto;
import static com.google.common.base.Preconditions.checkNotNull;
-import static java.util.Optional.*;
+import static java.util.Optional.ofNullable;
import static org.sonar.db.DatabaseUtils.executeLargeInputs;
public class RuleDao implements Dao {
import org.apache.ibatis.session.RowBounds;
import org.sonar.api.utils.System2;
import org.sonar.db.Dao;
-import org.sonar.db.DbSession;
import org.sonar.db.DaoDatabaseUtils;
+import org.sonar.db.DbSession;
import org.sonar.db.WildcardPosition;
import static org.sonar.db.DatabaseUtils.executeLargeInputs;
import org.junit.Test;
-import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newModuleDto;
-import static org.sonar.db.component.ComponentTesting.newProjectCopy;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
+import static org.sonar.db.component.ComponentTesting.newProjectCopy;
import static org.sonar.db.component.ComponentTesting.newSubView;
import static org.sonar.db.component.ComponentTesting.newView;
import static org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN;
*/
package org.sonar.db.duplication;
+import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import java.util.List;
-
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.Date;
import org.junit.Test;
-import org.sonar.api.config.Settings;
-import org.sonar.api.config.MapSettings;
+import org.sonar.api.config.PropertyDefinitions;
+import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.config.PurgeConstants;
+import org.sonar.core.config.PurgeProperties;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void do_not_delete_directory_by_default() {
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings(new PropertyDefinitions(PurgeProperties.all()));
settings.setProperty(PurgeConstants.PROPERTY_CLEAN_DIRECTORY, false);
settings.setProperty(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES, 5);
Date now = new Date();
- PurgeConfiguration underTest = PurgeConfiguration.newDefaultPurgeConfiguration(settings, new IdUuidPair(42L, "any-uuid"), Collections.emptyList());
+ PurgeConfiguration underTest = PurgeConfiguration.newDefaultPurgeConfiguration(settings.asConfig(), new IdUuidPair(42L, "any-uuid"), Collections.emptyList());
assertThat(underTest.scopesWithoutHistoricalData()).contains(Scopes.FILE)
.doesNotContain(Scopes.DIRECTORY);
@Test
public void delete_directory_if_in_settings() {
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings(new PropertyDefinitions(PurgeProperties.all()));
settings.setProperty(PurgeConstants.PROPERTY_CLEAN_DIRECTORY, true);
- PurgeConfiguration underTest = PurgeConfiguration.newDefaultPurgeConfiguration(settings, new IdUuidPair(42L, "any-uuid"), Collections.emptyList());
+ PurgeConfiguration underTest = PurgeConfiguration.newDefaultPurgeConfiguration(settings.asConfig(), new IdUuidPair(42L, "any-uuid"), Collections.emptyList());
assertThat(underTest.scopesWithoutHistoricalData()).contains(Scopes.DIRECTORY, Scopes.FILE);
}
import org.sonar.db.purge.PurgeProfiler;
import org.sonar.db.purge.PurgeableAnalysisDto;
-import static org.mockito.Mockito.anyListOf;
-import static org.mockito.Mockito.eq;
+import static org.mockito.Matchers.anyListOf;
+import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import org.sonar.db.DbTester;
import static java.util.Arrays.asList;
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class QProfileChangeDaoTest {
*/
package org.sonar.db.user;
-import static org.assertj.core.api.Assertions.assertThat;
-
import java.util.Arrays;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import static org.assertj.core.api.Assertions.assertThat;
+
public class UserDtoTest {
@Rule
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import org.apache.commons.io.IOUtils;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.DefaultProcessCommands;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
private final File ipcSharedDir;
- public CeHttpClient(Settings props) {
- this.ipcSharedDir = new File(props.getString(PROPERTY_SHARED_PATH));
+ public CeHttpClient(Configuration config) {
+ this.ipcSharedDir = new File(config.get(PROPERTY_SHARED_PATH).get());
}
/**
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program 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.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.ce.settings;
+
+import org.sonar.api.ce.ComputeEngineSide;
+import org.sonar.api.config.Configuration;
+import org.sonar.api.config.Settings;
+import org.sonar.api.config.internal.ConfigurationBridge;
+import org.sonar.db.DbClient;
+
+@ComputeEngineSide
+public class ProjectConfigurationFactory {
+
+ private final Settings globalSettings;
+ private final DbClient dbClient;
+
+ public ProjectConfigurationFactory(Settings globalSettings, DbClient dbClient) {
+ this.globalSettings = globalSettings;
+ this.dbClient = dbClient;
+ }
+
+ public Configuration newProjectConfiguration(String projectKey) {
+ Settings projectSettings = new ProjectSettings(globalSettings);
+ dbClient.propertiesDao()
+ .selectProjectProperties(projectKey)
+ .forEach(property -> projectSettings.setProperty(property.getKey(), property.getValue()));
+ return new ConfigurationBridge(projectSettings);
+ }
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program 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.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.ce.settings;
-
-import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
-import org.sonar.db.DbClient;
-
-@ComputeEngineSide
-public class ProjectSettingsFactory {
-
- private final Settings globalSettings;
- private final DbClient dbClient;
-
- public ProjectSettingsFactory(Settings globalSettings, DbClient dbClient) {
- this.globalSettings = globalSettings;
- this.dbClient = dbClient;
- }
-
- public Settings newProjectSettings(String projectKey) {
- Settings projectSettings = new ProjectSettings(globalSettings);
- dbClient.propertiesDao()
- .selectProjectProperties(projectKey)
- .forEach(property -> projectSettings.setProperty(property.getKey(), property.getValue()));
- return projectSettings;
- }
-}
package org.sonar.server.app;
import java.io.File;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.process.DefaultProcessCommands;
import org.sonar.process.ProcessCommands;
-import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH;
public class ProcessCommandWrapperImpl implements ProcessCommandWrapper {
- private final Settings settings;
+ private final Configuration config;
- public ProcessCommandWrapperImpl(Settings settings) {
- this.settings = settings;
+ public ProcessCommandWrapperImpl(Configuration config) {
+ this.config = config;
}
@Override
}
private int nonNullAsInt(String key) {
- String s = settings.getString(key);
- checkArgument(s != null, "Property %s is not set", key);
- return Integer.parseInt(s);
+ return config.getInt(key).orElseThrow(() -> new IllegalArgumentException(String.format("Property %s is not set", key)));
}
private File nonNullValueAsFile(String key) {
- String s = settings.getString(key);
- checkArgument(s != null, "Property %s is not set", key);
- return new File(s);
+ return new File(config.get(key).orElseThrow(() -> new IllegalArgumentException(String.format("Property %s is not set", key))));
}
}
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
private final int sessionTimeoutInSeconds;
private final JwtCsrfVerifier jwtCsrfVerifier;
- public JwtHttpHandler(System2 system2, DbClient dbClient, Settings settings, JwtSerializer jwtSerializer, JwtCsrfVerifier jwtCsrfVerifier) {
+ public JwtHttpHandler(System2 system2, DbClient dbClient, Configuration config, JwtSerializer jwtSerializer, JwtCsrfVerifier jwtCsrfVerifier) {
this.jwtSerializer = jwtSerializer;
this.dbClient = dbClient;
this.system2 = system2;
- this.sessionTimeoutInSeconds = getSessionTimeoutInSeconds(settings);
+ this.sessionTimeoutInSeconds = getSessionTimeoutInSeconds(config);
this.jwtCsrfVerifier = jwtCsrfVerifier;
}
}
}
- private static int getSessionTimeoutInSeconds(Settings settings) {
- int minutes;
- if (settings.hasKey(SESSION_TIMEOUT_IN_MINUTES_PROPERTY)) {
- minutes = settings.getInt(SESSION_TIMEOUT_IN_MINUTES_PROPERTY);
- checkArgument(minutes > 0, "Property %s must be strictly positive. Got %s", SESSION_TIMEOUT_IN_MINUTES_PROPERTY, minutes);
- } else {
- minutes = SESSION_TIMEOUT_DEFAULT_VALUE_IN_MINUTES;
- }
+ private static int getSessionTimeoutInSeconds(Configuration config) {
+ int minutes = config.getInt(SESSION_TIMEOUT_IN_MINUTES_PROPERTY).orElse(SESSION_TIMEOUT_DEFAULT_VALUE_IN_MINUTES);
+ checkArgument(minutes > 0, "Property %s must be strictly positive. Got %s", SESSION_TIMEOUT_IN_MINUTES_PROPERTY, minutes);
checkArgument(minutes <= MAX_SESSION_TIMEOUT_IN_MINUTES, "Property %s must not be greater than 3 months (%s minutes). Got %s minutes",
SESSION_TIMEOUT_IN_MINUTES_PROPERTY, MAX_SESSION_TIMEOUT_IN_MINUTES, minutes);
return minutes * 60;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.sonar.api.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.jsonwebtoken.impl.crypto.MacProvider.generateKey;
import static java.util.Objects.requireNonNull;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
/**
* This class can be used to encode or decode a JWT token
private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
- private final Settings settings;
+ private final Configuration config;
private final System2 system2;
private final UuidFactory uuidFactory;
private SecretKey secretKey;
- public JwtSerializer(Settings settings, System2 system2, UuidFactory uuidFactory) {
- this.settings = settings;
+ public JwtSerializer(Configuration config, System2 system2, UuidFactory uuidFactory) {
+ this.config = config;
this.system2 = system2;
this.uuidFactory = uuidFactory;
}
@Override
public void start() {
- String encodedKey = settings.getString(SECRET_KEY_PROPERTY);
- if (encodedKey == null) {
- this.secretKey = generateSecretKey();
+ Optional<String> encodedKey = config.get(SECRET_KEY_PROPERTY);
+ if (encodedKey.isPresent()) {
+ this.secretKey = decodeSecretKeyProperty(encodedKey.get());
} else {
- this.secretKey = decodeSecretKeyProperty(encodedKey);
+ this.secretKey = generateSecretKey();
}
}
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.sonar.api.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.security.Authenticator;
import org.sonar.api.security.ExternalGroupsProvider;
import org.sonar.api.security.ExternalUsersProvider;
import org.sonar.api.utils.log.Loggers;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.user.SecurityRealmFactory;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.trimToNull;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY;
public class RealmAuthenticator implements Startable {
private static final Logger LOG = Loggers.get(RealmAuthenticator.class);
- private final Settings settings;
+ private final Configuration config;
private final SecurityRealmFactory securityRealmFactory;
private final UserIdentityAuthenticator userIdentityAuthenticator;
private final AuthenticationEvent authenticationEvent;
private ExternalUsersProvider externalUsersProvider;
private ExternalGroupsProvider externalGroupsProvider;
- public RealmAuthenticator(Settings settings, SecurityRealmFactory securityRealmFactory,
+ public RealmAuthenticator(Configuration config, SecurityRealmFactory securityRealmFactory,
UserIdentityAuthenticator userIdentityAuthenticator, AuthenticationEvent authenticationEvent) {
- this.settings = settings;
+ this.config = config;
this.securityRealmFactory = securityRealmFactory;
this.userIdentityAuthenticator = userIdentityAuthenticator;
this.authenticationEvent = authenticationEvent;
}
private String getLogin(String userLogin) {
- if (settings.getBoolean("sonar.authenticator.downcase")) {
+ if (config.getBoolean("sonar.authenticator.downcase").orElse(false)) {
return userLogin.toLowerCase(Locale.ENGLISH);
}
return userLogin;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.sonar.api.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.utils.log.Loggers;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.exceptions.BadRequestException;
-import static org.apache.commons.lang.StringUtils.defaultIfBlank;
import static org.apache.commons.lang.time.DateUtils.addMinutes;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY;
public class SsoAuthenticator implements Startable {
REFRESH_INTERVAL_PARAM, REFRESH_INTERVAL_DEFAULT_VALUE);
private final System2 system2;
- private final Settings settings;
+ private final Configuration config;
private final UserIdentityAuthenticator userIdentityAuthenticator;
private final JwtHttpHandler jwtHttpHandler;
private final AuthenticationEvent authenticationEvent;
private boolean enabled = false;
private Map<String, String> settingsByKey = new HashMap<>();
- public SsoAuthenticator(System2 system2, Settings settings, UserIdentityAuthenticator userIdentityAuthenticator,
+ public SsoAuthenticator(System2 system2, Configuration config, UserIdentityAuthenticator userIdentityAuthenticator,
JwtHttpHandler jwtHttpHandler, AuthenticationEvent authenticationEvent) {
this.system2 = system2;
- this.settings = settings;
+ this.config = config;
this.userIdentityAuthenticator = userIdentityAuthenticator;
this.jwtHttpHandler = jwtHttpHandler;
this.authenticationEvent = authenticationEvent;
@Override
public void start() {
- if (settings.getBoolean(ENABLE_PARAM)) {
+ if (config.getBoolean(ENABLE_PARAM).orElse(false)) {
LOG.info("SSO Authentication enabled");
enabled = true;
DEFAULT_VALUES_BY_SETTING_KEYS.entrySet()
- .forEach(entry -> settingsByKey.put(entry.getKey(), defaultIfBlank(settings.getString(entry.getKey()), DEFAULT_VALUES_BY_SETTING_KEYS.get(entry.getKey()))));
+ .forEach(entry -> settingsByKey.put(entry.getKey(), config.get(entry.getKey()).orElse(DEFAULT_VALUES_BY_SETTING_KEYS.get(entry.getKey()))));
}
}
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
+import org.sonar.api.web.ServletFilter.UrlPattern;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
+import org.sonar.server.authentication.event.AuthenticationEvent.Method;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.user.ThreadLocalUserSession;
import org.sonar.server.user.UserSession;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY;
-import static org.sonar.api.web.ServletFilter.UrlPattern;
import static org.sonar.api.web.ServletFilter.UrlPattern.Builder.staticResourcePatterns;
import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Method;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.authentication.ws.LoginAction.LOGIN_URL;
import static org.sonar.server.authentication.ws.LogoutAction.LOGOUT_URL;
import static org.sonar.server.authentication.ws.ValidateAction.VALIDATE_URL;
.excludes(SKIPPED_URLS)
.build();
- private final Settings settings;
+ private final Configuration config;
private final JwtHttpHandler jwtHttpHandler;
private final BasicAuthenticator basicAuthenticator;
private final SsoAuthenticator ssoAuthenticator;
private final AuthenticationEvent authenticationEvent;
private final UserSessionFactory userSessionFactory;
- public UserSessionInitializer(Settings settings, JwtHttpHandler jwtHttpHandler, BasicAuthenticator basicAuthenticator,
+ public UserSessionInitializer(Configuration config, JwtHttpHandler jwtHttpHandler, BasicAuthenticator basicAuthenticator,
SsoAuthenticator ssoAuthenticator, ThreadLocalUserSession threadLocalSession, AuthenticationEvent authenticationEvent,
UserSessionFactory userSessionFactory) {
- this.settings = settings;
+ this.config = config;
this.jwtHttpHandler = jwtHttpHandler;
this.basicAuthenticator = basicAuthenticator;
this.ssoAuthenticator = ssoAuthenticator;
threadLocalSession.set(session);
request.setAttribute(ACCESS_LOG_LOGIN, session.getLogin());
} else {
- if (settings.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY)) {
+ if (config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(false)) {
throw AuthenticationException.newBuilder()
.setSource(Source.local(Method.BASIC))
.setMessage("User must be authenticated")
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.api.web.ServletFilter;
private static final String VALIDATE_ACTION = "validate";
public static final String VALIDATE_URL = "/" + AUTHENTICATION_CONTROLLER + "/" + VALIDATE_ACTION;
- private final Settings settings;
+ private final Configuration config;
private final JwtHttpHandler jwtHttpHandler;
private final BasicAuthenticator basicAuthenticator;
- public ValidateAction(Settings settings, BasicAuthenticator basicAuthenticator, JwtHttpHandler jwtHttpHandler) {
- this.settings = settings;
+ public ValidateAction(Configuration config, BasicAuthenticator basicAuthenticator, JwtHttpHandler jwtHttpHandler) {
+ this.config = config;
this.basicAuthenticator = basicAuthenticator;
this.jwtHttpHandler = jwtHttpHandler;
}
if (user.isPresent()) {
return true;
}
- return !settings.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY);
+ return !config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(false);
} catch (AuthenticationException e) {
return false;
}
*/
package org.sonar.server.component.index;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.DefaultIndexSettingsElement;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
static final DefaultIndexSettingsElement[] NAME_ANALYZERS = {SORTABLE_ANALYZER, SEARCH_PREFIX_ANALYZER, SEARCH_PREFIX_CASE_INSENSITIVE_ANALYZER, SEARCH_GRAMS_ANALYZER};
- private final Settings settings;
+ private final Configuration config;
- public ComponentIndexDefinition(Settings settings) {
- this.settings = settings;
+ public ComponentIndexDefinition(Configuration config) {
+ this.config = config;
}
@Override
public void define(IndexDefinitionContext context) {
NewIndex index = context.create(INDEX_TYPE_COMPONENT.getIndex());
index.refreshHandledByIndexer();
- index.configureShards(settings, DEFAULT_NUMBER_OF_SHARDS);
+ index.configureShards(config, DEFAULT_NUMBER_OF_SHARDS);
NewIndex.NewIndexType mapping = index.createType(INDEX_TYPE_COMPONENT.getType())
.requireProjectAuthorization();
import java.util.Collection;
import org.sonar.api.CoreProperties;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.TimeUtils;
import org.sonar.api.utils.log.Logger;
this.purgeListener = purgeListener;
}
- public ProjectCleaner purge(DbSession session, IdUuidPair idUuidPair, Settings projectSettings, Collection<String> disabledComponentUuids) {
+ public ProjectCleaner purge(DbSession session, IdUuidPair idUuidPair, Configuration projectConfig, Collection<String> disabledComponentUuids) {
long start = System.currentTimeMillis();
profiler.reset();
- PurgeConfiguration configuration = newDefaultPurgeConfiguration(projectSettings, idUuidPair, disabledComponentUuids);
+ PurgeConfiguration configuration = newDefaultPurgeConfiguration(projectConfig, idUuidPair, disabledComponentUuids);
- cleanHistoricalData(session, configuration.rootProjectIdUuid().getUuid(), projectSettings);
+ cleanHistoricalData(session, configuration.rootProjectIdUuid().getUuid(), projectConfig);
doPurge(session, configuration);
session.commit();
- logProfiling(start, projectSettings);
+ logProfiling(start, projectConfig);
return this;
}
- private void logProfiling(long start, Settings settings) {
- if (settings.getBoolean(CoreProperties.PROFILING_LOG_PROPERTY)) {
+ private void logProfiling(long start, Configuration config) {
+ if (config.getBoolean(CoreProperties.PROFILING_LOG_PROPERTY).orElse(false)) {
long duration = System.currentTimeMillis() - start;
LOG.info("\n -------- Profiling for purge: " + TimeUtils.formatDuration(duration) + " --------\n");
profiler.dump(duration, LOG);
}
}
- private void cleanHistoricalData(DbSession session, String rootUuid, Settings settings) {
+ private void cleanHistoricalData(DbSession session, String rootUuid, Configuration config) {
try {
- periodCleaner.clean(session, rootUuid, settings);
+ periodCleaner.clean(session, rootUuid, config);
} catch (Exception e) {
// purge errors must no fail the batch
LOG.error("Fail to clean historical data [uuid=" + rootUuid + "]", e);
import org.sonar.api.ce.measure.Component;
import org.sonar.api.ce.measure.Issue;
import org.sonar.api.ce.measure.Measure;
+import org.sonar.api.ce.measure.MeasureComputer.MeasureComputerContext;
+import org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition;
import org.sonar.api.ce.measure.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.core.issue.DefaultIssue;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.server.computation.task.projectanalysis.measure.MeasureRepository;
import org.sonar.server.computation.task.projectanalysis.metric.Metric;
import org.sonar.server.computation.task.projectanalysis.metric.MetricRepository;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.api.ce.measure.MeasureComputer.MeasureComputerContext;
-import static org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition;
import static org.sonar.server.computation.task.projectanalysis.measure.Measure.newMeasureBuilder;
public class MeasureComputerContextImpl implements MeasureComputerContext {
- private final SettingsRepository settings;
+ private final ConfigurationRepository config;
private final MeasureRepository measureRepository;
private final MetricRepository metricRepository;
private MeasureComputerDefinition definition;
private Set<String> allowedMetrics;
- public MeasureComputerContextImpl(org.sonar.server.computation.task.projectanalysis.component.Component component, SettingsRepository settings,
+ public MeasureComputerContextImpl(org.sonar.server.computation.task.projectanalysis.component.Component component, ConfigurationRepository config,
MeasureRepository measureRepository, MetricRepository metricRepository, ComponentIssuesRepository componentIssuesRepository) {
- this.settings = settings;
+ this.config = config;
this.internalComponent = component;
this.measureRepository = measureRepository;
this.metricRepository = metricRepository;
@Override
@CheckForNull
public String getString(String key) {
- return getComponentSettings().getString(key);
+ return getComponentSettings().get(key).orElse(null);
}
@Override
};
}
- private org.sonar.api.config.Settings getComponentSettings() {
- return settings.getSettings(internalComponent);
+ private Configuration getComponentSettings() {
+ return config.getConfiguration(internalComponent);
}
@Override
component.getKey(),
Component.Type.valueOf(component.getType().name()),
component.getType() == org.sonar.server.computation.task.projectanalysis.component.Component.Type.FILE
- ? new ComponentImpl.FileAttributesImpl(component.getFileAttributes().getLanguageKey(), component.getFileAttributes().isUnitTest()) : null);
+ ? new ComponentImpl.FileAttributesImpl(component.getFileAttributes().getLanguageKey(), component.getFileAttributes().isUnitTest())
+ : null);
}
- private class ComponentToMeasure implements Function<org.sonar.server.computation.task.projectanalysis.component.Component,
- Optional<org.sonar.server.computation.task.projectanalysis.measure.Measure>> {
+ private class ComponentToMeasure
+ implements Function<org.sonar.server.computation.task.projectanalysis.component.Component, Optional<org.sonar.server.computation.task.projectanalysis.measure.Measure>> {
private final Metric metric;
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program 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.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.computation.task.projectanalysis.component;
+
+import org.sonar.api.config.Configuration;
+
+/**
+ * Repository of component settings.
+ */
+public interface ConfigurationRepository {
+ /**
+ * Returns the configuration for the specified Component.
+ */
+ Configuration getConfiguration(Component component);
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program 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.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.computation.task.projectanalysis.component;
+
+import java.util.Collection;
+import java.util.Map;
+import org.sonar.api.config.Configuration;
+import org.sonar.ce.settings.ProjectConfigurationFactory;
+import org.sonar.server.util.cache.CacheLoader;
+import org.sonar.server.util.cache.MemoryCache;
+
+/**
+ * Repository of component settings implementation based on a memory cache.
+ */
+public class ConfigurationRepositoryImpl implements ConfigurationRepository {
+
+ private final ProjectConfigurationFactory projectConfigurationFactory;
+ private final MemoryCache<String, Configuration> cache = new MemoryCache<>(new CacheLoader<String, Configuration>() {
+ @Override
+ public Configuration load(String key) {
+ return projectConfigurationFactory.newProjectConfiguration(key);
+ }
+
+ @Override
+ public Map<String, Configuration> loadAll(Collection<? extends String> keys) {
+ throw new UnsupportedOperationException("loadAll is not supported");
+ }
+ });
+
+ public ConfigurationRepositoryImpl(ProjectConfigurationFactory projectSettingsFactory) {
+ this.projectConfigurationFactory = projectSettingsFactory;
+ }
+
+ @Override
+ public Configuration getConfiguration(Component component) {
+ return cache.get(component.getKey());
+ }
+
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program 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.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.computation.task.projectanalysis.component;
-
-import org.sonar.api.config.Settings;
-
-/**
- * Repository of component settings.
- */
-public interface SettingsRepository {
- /**
- * Returns the settings for the specified Component.
- */
- Settings getSettings(Component component);
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program 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.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.computation.task.projectanalysis.component;
-
-import java.util.Collection;
-import java.util.Map;
-import org.sonar.api.config.Settings;
-import org.sonar.ce.settings.ProjectSettingsFactory;
-import org.sonar.server.util.cache.CacheLoader;
-import org.sonar.server.util.cache.MemoryCache;
-
-/**
- * Repository of component settings implementation based on a memory cache.
- */
-public class SettingsRepositoryImpl implements SettingsRepository {
-
- private final ProjectSettingsFactory projectSettingsFactory;
- private final MemoryCache<String, Settings> cache = new MemoryCache<>(new CacheLoader<String, Settings>() {
- @Override
- public Settings load(String key) {
- return projectSettingsFactory.newProjectSettings(key);
- }
-
- @Override
- public Map<String, Settings> loadAll(Collection<? extends String> keys) {
- throw new UnsupportedOperationException("loadAll is not supported");
- }
- });
-
- public SettingsRepositoryImpl(ProjectSettingsFactory projectSettingsFactory) {
- this.projectSettingsFactory = projectSettingsFactory;
- }
-
- @Override
- public Settings getSettings(Component component){
- return cache.get(component.getKey());
- }
-
-}
import org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderImpl;
import org.sonar.server.computation.task.projectanalysis.component.DbIdsRepositoryImpl;
import org.sonar.server.computation.task.projectanalysis.component.DisabledComponentsHolderImpl;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepositoryImpl;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepositoryImpl;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderImpl;
import org.sonar.server.computation.task.projectanalysis.duplication.CrossProjectDuplicationStatusHolderImpl;
import org.sonar.server.computation.task.projectanalysis.duplication.DuplicationRepositoryImpl;
LanguageRepositoryImpl.class,
MeasureRepositoryImpl.class,
EventRepositoryImpl.class,
- SettingsRepositoryImpl.class,
+ ConfigurationRepositoryImpl.class,
DbIdsRepositoryImpl.class,
DisabledComponentsHolderImpl.class,
QualityGateServiceImpl.class,
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.duplications.block.Block;
private static final int MAX_CLONE_GROUP_PER_FILE = 100;
private static final int MAX_CLONE_PART_PER_GROUP = 100;
- private final Settings settings;
+ private final Configuration config;
private final DuplicationRepository duplicationRepository;
private Map<String, NumberOfUnitsNotLessThan> numberOfUnitsByLanguage = new HashMap<>();
- public IntegrateCrossProjectDuplications(Settings settings, DuplicationRepository duplicationRepository) {
- this.settings = settings;
+ public IntegrateCrossProjectDuplications(Configuration config, DuplicationRepository duplicationRepository) {
+ this.config = config;
this.duplicationRepository = duplicationRepository;
}
if (!Iterables.isEmpty(duplicates)) {
duplicationRepository.add(
file,
- new Duplication(new TextBlock(originPart.getStartLine(), originPart.getEndLine()), duplicates)
- );
+ new Duplication(new TextBlock(originPart.getStartLine(), originPart.getEndLine()), duplicates));
}
}
if (languageKey.equalsIgnoreCase(JAVA_KEY)) {
return 0;
}
- int minimumTokens = settings.getInt("sonar.cpd." + languageKey + ".minimumTokens");
- if (minimumTokens == 0) {
- return 100;
- }
- return minimumTokens;
+ return config.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100);
}
private static class NumberOfUnitsNotLessThan implements Predicate<CloneGroup> {
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolder;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import static org.sonar.api.CoreProperties.DEFAULT_ISSUE_ASSIGNEE;
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
- private final SettingsRepository settingsRepository;
+ private final ConfigurationRepository configRepository;
private final AnalysisMetadataHolder analysisMetadataHolder;
private boolean loaded = false;
private String login = null;
- public DefaultAssignee(DbClient dbClient, TreeRootHolder treeRootHolder, SettingsRepository settingsRepository, AnalysisMetadataHolder analysisMetadataHolder) {
+ public DefaultAssignee(DbClient dbClient, TreeRootHolder treeRootHolder, ConfigurationRepository configRepository, AnalysisMetadataHolder analysisMetadataHolder) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
- this.settingsRepository = settingsRepository;
+ this.configRepository = configRepository;
this.analysisMetadataHolder = analysisMetadataHolder;
}
if (loaded) {
return login;
}
- String configuredLogin = settingsRepository.getSettings(treeRootHolder.getRoot()).getString(DEFAULT_ISSUE_ASSIGNEE);
+ String configuredLogin = configRepository.getConfiguration(treeRootHolder.getRoot()).get(DEFAULT_ISSUE_ASSIGNEE).orElse(null);
if (!Strings.isNullOrEmpty(configuredLogin) && isValidLogin(configuredLogin)) {
this.login = configuredLogin;
}
import java.util.Iterator;
import java.util.List;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.computation.task.projectanalysis.component.Component;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
-import static org.apache.commons.lang.StringUtils.defaultIfBlank;
import static org.sonar.core.config.IssueExclusionProperties.PATTERNS_MULTICRITERIA_EXCLUSION_KEY;
import static org.sonar.core.config.IssueExclusionProperties.PATTERNS_MULTICRITERIA_INCLUSION_KEY;
import static org.sonar.core.config.IssueExclusionProperties.RESOURCE_KEY;
private final List<IssuePattern> exclusionPatterns;
private final List<IssuePattern> inclusionPatterns;
- public IssueFilter(TreeRootHolder treeRootHolder, SettingsRepository settingsRepository) {
- Settings settings = settingsRepository.getSettings(treeRootHolder.getRoot());
- this.exclusionPatterns = loadPatterns(PATTERNS_MULTICRITERIA_EXCLUSION_KEY, settings);
- this.inclusionPatterns = loadPatterns(PATTERNS_MULTICRITERIA_INCLUSION_KEY, settings);
+ public IssueFilter(TreeRootHolder treeRootHolder, ConfigurationRepository configRepository) {
+ Configuration config = configRepository.getConfiguration(treeRootHolder.getRoot());
+ this.exclusionPatterns = loadPatterns(PATTERNS_MULTICRITERIA_EXCLUSION_KEY, config);
+ this.inclusionPatterns = loadPatterns(PATTERNS_MULTICRITERIA_INCLUSION_KEY, config);
}
public boolean accept(DefaultIssue issue, Component component) {
}
}
- private static List<IssuePattern> loadPatterns(String propertyKey, Settings settings) {
+ private static List<IssuePattern> loadPatterns(String propertyKey, Configuration settings) {
List<IssuePattern> patterns = new ArrayList<>();
- String patternConf = defaultIfBlank(settings.getString(propertyKey), "");
+ String patternConf = settings.get(propertyKey).orElse("");
for (String id : Splitter.on(",").omitEmptyStrings().split(patternConf)) {
String propPrefix = propertyKey + "." + id + ".";
- String componentPathPattern = settings.getString(propPrefix + RESOURCE_KEY);
+ String componentPathPattern = settings.get(propPrefix + RESOURCE_KEY).orElse(null);
checkArgument(!isNullOrEmpty(componentPathPattern), format("File path pattern cannot be empty. Please check '%s' settings", propertyKey));
- String ruleKeyPattern = settings.getString(propPrefix + RULE_KEY);
+ String ruleKeyPattern = settings.get(propPrefix + RULE_KEY).orElse(null);
checkArgument(!isNullOrEmpty(ruleKeyPattern), format("Rule key pattern cannot be empty. Please check '%s' settings", propertyKey));
patterns.add(new IssuePattern(componentPathPattern, ruleKeyPattern));
}
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.server.computation.task.projectanalysis.component.CrawlerDepthLimit;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.server.computation.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.server.computation.task.projectanalysis.api.measurecomputer.MeasureComputerContextImpl;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
- private final SettingsRepository settings;
+ private final ConfigurationRepository settings;
private final MeasureComputersHolder measureComputersHolder;
private final ComponentIssuesRepository componentIssuesRepository;
- public MeasureComputersVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, SettingsRepository settings,
+ public MeasureComputersVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, ConfigurationRepository settings,
MeasureComputersHolder measureComputersHolder, ComponentIssuesRepository componentIssuesRepository) {
super(CrawlerDepthLimit.reportMaxDepth(FILE).withViewsMaxDepth(SUBVIEW), POST_ORDER);
this.metricRepository = metricRepository;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import static java.lang.String.format;
public class RatingSettings {
- private final Settings settings;
+ private final Configuration config;
private final Map<String, LanguageSpecificConfiguration> languageSpecificConfigurationByLanguageKey;
- public RatingSettings(Settings settings) {
- this.settings = settings;
- this.languageSpecificConfigurationByLanguageKey = buildLanguageSpecificConfigurationByLanguageKey(settings);
+ public RatingSettings(Configuration config) {
+ this.config = config;
+ this.languageSpecificConfigurationByLanguageKey = buildLanguageSpecificConfigurationByLanguageKey(config);
}
- private static Map<String, LanguageSpecificConfiguration> buildLanguageSpecificConfigurationByLanguageKey(Settings settings) {
+ private static Map<String, LanguageSpecificConfiguration> buildLanguageSpecificConfigurationByLanguageKey(Configuration config) {
ImmutableMap.Builder<String, LanguageSpecificConfiguration> builder = ImmutableMap.builder();
- String[] languageConfigIndexes = settings.getStringArray(LANGUAGE_SPECIFIC_PARAMETERS);
+ String[] languageConfigIndexes = config.getStringArray(LANGUAGE_SPECIFIC_PARAMETERS);
for (String languageConfigIndex : languageConfigIndexes) {
String languagePropertyKey = LANGUAGE_SPECIFIC_PARAMETERS + "." + languageConfigIndex + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY;
- String languageKey = settings.getString(languagePropertyKey);
- if (languageKey == null) {
- throw MessageException.of("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " +
- "Contact your administrator to update this configuration in the global administration section of SonarQube.");
- }
- builder.put(languageKey, LanguageSpecificConfiguration.create(settings, languageConfigIndex));
+ String languageKey = config.get(languagePropertyKey)
+ .orElseThrow(() -> MessageException.of("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " +
+ "Contact your administrator to update this configuration in the global administration section of SonarQube."));
+ builder.put(languageKey, LanguageSpecificConfiguration.create(config, languageConfigIndex));
}
return builder.build();
}
public RatingGrid getRatingGrid() {
try {
- String[] ratingGrades = settings.getStringArray(RATING_GRID);
+ String[] ratingGrades = config.getStringArray(RATING_GRID);
double[] grid = new double[4];
for (int i = 0; i < 4; i++) {
grid[i] = Double.parseDouble(ratingGrades[i]);
} catch (Exception e) {
throw new IllegalArgumentException("The rating grid is incorrect. Expected something similar to '"
+ RATING_GRID_DEF_VALUES + "' and got '"
- + settings.getString(RATING_GRID) + "'", e);
+ + config.get(RATING_GRID).get() + "'", e);
}
}
private long getDefaultDevelopmentCost() {
try {
- return Long.parseLong(settings.getString(DEVELOPMENT_COST));
+ return Long.parseLong(config.get(DEVELOPMENT_COST).get());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The value of the development cost property '" + DEVELOPMENT_COST
- + "' is incorrect. Expected long but got '" + settings.getString(DEVELOPMENT_COST) + "'", e);
+ + "' is incorrect. Expected long but got '" + config.get(DEVELOPMENT_COST).get() + "'", e);
}
}
this.metricKey = metricKey;
}
- static LanguageSpecificConfiguration create(Settings settings, String configurationId) {
+ static LanguageSpecificConfiguration create(Configuration config, String configurationId) {
String configurationPrefix = LANGUAGE_SPECIFIC_PARAMETERS + "." + configurationId + ".";
- String language = settings.getString(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY);
- String manDays = settings.getString(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY);
- String metric = settings.getString(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY);
+ String language = config.get(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY).orElse(null);
+ String manDays = config.get(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY).orElse(null);
+ String metric = config.get(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY).orElse(null);
return new LanguageSpecificConfiguration(language, manDays, metric);
}
import com.google.common.base.Optional;
import javax.annotation.CheckForNull;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.server.computation.task.projectanalysis.component.Component;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.server.computation.task.projectanalysis.period.Period;
public class LoadPeriodsStep implements ComputationStep {
private final DbClient dbClient;
- private final SettingsRepository settingsRepository;
+ private final ConfigurationRepository configRepository;
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final PeriodHolderImpl periodsHolder;
- public LoadPeriodsStep(DbClient dbClient, SettingsRepository settingsRepository, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder,
+ public LoadPeriodsStep(DbClient dbClient, ConfigurationRepository settingsRepository, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder,
PeriodHolderImpl periodsHolder) {
this.dbClient = dbClient;
- this.settingsRepository = settingsRepository;
+ this.configRepository = settingsRepository;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.periodsHolder = periodsHolder;
PeriodResolver periodResolver = new PeriodResolver(dbClient, session, projectDto.get().uuid(), analysisMetadataHolder.getAnalysisDate(),
isReportType ? projectOrView.getReportAttributes().getVersion() : null);
- Settings settings = settingsRepository.getSettings(projectOrView);
- Period period = periodResolver.resolve(settings);
+ Configuration config = configRepository.getConfiguration(projectOrView);
+ Period period = periodResolver.resolve(config);
// SONAR-4700 Add a past snapshot only if it exists
if (period != null) {
return period;
import com.google.common.base.Optional;
import org.apache.commons.lang.StringUtils;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.server.computation.task.projectanalysis.component.Component;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.server.computation.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.server.computation.task.projectanalysis.qualitygate.MutableQualityGateHolder;
private static final String PROPERTY_QUALITY_GATE = "sonar.qualitygate";
private final TreeRootHolder treeRootHolder;
- private final SettingsRepository settingsRepository;
+ private final ConfigurationRepository configRepository;
private final QualityGateService qualityGateService;
private final MutableQualityGateHolder qualityGateHolder;
- public LoadQualityGateStep(TreeRootHolder treeRootHolder, SettingsRepository settingsRepository,
- QualityGateService qualityGateService, MutableQualityGateHolder qualityGateHolder) {
+ public LoadQualityGateStep(TreeRootHolder treeRootHolder, ConfigurationRepository settingsRepository,
+ QualityGateService qualityGateService, MutableQualityGateHolder qualityGateHolder) {
this.treeRootHolder = treeRootHolder;
- this.settingsRepository = settingsRepository;
+ this.configRepository = settingsRepository;
this.qualityGateService = qualityGateService;
this.qualityGateHolder = qualityGateHolder;
}
private void executeForProject(Component project) {
String projectKey = project.getKey();
- Settings settings = settingsRepository.getSettings(project);
- String qualityGateSetting = settings.getString(PROPERTY_QUALITY_GATE);
+ Configuration config = configRepository.getConfiguration(project);
+ String qualityGateSetting = config.get(PROPERTY_QUALITY_GATE).orElse(null);
- if (qualityGateSetting == null || StringUtils.isBlank(qualityGateSetting)) {
+ if (StringUtils.isBlank(qualityGateSetting)) {
LOGGER.debug("No quality gate is configured for project " + projectKey);
qualityGateHolder.setNoQualityGate();
return;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
}
@CheckForNull
- public Period resolve(Settings settings) {
- String propertyValue = getPropertyValue(settings);
+ public Period resolve(Configuration config) {
+ String propertyValue = getPropertyValue(config);
if (StringUtils.isBlank(propertyValue)) {
return null;
}
return DateUtils.formatDate(Date.from(new Date(date).toInstant().truncatedTo(ChronoUnit.SECONDS)));
}
- private static String getPropertyValue(Settings settings) {
- return settings.getString(LEAK_PERIOD);
+ private static String getPropertyValue(Configuration config) {
+ return config.get(LEAK_PERIOD).get();
}
}
import org.sonar.server.computation.task.projectanalysis.component.DbIdsRepository;
import org.sonar.server.computation.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.server.computation.task.projectanalysis.component.DisabledComponentsHolder;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.server.computation.dbcleaner.ProjectCleaner;
private final DbClient dbClient;
private final DbIdsRepository dbIdsRepository;
private final TreeRootHolder treeRootHolder;
- private final SettingsRepository settingsRepository;
+ private final ConfigurationRepository configRepository;
private final DisabledComponentsHolder disabledComponentsHolder;
public PurgeDatastoresStep(DbClient dbClient, ProjectCleaner projectCleaner, DbIdsRepository dbIdsRepository, TreeRootHolder treeRootHolder,
- SettingsRepository settingsRepository, DisabledComponentsHolder disabledComponentsHolder) {
+ ConfigurationRepository configRepository, DisabledComponentsHolder disabledComponentsHolder) {
this.projectCleaner = projectCleaner;
this.dbClient = dbClient;
this.dbIdsRepository = dbIdsRepository;
this.treeRootHolder = treeRootHolder;
- this.settingsRepository = settingsRepository;
+ this.configRepository = configRepository;
this.disabledComponentsHolder = disabledComponentsHolder;
}
private void execute(Component root) {
try (DbSession dbSession = dbClient.openSession(true)) {
IdUuidPair idUuidPair = new IdUuidPair(dbIdsRepository.getComponentId(root), root.getUuid());
- projectCleaner.purge(dbSession, idUuidPair, settingsRepository.getSettings(root), disabledComponentsHolder.getUuids());
+ projectCleaner.purge(dbSession, idUuidPair, configRepository.getConfiguration(root), disabledComponentsHolder.getUuids());
dbSession.commit();
}
}
import java.util.List;
import java.util.Optional;
import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.core.config.WebhookProperties;
import org.sonar.core.util.stream.MoreCollectors;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import static java.lang.String.format;
private static final Logger LOGGER = Loggers.get(WebhookPostTask.class);
private final TreeRootHolder rootHolder;
- private final SettingsRepository settingsRepository;
+ private final ConfigurationRepository configRepository;
private final WebhookPayloadFactory payloadFactory;
private final WebhookCaller caller;
private final WebhookDeliveryStorage deliveryStorage;
- public WebhookPostTask(TreeRootHolder rootHolder, SettingsRepository settingsRepository, WebhookPayloadFactory payloadFactory,
+ public WebhookPostTask(TreeRootHolder rootHolder, ConfigurationRepository settingsRepository, WebhookPayloadFactory payloadFactory,
WebhookCaller caller, WebhookDeliveryStorage deliveryStorage) {
this.rootHolder = rootHolder;
- this.settingsRepository = settingsRepository;
+ this.configRepository = settingsRepository;
this.payloadFactory = payloadFactory;
this.caller = caller;
this.deliveryStorage = deliveryStorage;
@Override
public void finished(ProjectAnalysis analysis) {
- Settings settings = settingsRepository.getSettings(rootHolder.getRoot());
+ Configuration config = configRepository.getConfiguration(rootHolder.getRoot());
Iterable<String> webhookProps = Iterables.concat(
- getWebhookProperties(settings, WebhookProperties.GLOBAL_KEY),
- getWebhookProperties(settings, WebhookProperties.PROJECT_KEY));
+ getWebhookProperties(config, WebhookProperties.GLOBAL_KEY),
+ getWebhookProperties(config, WebhookProperties.PROJECT_KEY));
if (!Iterables.isEmpty(webhookProps)) {
- process(settings, analysis, webhookProps);
+ process(config, analysis, webhookProps);
deliveryStorage.purge(analysis.getProject().getUuid());
}
}
- private static List<String> getWebhookProperties(Settings settings, String propertyKey) {
- String[] webhookIds = settings.getStringArray(propertyKey);
+ private static List<String> getWebhookProperties(Configuration config, String propertyKey) {
+ String[] webhookIds = config.getStringArray(propertyKey);
return Arrays.stream(webhookIds)
.map(webhookId -> format("%s.%s", propertyKey, webhookId))
.limit(MAX_WEBHOOKS_PER_TYPE)
.collect(MoreCollectors.toList(webhookIds.length));
}
- private void process(Settings settings, ProjectAnalysis analysis, Iterable<String> webhookProperties) {
+ private void process(Configuration config, ProjectAnalysis analysis, Iterable<String> webhookProperties) {
WebhookPayload payload = payloadFactory.create(analysis);
for (String webhookProp : webhookProperties) {
- String name = settings.getString(format("%s.%s", webhookProp, WebhookProperties.NAME_FIELD));
- String url = settings.getString(format("%s.%s", webhookProp, WebhookProperties.URL_FIELD));
+ String name = config.get(format("%s.%s", webhookProp, WebhookProperties.NAME_FIELD)).orElse(null);
+ String url = config.get(format("%s.%s", webhookProp, WebhookProperties.URL_FIELD)).orElse(null);
// as webhooks are defined as property sets, we can't ensure validity of fields on creation.
if (name != null && url != null) {
Webhook webhook = new Webhook(analysis.getProject().getUuid(), analysis.getCeTask().getId(), name, url);
import org.elasticsearch.common.transport.TransportAddress;
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
private EsClient cache;
- public EsClient provide(Settings settings) {
+ public EsClient provide(Configuration config) {
if (cache == null) {
TransportClient nativeClient;
org.elasticsearch.common.settings.Settings.Builder esSettings = org.elasticsearch.common.settings.Settings.builder();
// mandatory property defined by bootstrap process
- esSettings.put("cluster.name", settings.getString(ProcessProperties.CLUSTER_NAME));
+ esSettings.put("cluster.name", config.get(ProcessProperties.CLUSTER_NAME).get());
- boolean clusterEnabled = settings.getBoolean(ProcessProperties.CLUSTER_ENABLED);
- if (clusterEnabled && settings.getBoolean(ProcessProperties.CLUSTER_SEARCH_DISABLED)) {
+ boolean clusterEnabled = config.getBoolean(ProcessProperties.CLUSTER_ENABLED).orElse(false);
+ if (clusterEnabled && config.getBoolean(ProcessProperties.CLUSTER_SEARCH_DISABLED).orElse(false)) {
esSettings.put("client.transport.sniff", true);
nativeClient = TransportClient.builder().settings(esSettings).build();
- Arrays.stream(settings.getStringArray(ProcessProperties.CLUSTER_SEARCH_HOSTS))
+ Arrays.stream(config.getStringArray(ProcessProperties.CLUSTER_SEARCH_HOSTS))
.map(HostAndPort::fromString)
.forEach(h -> addHostToClient(h, nativeClient));
LOGGER.info("Connected to remote Elasticsearch: [{}]", displayedAddresses(nativeClient));
} else {
nativeClient = TransportClient.builder().settings(esSettings).build();
- HostAndPort host = HostAndPort.fromParts(settings.getString(ProcessProperties.SEARCH_HOST), settings.getInt(ProcessProperties.SEARCH_PORT));
+ HostAndPort host = HostAndPort.fromParts(config.get(ProcessProperties.SEARCH_HOST).get(), config.getInt(ProcessProperties.SEARCH_PORT).get());
addHostToClient(host, nativeClient);
LOGGER.info("Connected to local Elasticsearch: [{}]", displayedAddresses(nativeClient));
}
import java.util.Map;
import org.elasticsearch.common.settings.Settings;
import org.picocontainer.Startable;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
/**
private final Map<String, Index> byKey = Maps.newHashMap();
private final IndexDefinition[] defs;
- private final org.sonar.api.config.Settings settings;
+ private final Configuration config;
- public IndexDefinitions(IndexDefinition[] defs, org.sonar.api.config.Settings settings) {
+ public IndexDefinitions(IndexDefinition[] defs, Configuration config) {
this.defs = defs;
- this.settings = settings;
+ this.config = config;
}
public Map<String, Index> getIndices() {
// collect definitions
IndexDefinition.IndexDefinitionContext context = new IndexDefinition.IndexDefinitionContext();
- if (!settings.getBoolean("sonar.internal.es.disableIndexes")) {
+ if (!config.getBoolean("sonar.internal.es.disableIndexes").orElse(false)) {
for (IndexDefinition definition : defs) {
definition.define(context);
}
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.unit.TimeValue;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
private static final String SETTING_PREFIX_INITIAL_INDEXING_FINISHED = "sonarqube_initial_indexing_finished.";
private final EsClient esClient;
- private final Settings settings;
+ private final Configuration config;
private final StartupIndexer[] indexers;
- public IndexerStartupTask(EsClient esClient, Settings settings, StartupIndexer... indexers) {
+ public IndexerStartupTask(EsClient esClient, Configuration config, StartupIndexer... indexers) {
this.esClient = esClient;
- this.settings = settings;
+ this.config = config;
this.indexers = indexers;
}
}
private boolean indexesAreEnabled() {
- return !settings.getBoolean("sonar.internal.es.disableIndexes");
+ return !config.getBoolean("sonar.internal.es.disableIndexes").orElse(false);
}
private void indexEmptyTypes(StartupIndexer indexer) {
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.process.ProcessProperties;
import org.sonar.server.permission.index.AuthorizationTypeSupport;
return types;
}
- public void configureShards(org.sonar.api.config.Settings settings, int defaultNbOfShards) {
- boolean clusterMode = settings.getBoolean(ProcessProperties.CLUSTER_ENABLED);
- int shards = settings.getInt(format("sonar.search.%s.shards", indexName));
- if (shards == 0) {
- shards = defaultNbOfShards;
- }
+ public void configureShards(Configuration config, int defaultNbOfShards) {
+ boolean clusterMode = config.getBoolean(ProcessProperties.CLUSTER_ENABLED).orElse(false);
+ int shards = config.getInt(format("sonar.search.%s.shards", indexName)).orElse(defaultNbOfShards);
+
+ int replicas = config.getInt(ProcessProperties.SEARCH_REPLICAS).orElse(clusterMode ? 1 : 0);
- int replicas = settings.getInt(ProcessProperties.SEARCH_REPLICAS);
- if (replicas == 0 && settings.getString(ProcessProperties.SEARCH_REPLICAS) == null) {
- replicas = clusterMode ? 1 : 0;
- }
getSettings().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, shards);
getSettings().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, replicas);
}
*/
package org.sonar.server.issue.index;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.NewIndex;
*/
public static final String FIELD_ISSUE_TECHNICAL_UPDATED_AT = "updatedAt";
- private final Settings settings;
+ private final Configuration config;
- public IssueIndexDefinition(Settings settings) {
- this.settings = settings;
+ public IssueIndexDefinition(Configuration config) {
+ this.config = config;
}
@Override
NewIndex index = context.create(INDEX_TYPE_ISSUE.getIndex());
index.refreshHandledByIndexer();
- index.configureShards(settings, 5);
+ index.configureShards(config, 5);
NewIndex.NewIndexType type = index.createType(INDEX_TYPE_ISSUE.getType());
type.requireProjectAuthorization();
*/
package org.sonar.server.measure.index;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.NewIndex;
public static final String FIELD_MEASURES_VALUE = "value";
public static final String FIELD_LANGUAGES = "languages";
- private final Settings settings;
+ private final Configuration config;
- public ProjectMeasuresIndexDefinition(Settings settings) {
- this.settings = settings;
+ public ProjectMeasuresIndexDefinition(Configuration settings) {
+ this.config = settings;
}
@Override
public void define(IndexDefinitionContext context) {
NewIndex index = context.create(INDEX_TYPE_PROJECT_MEASURES.getIndex());
index.refreshHandledByIndexer();
- index.configureShards(settings, 5);
+ index.configureShards(config, 5);
NewIndex.NewIndexType mapping = index.createType(INDEX_TYPE_PROJECT_MEASURES.getType())
.requireProjectAuthorization();
import org.picocontainer.Startable;
import org.sonar.api.Properties;
import org.sonar.api.Property;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.notifications.Notification;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.log.Logger;
private ScheduledExecutorService executorService;
private boolean stopping = false;
- public NotificationDaemon(Settings settings, DefaultNotificationManager manager, NotificationService service) {
- this.delayInSeconds = settings.getLong(PROPERTY_DELAY);
- this.delayBeforeReportingStatusInSeconds = settings.getLong(PROPERTY_DELAY_BEFORE_REPORTING_STATUS);
+ public NotificationDaemon(Configuration config, DefaultNotificationManager manager, NotificationService service) {
+ this.delayInSeconds = config.getLong(PROPERTY_DELAY).get();
+ this.delayBeforeReportingStatusInSeconds = config.getLong(PROPERTY_DELAY_BEFORE_REPORTING_STATUS).get();
this.manager = manager;
this.service = service;
}
import java.util.Optional;
import java.util.function.Consumer;
import javax.annotation.Nullable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.System2;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.util.UuidFactory;
private final System2 system2;
private final UuidFactory uuidFactory;
private final OrganizationValidation organizationValidation;
- private final Settings settings;
+ private final Configuration config;
private final BuiltInQProfileRepository builtInQProfileRepository;
private final DefaultGroupCreator defaultGroupCreator;
private final UserIndexer userIndexer;
public OrganizationCreationImpl(DbClient dbClient, System2 system2, UuidFactory uuidFactory,
- OrganizationValidation organizationValidation, Settings settings, UserIndexer userIndexer,
+ OrganizationValidation organizationValidation, Configuration config, UserIndexer userIndexer,
BuiltInQProfileRepository builtInQProfileRepository,
DefaultGroupCreator defaultGroupCreator) {
this.dbClient = dbClient;
this.system2 = system2;
this.uuidFactory = uuidFactory;
this.organizationValidation = organizationValidation;
- this.settings = settings;
+ this.config = config;
this.userIndexer = userIndexer;
this.builtInQProfileRepository = builtInQProfileRepository;
this.defaultGroupCreator = defaultGroupCreator;
}
private boolean isCreatePersonalOrgEnabled() {
- return settings.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_CREATE_PERSONAL_ORG);
+ return config.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_CREATE_PERSONAL_ORG).orElse(false);
}
private void validate(NewOrganization newOrganization) {
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
public class CreateAction implements OrganizationsWsAction {
private static final String ACTION = "create";
- private final Settings settings;
+ private final Configuration config;
private final UserSession userSession;
private final DbClient dbClient;
private final OrganizationsWsSupport wsSupport;
private final OrganizationCreation organizationCreation;
private final OrganizationFlags organizationFlags;
- public CreateAction(Settings settings, UserSession userSession, DbClient dbClient, OrganizationsWsSupport wsSupport,
+ public CreateAction(Configuration config, UserSession userSession, DbClient dbClient, OrganizationsWsSupport wsSupport,
OrganizationValidation organizationValidation, OrganizationCreation organizationCreation, OrganizationFlags organizationFlags) {
- this.settings = settings;
+ this.config = config;
this.userSession = userSession;
this.dbClient = dbClient;
this.wsSupport = wsSupport;
@Override
public void handle(Request request, Response response) throws Exception {
- if (settings.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_ANYONE_CAN_CREATE)) {
+ if (config.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_ANYONE_CAN_CREATE).orElse(false)) {
userSession.checkLoggedIn();
} else {
userSession.checkIsSystemAdministrator();
import java.io.File;
import org.picocontainer.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.process.ProcessProperties;
import org.sonar.server.app.TomcatContexts;
-import static java.util.Objects.requireNonNull;
-
public class ServerFileSystemImpl implements ServerFileSystem, org.sonar.api.platform.ServerFileSystem, Startable {
private static final Logger LOGGER = Loggers.get(ServerFileSystemImpl.class);
private final File dataDir;
private final File deployDir;
- public ServerFileSystemImpl(Settings settings) {
- this.homeDir = new File(requireNonNull(settings.getString(ProcessProperties.PATH_HOME)));
- this.tempDir = new File(requireNonNull(settings.getString(ProcessProperties.PATH_TEMP)));
- this.dataDir = new File(requireNonNull(settings.getString(ProcessProperties.PATH_DATA)));
+ public ServerFileSystemImpl(Configuration config) {
+ this.homeDir = new File(config.get(ProcessProperties.PATH_HOME).get());
+ this.tempDir = new File(config.get(ProcessProperties.PATH_TEMP).get());
+ this.dataDir = new File(config.get(ProcessProperties.PATH_DATA).get());
this.deployDir = new File(this.dataDir, TomcatContexts.WEB_DEPLOY_PATH_RELATIVE_TO_DATA_DIR);
}
*/
package org.sonar.server.platform;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
-
-import static com.google.common.base.Optional.fromNullable;
+import org.sonar.api.config.Configuration;
public class ServerIdLoader {
- private final Settings settings;
+ private final Configuration config;
private final ServerIdGenerator idGenerator;
- public ServerIdLoader(Settings settings, ServerIdGenerator idGenerator) {
- this.settings = settings;
+ public ServerIdLoader(Configuration config, ServerIdGenerator idGenerator) {
+ this.config = config;
this.idGenerator = idGenerator;
}
public Optional<String> getRaw() {
- return fromNullable(settings.getString(CoreProperties.PERMANENT_SERVER_ID));
+ return config.get(CoreProperties.PERMANENT_SERVER_ID);
}
public Optional<ServerId> get() {
- Optional<String> rawId = getRaw();
- if (!rawId.isPresent()) {
- return Optional.absent();
- }
-
- String organization = settings.getString(CoreProperties.ORGANISATION);
- String ipAddress = settings.getString(CoreProperties.SERVER_ID_IP_ADDRESS);
- boolean validated = organization != null
- && ipAddress != null
- && idGenerator.validate(organization, ipAddress, rawId.get());
-
- return Optional.of(new ServerId(rawId.get(), validated));
+ return getRaw().map(rawId -> {
+ Optional<String> organization = config.get(CoreProperties.ORGANISATION);
+ Optional<String> ipAddress = config.get(CoreProperties.SERVER_ID_IP_ADDRESS);
+ boolean validated = organization.isPresent()
+ && ipAddress.isPresent()
+ && idGenerator.validate(organization.get(), ipAddress.get(), rawId);
+
+ return new ServerId(rawId, validated);
+ });
}
}
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarRuntime;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.api.server.ServerSide;
@ServerSide
public class ServerImpl extends Server {
- private final Settings settings;
+ private final Configuration config;
private final StartupMetadata state;
private final ServerFileSystem fs;
private final UrlSettings urlSettings;
private final SonarRuntime runtime;
- public ServerImpl(Settings settings, StartupMetadata state, ServerFileSystem fs, UrlSettings urlSettings, SonarRuntime runtime) {
- this.settings = settings;
+ public ServerImpl(Configuration config, StartupMetadata state, ServerFileSystem fs, UrlSettings urlSettings, SonarRuntime runtime) {
+ this.config = config;
this.state = state;
this.fs = fs;
this.urlSettings = urlSettings;
@Override
public String getId() {
- return settings.getString(CoreProperties.SERVER_ID);
+ return config.get(CoreProperties.SERVER_ID).get();
}
@Override
public String getPermanentServerId() {
- return settings.getString(CoreProperties.PERMANENT_SERVER_ID);
+ return config.get(CoreProperties.PERMANENT_SERVER_ID).orElse(null);
}
@Override
import java.io.File;
import org.slf4j.LoggerFactory;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.process.logging.LogbackHelper;
import org.sonar.process.ProcessProperties;
+import org.sonar.process.logging.LogbackHelper;
import org.sonar.server.app.ServerProcessLogging;
@ServerSide
public class ServerLogging {
private final LogbackHelper helper;
- private final Settings settings;
+ private final Configuration config;
- public ServerLogging(Settings settings) {
- this(new LogbackHelper(), settings);
+ public ServerLogging(Configuration config) {
+ this(new LogbackHelper(), config);
}
@VisibleForTesting
- ServerLogging(LogbackHelper helper, Settings settings) {
+ ServerLogging(LogbackHelper helper, Configuration config) {
this.helper = helper;
- this.settings = settings;
+ this.config = config;
}
public void changeLevel(ServerProcessLogging serverProcessLogging, LoggerLevel level) {
* The directory that contains log files. May not exist.
*/
public File getLogsDir() {
- return new File(settings.getString(ProcessProperties.PATH_LOGS));
+ return new File(config.get(ProcessProperties.PATH_LOGS).get());
}
}
package org.sonar.server.platform;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
-import static org.apache.commons.lang.StringUtils.defaultIfBlank;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.sonar.api.CoreProperties.SERVER_BASE_URL;
private static final int DEFAULT_HTTP_PORT = 80;
private static final String ALL_IPS_HOST = "0.0.0.0";
- private final Settings settings;
+ private final Configuration config;
// cached, so can't change at runtime
private final String contextPath;
- public UrlSettings(Settings settings) {
- this.settings = settings;
- this.contextPath = defaultIfBlank(settings.getString(PROPERTY_CONTEXT), "")
+ public UrlSettings(Configuration config) {
+ this.config = config;
+ this.contextPath = config.get(PROPERTY_CONTEXT).orElse("")
// Remove trailing slashes
.replaceFirst("(\\/+)$", "");
}
public String getBaseUrl() {
- String url = settings.getString(SERVER_BASE_URL);
+ String url = config.get(SERVER_BASE_URL).orElse("");
if (isEmpty(url)) {
url = computeBaseUrl();
}
}
public boolean isDev() {
- return settings.getBoolean("sonar.web.dev");
+ return config.getBoolean("sonar.web.dev").orElse(false);
}
public boolean isSecured() {
}
private String computeBaseUrl() {
- String host = settings.getString("sonar.web.host");
- int port = settings.getInt("sonar.web.port");
- String context = settings.getString("sonar.web.context");
+ String host = config.get("sonar.web.host").orElse("");
+ int port = config.getInt("sonar.web.port").orElse(0);
+ String context = config.get("sonar.web.context").orElse("");
StringBuilder res = new StringBuilder();
res.append("http://");
*/
package org.sonar.server.platform.cluster;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.log.Loggers;
import org.sonar.process.ProcessProperties;
private final boolean enabled;
private final boolean startupLeader;
- public ClusterImpl(Settings settings) {
- this.enabled = settings.getBoolean(ProcessProperties.CLUSTER_ENABLED);
+ public ClusterImpl(Configuration config) {
+ this.enabled = config.getBoolean(ProcessProperties.CLUSTER_ENABLED).orElse(false);
if (this.enabled) {
- this.startupLeader = settings.getBoolean(CLUSTER_WEB_LEADER);
+ this.startupLeader = config.getBoolean(CLUSTER_WEB_LEADER).orElse(false);
Loggers.get(ClusterImpl.class).info("Cluster enabled (startup {})", startupLeader ? "leader" : "follower");
} else {
this.startupLeader = true;
import org.h2.Driver;
import org.h2.tools.Server;
import org.picocontainer.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
public class EmbeddedDatabase implements Startable {
private static final Logger LOG = Loggers.get(EmbeddedDatabase.class);
- private final Settings settings;
+ private final Configuration config;
private final System2 system2;
private Server server;
- public EmbeddedDatabase(Settings settings, System2 system2) {
- this.settings = settings;
+ public EmbeddedDatabase(Configuration config, System2 system2) {
+ this.config = config;
this.system2 = system2;
}
}
private String getRequiredSetting(String property) {
- String value = settings.getString(property);
+ String value = config.get(property).orElse("");
checkArgument(isNotEmpty(value), "Missing property %s", property);
return value;
}
private String getSetting(String name, String defaultValue) {
- return StringUtils.defaultIfBlank(settings.getString(name), defaultValue);
+ return StringUtils.defaultIfBlank(config.get(name).orElse(""), defaultValue);
}
private static void createDatabase(File dbHome, String user, String password) throws SQLException {
import com.google.common.annotations.VisibleForTesting;
import org.picocontainer.Startable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.database.DatabaseProperties;
import org.sonar.api.utils.System2;
private static final String URL_PREFIX = "jdbc:h2:tcp:";
- private final Settings settings;
+ private final Configuration config;
private final System2 system2;
private EmbeddedDatabase embeddedDatabase;
- public EmbeddedDatabaseFactory(Settings settings, System2 system2) {
- this.settings = settings;
+ public EmbeddedDatabaseFactory(Configuration config, System2 system2) {
+ this.config = config;
this.system2 = system2;
}
@Override
public void start() {
if (embeddedDatabase == null) {
- String jdbcUrl = settings.getString(DatabaseProperties.PROP_URL);
+ String jdbcUrl = config.get(DatabaseProperties.PROP_URL).get();
if (startsWith(jdbcUrl, URL_PREFIX)) {
embeddedDatabase = createEmbeddedDatabase();
embeddedDatabase.start();
@VisibleForTesting
EmbeddedDatabase createEmbeddedDatabase() {
- return new EmbeddedDatabase(settings, system2);
+ return new EmbeddedDatabase(config, system2);
}
}
package org.sonar.server.platform.monitoring;
import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.api.security.SecurityRealm;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.process.ProcessProperties;
import org.sonar.server.authentication.IdentityProviderRepository;
-import org.sonar.server.platform.ServerId;
import org.sonar.server.platform.ServerIdLoader;
import org.sonar.server.platform.ServerLogging;
import org.sonar.server.user.SecurityRealmFactory;
static final String BRANDING_FILE_PATH = "web/WEB-INF/classes/com/sonarsource/branding";
- private final Settings settings;
+ private final Configuration config;
private final SecurityRealmFactory securityRealmFactory;
private final IdentityProviderRepository identityProviderRepository;
private final Server server;
private final ServerLogging serverLogging;
private final ServerIdLoader serverIdLoader;
- public SonarQubeMonitor(Settings settings, SecurityRealmFactory securityRealmFactory,
+ public SonarQubeMonitor(Configuration config, SecurityRealmFactory securityRealmFactory,
IdentityProviderRepository identityProviderRepository, Server server, ServerLogging serverLogging,
ServerIdLoader serverIdLoader) {
- this.settings = settings;
+ this.config = config;
this.securityRealmFactory = securityRealmFactory;
this.identityProviderRepository = identityProviderRepository;
this.server = server;
@Override
public String getServerId() {
- return serverIdLoader.getRaw().orNull();
+ return serverIdLoader.getRaw().orElse(null);
}
@Override
}
private boolean getForceAuthentication() {
- return settings.getBoolean(CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY);
+ return config.getBoolean(CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(false);
}
private boolean isOfficialDistribution() {
addIfNotEmpty("External identity providers whose users are allowed to sign themselves up", getAllowsToSignUpEnabledIdentityProviders(), attributes);
attributes.put("Force authentication", getForceAuthentication());
attributes.put("Official Distribution", isOfficialDistribution());
- attributes.put("Home Dir", settings.getString(ProcessProperties.PATH_HOME));
- attributes.put("Data Dir", settings.getString(ProcessProperties.PATH_DATA));
- attributes.put("Temp Dir", settings.getString(ProcessProperties.PATH_TEMP));
- attributes.put("Logs Dir", settings.getString(ProcessProperties.PATH_LOGS));
+ attributes.put("Home Dir", config.get(ProcessProperties.PATH_HOME).orElse(null));
+ attributes.put("Data Dir", config.get(ProcessProperties.PATH_DATA).orElse(null));
+ attributes.put("Temp Dir", config.get(ProcessProperties.PATH_TEMP).orElse(null));
+ attributes.put("Logs Dir", config.get(ProcessProperties.PATH_LOGS).orElse(null));
attributes.put("Logs Level", getLogLevel());
return attributes;
}
private void completeWithServerIdAttributes(Map<String, Object> attributes) {
- Optional<ServerId> serverId = serverIdLoader.get();
- if (serverId.isPresent()) {
- attributes.put("Server ID", serverId.get().getId());
- attributes.put("Server ID validated", serverId.get().isValid());
- }
+ serverIdLoader.get().ifPresent(serverId -> {
+ attributes.put("Server ID", serverId.getId());
+ attributes.put("Server ID validated", serverId.isValid());
+ });
}
private static void addIfNotNull(String key, @Nullable String value, Map<String, Object> attributes) {
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import org.sonar.api.utils.internal.TempFolderCleaner;
+import org.sonar.core.config.ConfigurationProvider;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DaoModule;
new SonarQubeVersion(apiVersion),
SonarRuntimeImpl.forSonarQube(apiVersion, SonarQubeSide.SERVER),
ThreadLocalSettings.class,
+ new ConfigurationProvider(),
LogServerVersion.class,
ProcessCommandWrapperImpl.class,
RestartFlagHolderImpl.class,
import org.sonar.api.rules.XMLRuleParser;
import org.sonar.api.server.rule.RulesDefinitionXmlLoader;
import org.sonar.ce.CeModule;
-import org.sonar.ce.settings.ProjectSettingsFactory;
+import org.sonar.ce.settings.ProjectConfigurationFactory;
import org.sonar.core.component.DefaultResourceTypes;
import org.sonar.core.timemachine.Periods;
import org.sonar.server.authentication.AuthenticationModule;
CeWsModule.class,
InternalPropertiesImpl.class,
- ProjectSettingsFactory.class,
+ ProjectConfigurationFactory.class,
// UI
NavigationWsModule.class,
*/
package org.sonar.server.platform.ws;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
private static final Logger LOGGER = Loggers.get(RestartAction.class);
private final UserSession userSession;
- private final Settings settings;
+ private final Configuration config;
private final Platform platform;
private final ProcessCommandWrapper processCommandWrapper;
private final RestartFlagHolder restartFlagHolder;
- public RestartAction(UserSession userSession, Settings settings, Platform platform, ProcessCommandWrapper processCommandWrapper, RestartFlagHolder restartFlagHolder) {
+ public RestartAction(UserSession userSession, Configuration config, Platform platform, ProcessCommandWrapper processCommandWrapper, RestartFlagHolder restartFlagHolder) {
this.userSession = userSession;
- this.settings = settings;
+ this.config = config;
this.platform = platform;
this.processCommandWrapper = processCommandWrapper;
this.restartFlagHolder = restartFlagHolder;
@Override
public void handle(Request request, Response response) {
- if (settings.getBoolean("sonar.web.dev")) {
+ if (config.getBoolean("sonar.web.dev").orElse(false)) {
LOGGER.info("Fast restarting WebServer...");
restartFlagHolder.set();
try {
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.utils.UriReader;
import org.sonar.api.utils.log.Loggers;
import org.sonar.core.config.WebConstants;
private UpdateCenter pluginCenter = null;
private long lastRefreshDate = 0;
- public UpdateCenterClient(UriReader uriReader, Settings settings) throws URISyntaxException {
+ public UpdateCenterClient(UriReader uriReader, Configuration config) throws URISyntaxException {
this.uriReader = uriReader;
- this.uri = new URI(settings.getString(URL_PROPERTY));
- this.isActivated = settings.getBoolean(WebConstants.SONAR_UPDATECENTER_ACTIVATE);
+ this.uri = new URI(config.get(URL_PROPERTY).get());
+ this.isActivated = config.getBoolean(WebConstants.SONAR_UPDATECENTER_ACTIVATE).get();
Loggers.get(getClass()).info("Update center: " + uriReader.description(uri));
}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import java.util.Set;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.DefaultIndexSettings;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
public static final String FIELD_ACTIVE_RULE_SEVERITY = "severity";
public static final String FIELD_ACTIVE_RULE_RULE_KEY = "ruleKey";
- private final Settings settings;
+ private final Configuration config;
private final boolean enableSource;
- public RuleIndexDefinition(Settings settings) {
- this(settings, false);
+ public RuleIndexDefinition(Configuration config) {
+ this(config, false);
}
- private RuleIndexDefinition(Settings settings, boolean enableSource) {
- this.settings = settings;
+ private RuleIndexDefinition(Configuration config, boolean enableSource) {
+ this.config = config;
this.enableSource = enableSource;
}
* Keep the document sources in index so that indexer tests can verify content
* of indexed documents.
*/
- public static RuleIndexDefinition createForTest(Settings settings) {
- return new RuleIndexDefinition(settings, true);
+ public static RuleIndexDefinition createForTest(Configuration config) {
+ return new RuleIndexDefinition(config, true);
}
@Override
// Default nb of shards should be greater than 1 in order to
// easily detect routing misconfiguration.
// See https://jira.sonarsource.com/browse/SONAR-9489
- index.configureShards(settings, 2);
+ index.configureShards(config, 2);
// Active rule type
NewIndex.NewIndexType activeRuleMapping = index.createType(INDEX_TYPE_ACTIVE_RULE.getType());
package org.sonar.server.test.index;
import com.google.common.collect.ImmutableMap;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.NewIndex;
public static final String FIELD_COVERED_FILE_LINES = "coveredLines";
public static final String FIELD_UPDATED_AT = "updatedAt";
- private final Settings settings;
+ private final Configuration config;
- public TestIndexDefinition(Settings settings) {
- this.settings = settings;
+ public TestIndexDefinition(Configuration config) {
+ this.config = config;
}
@Override
NewIndex index = context.create(INDEX_TYPE_TEST.getIndex());
index.refreshHandledByIndexer();
- index.configureShards(settings, 5);
+ index.configureShards(config, 5);
NewIndex.NewIndexType mapping = index.createType(INDEX_TYPE_TEST.getType());
mapping.setAttribute("_routing", ImmutableMap.of("required", true));
mapping.stringFieldBuilder(FIELD_STACKTRACE).disableNorms().disableSearch().build();
mapping.setProperty(FIELD_COVERED_FILES, ImmutableMap.of("type", "nested", "properties", ImmutableMap.of(
FIELD_COVERED_FILE_UUID, ImmutableMap.of("type", "string", "index", "not_analyzed"),
- FIELD_COVERED_FILE_LINES, ImmutableMap.of("type", "integer")
- )));
+ FIELD_COVERED_FILE_LINES, ImmutableMap.of("type", "integer"))));
mapping.createDateTimeField(FIELD_UPDATED_AT);
}
}
import com.google.common.collect.ImmutableSet;
import java.util.Set;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
RATING_GRID);
private final PageRepository pageRepository;
- private final Settings settings;
+ private final Configuration config;
private final ResourceTypes resourceTypes;
private final Server server;
private final DbClient dbClient;
private final DefaultOrganizationProvider defaultOrganizationProvider;
private final UserSession userSession;
- public GlobalAction(PageRepository pageRepository, Settings settings, ResourceTypes resourceTypes, Server server,
- DbClient dbClient, OrganizationFlags organizationFlags, DefaultOrganizationProvider defaultOrganizationProvider, UserSession userSession) {
+ public GlobalAction(PageRepository pageRepository, Configuration config, ResourceTypes resourceTypes, Server server,
+ DbClient dbClient, OrganizationFlags organizationFlags, DefaultOrganizationProvider defaultOrganizationProvider, UserSession userSession) {
this.pageRepository = pageRepository;
- this.settings = settings;
+ this.config = config;
this.resourceTypes = resourceTypes;
this.server = server;
this.dbClient = dbClient;
private void writeSettings(JsonWriter json) {
json.name("settings").beginObject();
for (String settingKey : SETTING_KEYS) {
- json.prop(settingKey, settings.getString(settingKey));
+ json.prop(settingKey, config.get(settingKey).orElse(null));
}
json.endObject();
}
private void writeDeprecatedLogoProperties(JsonWriter json) {
- json.prop("logoUrl", settings.getString(SONAR_LF_LOGO_URL));
- json.prop("logoWidth", settings.getString(SONAR_LF_LOGO_WIDTH_PX));
+ json.prop("logoUrl", config.get(SONAR_LF_LOGO_URL).orElse(null));
+ json.prop("logoWidth", config.get(SONAR_LF_LOGO_WIDTH_PX).orElse(null));
}
private void writeQualifiers(JsonWriter json) {
*/
package org.sonar.server.ui.ws;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewController;
public class SettingsAction implements NavigationWsAction {
private final PageRepository pageRepository;
- private final Settings settings;
+ private final Configuration config;
private final UserSession userSession;
- public SettingsAction(PageRepository pageRepository, Settings settings, UserSession userSession) {
+ public SettingsAction(PageRepository pageRepository, Configuration config, UserSession userSession) {
this.pageRepository = pageRepository;
- this.settings = settings;
+ this.config = config;
this.userSession = userSession;
}
boolean isSysAdmin = userSession.isSystemAdministrator();
JsonWriter json = response.newJsonWriter().beginObject();
- json.prop("showUpdateCenter", isSysAdmin && settings.getBoolean(WebConstants.SONAR_UPDATECENTER_ACTIVATE));
+ json.prop("showUpdateCenter", isSysAdmin && config.getBoolean(WebConstants.SONAR_UPDATECENTER_ACTIVATE).orElse(false));
json.name("extensions").beginArray();
if (isSysAdmin) {
import org.apache.commons.lang.StringUtils;
import org.picocontainer.Startable;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.security.LoginPasswordAuthenticator;
import org.sonar.api.security.SecurityRealm;
import org.sonar.api.server.ServerSide;
private final boolean ignoreStartupFailure;
private final SecurityRealm realm;
- public SecurityRealmFactory(Settings settings, SecurityRealm[] realms, LoginPasswordAuthenticator[] authenticators) {
- ignoreStartupFailure = settings.getBoolean(CoreProperties.CORE_AUTHENTICATOR_IGNORE_STARTUP_FAILURE);
- String realmName = settings.getString(CoreProperties.CORE_AUTHENTICATOR_REALM);
- String className = settings.getString(CoreProperties.CORE_AUTHENTICATOR_CLASS);
+ public SecurityRealmFactory(Configuration config, SecurityRealm[] realms, LoginPasswordAuthenticator[] authenticators) {
+ ignoreStartupFailure = config.getBoolean(CoreProperties.CORE_AUTHENTICATOR_IGNORE_STARTUP_FAILURE).orElse(false);
+ String realmName = config.get(CoreProperties.CORE_AUTHENTICATOR_REALM).orElse(null);
+ String className = config.get(CoreProperties.CORE_AUTHENTICATOR_CLASS).orElse(null);
SecurityRealm selectedRealm = null;
if (!StringUtils.isEmpty(realmName)) {
selectedRealm = selectRealm(realms, realmName);
realm = selectedRealm;
}
- public SecurityRealmFactory(Settings settings, LoginPasswordAuthenticator[] authenticators) {
- this(settings, new SecurityRealm[0], authenticators);
+ public SecurityRealmFactory(Configuration config, LoginPasswordAuthenticator[] authenticators) {
+ this(config, new SecurityRealm[0], authenticators);
}
- public SecurityRealmFactory(Settings settings, SecurityRealm[] realms) {
- this(settings, realms, new LoginPasswordAuthenticator[0]);
+ public SecurityRealmFactory(Configuration config, SecurityRealm[] realms) {
+ this(config, realms, new LoginPasswordAuthenticator[0]);
}
- public SecurityRealmFactory(Settings settings) {
- this(settings, new SecurityRealm[0], new LoginPasswordAuthenticator[0]);
+ public SecurityRealmFactory(Configuration config) {
+ this(config, new SecurityRealm[0], new LoginPasswordAuthenticator[0]);
}
@Override
import java.util.Random;
import javax.annotation.Nullable;
import org.apache.commons.codec.digest.DigestUtils;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.platform.NewUserHandler;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
private final DefaultOrganizationProvider defaultOrganizationProvider;
private final OrganizationCreation organizationCreation;
private final DefaultGroupFinder defaultGroupFinder;
- private final Settings settings;
+ private final Configuration config;
public UserUpdater(NewUserNotifier newUserNotifier, DbClient dbClient, UserIndexer userIndexer, System2 system2, OrganizationFlags organizationFlags,
- DefaultOrganizationProvider defaultOrganizationProvider, OrganizationCreation organizationCreation, DefaultGroupFinder defaultGroupFinder, Settings settings) {
+ DefaultOrganizationProvider defaultOrganizationProvider, OrganizationCreation organizationCreation, DefaultGroupFinder defaultGroupFinder, Configuration config) {
this.newUserNotifier = newUserNotifier;
this.dbClient = dbClient;
this.userIndexer = userIndexer;
this.defaultOrganizationProvider = defaultOrganizationProvider;
this.organizationCreation = organizationCreation;
this.defaultGroupFinder = defaultGroupFinder;
- this.settings = settings;
+ this.config = config;
}
public UserDto create(DbSession dbSession, NewUser newUser) {
}
private void setOnboarded(UserDto userDto) {
- boolean showOnboarding = settings.getBoolean(ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS);
+ boolean showOnboarding = config.getBoolean(ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS).orElse(false);
userDto.setOnboarded(!showOnboarding);
}
*/
package org.sonar.server.user.index;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.NewIndex;
public static final String FIELD_SCM_ACCOUNTS = "scmAccounts";
public static final String FIELD_ORGANIZATION_UUIDS = "organizationUuids";
- private final Settings settings;
+ private final Configuration config;
- public UserIndexDefinition(Settings settings) {
- this.settings = settings;
+ public UserIndexDefinition(Configuration config) {
+ this.config = config;
}
@Override
public void define(IndexDefinitionContext context) {
NewIndex index = context.create(INDEX_TYPE_USER.getIndex());
- index.configureShards(settings, 1);
+ index.configureShards(config, 1);
// type "user"
NewIndex.NewIndexType mapping = index.createType(INDEX_TYPE_USER.getType());
import org.picocontainer.injectors.ProviderAdapter;
import org.sonar.api.SonarRuntime;
import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.process.ProcessProperties;
import org.sonarqube.ws.client.OkHttpClientBuilder;
/**
* @return a {@link OkHttpClient} singleton
*/
- public OkHttpClient provide(Settings settings, SonarRuntime runtime) {
+ public OkHttpClient provide(Configuration config, SonarRuntime runtime) {
if (okHttpClient == null) {
OkHttpClientBuilder builder = new OkHttpClientBuilder();
builder.setConnectTimeoutMs(DEFAULT_CONNECT_TIMEOUT_IN_MS);
builder.setReadTimeoutMs(DEFAULT_READ_TIMEOUT_IN_MS);
// no need to define proxy URL as system-wide proxy is used and properly
// configured by bootstrap process.
- builder.setProxyLogin(settings.getString(ProcessProperties.HTTP_PROXY_USER));
- builder.setProxyPassword(settings.getString(ProcessProperties.HTTP_PROXY_PASSWORD));
+ builder.setProxyLogin(config.get(ProcessProperties.HTTP_PROXY_USER).orElse(null));
+ builder.setProxyPassword(config.get(ProcessProperties.HTTP_PROXY_PASSWORD).orElse(null));
builder.setUserAgent(format("SonarQube/%s", runtime.getApiVersion().toString()));
okHttpClient = builder.build();
}
*/
package org.sonar.server.view.index;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.NewIndex;
public static final String FIELD_UUID = "uuid";
public static final String FIELD_PROJECTS = "projects";
- private final Settings settings;
+ private final Configuration config;
- public ViewIndexDefinition(Settings settings) {
- this.settings = settings;
+ public ViewIndexDefinition(Configuration config) {
+ this.config = config;
}
@Override
public void define(IndexDefinitionContext context) {
NewIndex index = context.create(INDEX_TYPE_VIEW.getIndex());
- index.configureShards(settings, 5);
+ index.configureShards(config, 5);
// type "view"
NewIndex.NewIndexType mapping = index.createType(INDEX_TYPE_VIEW.getType());
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.DefaultProcessCommands;
@Before
public void setUp() throws Exception {
ipcSharedDir = temp.newFolder();
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
settings.setProperty(ProcessEntryPoint.PROPERTY_SHARED_PATH, ipcSharedDir.getAbsolutePath());
- underTest = new CeHttpClient(settings);
+ underTest = new CeHttpClient(settings.asConfig());
}
@Test
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.process.DefaultProcessCommands;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
@Test
public void requestSQRestart_throws_IAE_if_process_index_property_not_set() throws Exception {
- ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig());
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property process.index is not set");
@Test
public void requestSQRestart_throws_IAE_if_process_shared_path_property_not_set() throws Exception {
settings.setProperty(PROPERTY_PROCESS_INDEX, 1);
- ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig());
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property process.sharedDir is not set");
settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath());
settings.setProperty(PROPERTY_PROCESS_INDEX, PROCESS_NUMBER);
- ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig());
underTest.requestSQRestart();
try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, PROCESS_NUMBER)) {
@Test
public void requestSQStop_throws_IAE_if_process_shared_path_property_not_set() throws Exception {
settings.setProperty(PROPERTY_PROCESS_INDEX, 1);
- ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig());
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property process.sharedDir is not set");
settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath());
settings.setProperty(PROPERTY_PROCESS_INDEX, PROCESS_NUMBER);
- ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig());
underTest.requestStop();
try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, PROCESS_NUMBER)) {
@Test
public void notifyOperational_throws_IAE_if_process_sharedDir_property_not_set() throws Exception {
settings.setProperty(PROPERTY_PROCESS_INDEX, 1);
- ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig());
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property process.sharedDir is not set");
@Test
public void notifyOperational_throws_IAE_if_process_index_property_not_set() throws Exception {
- ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig());
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property process.index is not set");
settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath());
settings.setProperty(PROPERTY_PROCESS_INDEX, PROCESS_NUMBER);
- ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings);
+ ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig());
underTest.notifyOperational();
try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, PROCESS_NUMBER)) {
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
private HttpServletResponse response = mock(HttpServletResponse.class);
private HttpSession httpSession = mock(HttpSession.class);
private System2 system2 = spy(System2.INSTANCE);
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private JwtSerializer jwtSerializer = mock(JwtSerializer.class);
private JwtCsrfVerifier jwtCsrfVerifier = mock(JwtCsrfVerifier.class);
private UserDto userDto = newUserDto().setLogin(USER_LOGIN);
- private JwtHttpHandler underTest = new JwtHttpHandler(system2, dbClient, settings, jwtSerializer, jwtCsrfVerifier);
+ private JwtHttpHandler underTest = new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
@Before
public void setUp() throws Exception {
int sessionTimeoutInMinutes = 10;
settings.setProperty("sonar.web.sessionTimeoutInMinutes", sessionTimeoutInMinutes);
- underTest = new JwtHttpHandler(system2, dbClient, settings, jwtSerializer, jwtCsrfVerifier);
+ underTest = new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
underTest.generateToken(userDto, request, response);
verify(jwtSerializer).encode(jwtArgumentCaptor.capture());
int firstSessionTimeoutInMinutes = 10;
settings.setProperty("sonar.web.sessionTimeoutInMinutes", firstSessionTimeoutInMinutes);
- underTest = new JwtHttpHandler(system2, dbClient, settings, jwtSerializer, jwtCsrfVerifier);
+ underTest = new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
underTest.generateToken(userDto, request, response);
// The property is updated, but it won't be taking into account
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must be strictly positive. Got 0");
- new JwtHttpHandler(system2, dbClient, settings, jwtSerializer, jwtCsrfVerifier);
+ new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
}
@Test
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must be strictly positive. Got -10");
- new JwtHttpHandler(system2, dbClient, settings, jwtSerializer, jwtCsrfVerifier);
+ new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
}
@Test
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must not be greater than 3 months (129600 minutes). Got 172800 minutes");
- new JwtHttpHandler(system2, dbClient, settings, jwtSerializer, jwtCsrfVerifier);
+ new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier);
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryImpl;
+import org.sonar.server.authentication.JwtSerializer.JwtSession;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.sonar.server.authentication.JwtSerializer.JwtSession;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException;
public class JwtSerializerTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private System2 system2 = System2.INSTANCE;
private UuidFactory uuidFactory = UuidFactoryImpl.INSTANCE;
- private JwtSerializer underTest = new JwtSerializer(settings, system2, uuidFactory);
+ private JwtSerializer underTest = new JwtSerializer(settings.asConfig(), system2, uuidFactory);
@Test
public void generate_token() throws Exception {
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.security.Authenticator;
import org.sonar.api.security.ExternalGroupsProvider;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.user.SecurityRealmFactory;
import static java.util.Arrays.asList;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.user.UserTesting.newUserDto;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC;
import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC_TOKEN;
import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException;
private ArgumentCaptor<IdentityProvider> identityProviderArgumentCaptor = ArgumentCaptor.forClass(IdentityProvider.class);
private ArgumentCaptor<AuthenticationEvent.Source> sourceCaptor = ArgumentCaptor.forClass(Source.class);
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class);
private SecurityRealm realm = mock(SecurityRealm.class);
private HttpServletRequest request = mock(HttpServletRequest.class);
- private RealmAuthenticator underTest = new RealmAuthenticator(settings, securityRealmFactory, userIdentityAuthenticator, authenticationEvent);
+ private RealmAuthenticator underTest = new RealmAuthenticator(settings.asConfig(), securityRealmFactory, userIdentityAuthenticator, authenticationEvent);
@Before
public void setUp() throws Exception {
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.organization.OrganizationCreation;
import org.sonar.server.organization.TestDefaultOrganizationProvider;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.user.UserTesting.newUserDto;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException;
public class SsoAuthenticatorTest {
private GroupDto sonarUsers;
private System2 system2 = mock(System2.class);
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private OrganizationCreation organizationCreation = mock(OrganizationCreation.class);
private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
private TestOrganizationFlags organizationFlags = TestOrganizationFlags.standalone();
private UserIdentityAuthenticator userIdentityAuthenticator = new UserIdentityAuthenticator(
db.getDbClient(),
new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), mock(UserIndexer.class), System2.INSTANCE, organizationFlags, defaultOrganizationProvider, organizationCreation,
- new DefaultGroupFinder(db.getDbClient()), settings),
+ new DefaultGroupFinder(db.getDbClient()), settings.asConfig()),
defaultOrganizationProvider, organizationFlags, new DefaultGroupFinder(db.getDbClient()));
private HttpServletResponse response = mock(HttpServletResponse.class);
private JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class);
private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
- private SsoAuthenticator underTest = new SsoAuthenticator(system2, settings, userIdentityAuthenticator, jwtHttpHandler, authenticationEvent);
+ private SsoAuthenticator underTest = new SsoAuthenticator(system2, settings.asConfig(), userIdentityAuthenticator, jwtHttpHandler, authenticationEvent);
@Before
public void setUp() throws Exception {
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
+import org.sonar.server.authentication.event.AuthenticationEvent.Method;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.organization.OrganizationCreation;
import org.sonar.server.organization.TestDefaultOrganizationProvider;
import static org.mockito.Mockito.mock;
import static org.sonar.core.config.CorePropertyDefinitions.ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS;
import static org.sonar.db.user.UserTesting.newUserDto;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Method;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException;
public class UserIdentityAuthenticatorTest {
defaultOrganizationProvider,
organizationCreation,
new DefaultGroupFinder(db.getDbClient()),
- settings);
+ settings.asConfig());
private UserIdentityAuthenticator underTest = new UserIdentityAuthenticator(db.getDbClient(), userUpdater, defaultOrganizationProvider, organizationFlags,
new DefaultGroupFinder(db.getDbClient()));
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.BaseIdentityProvider;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.event.AuthenticationEvent;
+import org.sonar.server.authentication.event.AuthenticationEvent.Method;
+import org.sonar.server.authentication.event.AuthenticationEvent.Source;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.user.ServerUserSession;
import org.sonar.server.user.TestUserSessionFactory;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.user.UserTesting.newUserDto;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Method;
-import static org.sonar.server.authentication.event.AuthenticationEvent.Source;
public class UserSessionInitializerTest {
private SsoAuthenticator ssoAuthenticator = mock(SsoAuthenticator.class);
private AuthenticationEvent authenticationEvent = mock(AuthenticationEvent.class);
private TestUserSessionFactory userSessionFactory = TestUserSessionFactory.standalone();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private UserDto user = newUserDto();
- private UserSessionInitializer underTest = new UserSessionInitializer(settings, jwtHttpHandler, basicAuthenticator,
+ private UserSessionInitializer underTest = new UserSessionInitializer(settings.asConfig(), jwtHttpHandler, basicAuthenticator,
ssoAuthenticator, userSession, authenticationEvent, userSessionFactory);
@Before
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.authentication.BasicAuthenticator;
import org.sonar.server.authentication.JwtHttpHandler;
BasicAuthenticator basicAuthenticator = mock(BasicAuthenticator.class);
JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class);
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
- ValidateAction underTest = new ValidateAction(settings, basicAuthenticator, jwtHttpHandler);
+ ValidateAction underTest = new ValidateAction(settings.asConfig(), basicAuthenticator, jwtHttpHandler);
@Before
public void setUp() throws Exception {
@Rule
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
public abstract class ComponentIndexTest {
@Rule
- public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private System2 system2 = System2.INSTANCE;
@Rule
- public EsTester esTester = new EsTester(new ComponentIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester dbTester = DbTester.create(system2);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
import org.sonar.test.JsonAssert;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.WsComponents.SuggestionsWsResponse;
+import org.sonarqube.ws.WsComponents.SuggestionsWsResponse.Category;
+import org.sonarqube.ws.WsComponents.SuggestionsWsResponse.Organization;
import org.sonarqube.ws.WsComponents.SuggestionsWsResponse.Project;
import org.sonarqube.ws.WsComponents.SuggestionsWsResponse.Suggestion;
import static org.sonar.server.component.ws.SuggestionsAction.PARAM_QUERY;
import static org.sonar.server.component.ws.SuggestionsAction.PARAM_RECENTLY_BROWSED;
import static org.sonar.server.component.ws.SuggestionsAction.SHORT_INPUT_WARNING;
-import static org.sonarqube.ws.WsComponents.SuggestionsWsResponse.Category;
-import static org.sonarqube.ws.WsComponents.SuggestionsWsResponse.Organization;
public class SuggestionsActionTest {
private static final String[] SUGGESTION_QUALIFIERS = Stream.of(SuggestionCategory.values())
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ComponentIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
public ResourceTypesRule resourceTypes = new ResourceTypesRule();
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
+import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.Logger;
import org.sonar.core.config.PurgeConstants;
+import org.sonar.core.config.PurgeProperties;
import org.sonar.db.DbSession;
import org.sonar.db.purge.IdUuidPair;
import org.sonar.db.purge.PurgeConfiguration;
import org.sonar.db.purge.period.DefaultPeriodCleaner;
import static java.util.Collections.emptyList;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
private PurgeProfiler profiler = mock(PurgeProfiler.class);
private DefaultPeriodCleaner periodCleaner = mock(DefaultPeriodCleaner.class);
private PurgeListener purgeListener = mock(PurgeListener.class);
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings(new PropertyDefinitions(PurgeProperties.all()));
@Before
public void before() {
public void no_profiling_when_property_is_false() {
settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, false);
- underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings, emptyList());
+ underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings.asConfig(), emptyList());
verify(profiler, never()).dump(anyLong(), any(Logger.class));
}
public void profiling_when_property_is_true() {
settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, true);
- underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings, emptyList());
+ underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings.asConfig(), emptyList());
verify(profiler).dump(anyLong(), any(Logger.class));
}
public void call_period_cleaner_index_client_and_purge_dao() {
settings.setProperty(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES, 5);
- underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings, emptyList());
+ underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings.asConfig(), emptyList());
- verify(periodCleaner).clean(any(DbSession.class), anyString(), any(Settings.class));
+ verify(periodCleaner).clean(any(DbSession.class), anyString(), any(Configuration.class));
verify(dao).purge(any(DbSession.class), any(PurgeConfiguration.class), any(PurgeListener.class), any(PurgeProfiler.class));
}
public void if_dao_purge_fails_it_should_not_interrupt_program_execution() {
doThrow(RuntimeException.class).when(dao).purge(any(DbSession.class), any(PurgeConfiguration.class), any(PurgeListener.class), any(PurgeProfiler.class));
- underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings, emptyList());
+ underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings.asConfig(), emptyList());
verify(dao).purge(any(DbSession.class), any(PurgeConfiguration.class), any(PurgeListener.class), any(PurgeProfiler.class));
}
@Test
public void if_profiler_cleaning_fails_it_should_not_interrupt_program_execution() {
- doThrow(RuntimeException.class).when(periodCleaner).clean(any(DbSession.class), anyString(), any(Settings.class));
+ doThrow(RuntimeException.class).when(periodCleaner).clean(any(DbSession.class), anyString(), any(Configuration.class));
- underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings, emptyList());
+ underTest.purge(mock(DbSession.class), mock(IdUuidPair.class), settings.asConfig(), emptyList());
- verify(periodCleaner).clean(any(DbSession.class), anyString(), any(Settings.class));
+ verify(periodCleaner).clean(any(DbSession.class), anyString(), any(Configuration.class));
}
}
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.Duration;
import org.sonar.core.issue.DefaultIssue;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.issue.ComponentIssuesRepositoryRule;
import org.sonar.server.computation.task.projectanalysis.measure.Measure;
@Rule
public ComponentIssuesRepositoryRule componentIssuesRepository = new ComponentIssuesRepositoryRule(treeRootHolder);
- SettingsRepository settingsRepository = mock(SettingsRepository.class);
+ ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class);
@Test
public void get_component() throws Exception {
@Test
public void get_string_settings() throws Exception {
- org.sonar.api.config.Settings serverSettings = new MapSettings();
+ MapSettings serverSettings = new MapSettings();
serverSettings.setProperty("prop", "value");
- when(settingsRepository.getSettings(FILE_1)).thenReturn(serverSettings);
+ when(settingsRepository.getConfiguration(FILE_1)).thenReturn(serverSettings.asConfig());
MeasureComputerContextImpl underTest = newContext(FILE_1_REF);
assertThat(underTest.getSettings().getString("prop")).isEqualTo("value");
@Test
public void get_string_array_settings() throws Exception {
- org.sonar.api.config.Settings serverSettings = new MapSettings();
+ MapSettings serverSettings = new MapSettings();
serverSettings.setProperty("prop", "1,3.4,8,50");
- when(settingsRepository.getSettings(FILE_1)).thenReturn(serverSettings);
+ when(settingsRepository.getConfiguration(FILE_1)).thenReturn(serverSettings.asConfig());
MeasureComputerContextImpl underTest = newContext(FILE_1_REF);
assertThat(underTest.getSettings().getStringArray("prop")).containsExactly("1", "3.4", "8", "50");
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program 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.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.server.computation.task.projectanalysis.component;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.api.config.Configuration;
+import org.sonar.api.config.internal.MapSettings;
+import org.sonar.api.utils.System2;
+import org.sonar.ce.settings.ProjectConfigurationFactory;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.DbTester;
+import org.sonar.db.component.ComponentDto;
+import org.sonar.db.component.ComponentTesting;
+import org.sonar.db.property.PropertyDto;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.PROJECT;
+
+public class ConfigurationRepositoryTest {
+
+ private static final Component ROOT = ReportComponent.builder(PROJECT, 1).setKey("ROOT").build();
+
+ @Rule
+ public final DbTester dbTester = DbTester.create(System2.INSTANCE);
+
+ DbClient dbClient = dbTester.getDbClient();
+
+ DbSession session;
+
+ MapSettings globalSettings;
+
+ ConfigurationRepository underTest;
+
+ @Before
+ public void createDao() {
+ globalSettings = new MapSettings();
+ session = dbClient.openSession(false);
+ underTest = new ConfigurationRepositoryImpl(new ProjectConfigurationFactory(globalSettings, dbClient));
+ }
+
+ @After
+ public void tearDown() {
+ session.close();
+ }
+
+ @Test
+ public void get_project_settings_from_global_settings() {
+ globalSettings.setProperty("key", "value");
+
+ Configuration config = underTest.getConfiguration(ROOT);
+
+ assertThat(config.get("key")).hasValue("value");
+ }
+
+ @Test
+ public void get_project_settings_from_db() {
+ ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert()).setKey(ROOT.getKey());
+ dbClient.componentDao().insert(session, project);
+ dbClient.propertiesDao().saveProperty(session, new PropertyDto().setResourceId(project.getId()).setKey("key").setValue("value"));
+ session.commit();
+
+ Configuration config = underTest.getConfiguration(ROOT);
+
+ assertThat(config.get("key")).hasValue("value");
+ }
+
+ @Test
+ public void call_twice_get_project_settings() {
+ globalSettings.setProperty("key", "value");
+
+ Configuration config = underTest.getConfiguration(ROOT);
+ assertThat(config.get("key")).hasValue("value");
+
+ config = underTest.getConfiguration(ROOT);
+ assertThat(config.get("key")).hasValue("value");
+ }
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program 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.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.computation.task.projectanalysis.component;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.sonar.api.config.Settings;
-import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.System2;
-import org.sonar.ce.settings.ProjectSettingsFactory;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.DbTester;
-import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.property.PropertyDto;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.PROJECT;
-
-
-public class SettingsRepositoryTest {
-
- private static final Component ROOT = ReportComponent.builder(PROJECT, 1).setKey("ROOT").build();
-
- @Rule
- public final DbTester dbTester = DbTester.create(System2.INSTANCE);
-
- DbClient dbClient = dbTester.getDbClient();
-
- DbSession session;
-
- MapSettings globalSettings;
-
- SettingsRepository underTest;
-
- @Before
- public void createDao() {
- globalSettings = new MapSettings();
- session = dbClient.openSession(false);
- underTest = new SettingsRepositoryImpl(new ProjectSettingsFactory(globalSettings, dbClient));
- }
-
- @After
- public void tearDown() {
- session.close();
- }
-
- @Test
- public void get_project_settings_from_global_settings() {
- globalSettings.setProperty("key", "value");
-
- Settings settings = underTest.getSettings(ROOT);
-
- assertThat(settings.getString("key")).isEqualTo("value");
- }
-
- @Test
- public void get_project_settings_from_db() {
- ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert()).setKey(ROOT.getKey());
- dbClient.componentDao().insert(session, project);
- dbClient.propertiesDao().saveProperty(session, new PropertyDto().setResourceId(project.getId()).setKey("key").setValue("value"));
- session.commit();
-
- Settings settings = underTest.getSettings(ROOT);
-
- assertThat(settings.getString("key")).isEqualTo("value");
- }
-
- @Test
- public void call_twice_get_project_settings() {
- globalSettings.setProperty("key", "value");
-
- Settings settings = underTest.getSettings(ROOT);
- assertThat(settings.getString("key")).isEqualTo("value");
-
- settings = underTest.getSettings(ROOT);
- assertThat(settings.getString("key")).isEqualTo("value");
- }
-}
*/
package org.sonar.server.computation.task.projectanalysis.component;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
/**
- * Implementation of {@link SettingsRepository} that always return the
- * same mutable {@link Settings}, whatever the component.
+ * Implementation of {@link ConfigurationRepository} that always return the
+ * same {@link Configuration}, whatever the component.
*/
-public class TestSettingsRepository implements SettingsRepository {
+public class TestSettingsRepository implements ConfigurationRepository {
- private final Settings settings;
+ private final Configuration config;
- public TestSettingsRepository(Settings settings) {
- this.settings = settings;
+ public TestSettingsRepository(Configuration config) {
+ this.config = config;
}
@Override
- public Settings getSettings(Component component) {
- return settings;
+ public Configuration getConfiguration(Component component) {
+ return config;
}
}
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
static final String OTHER_FILE_KEY = "OTHER_FILE_KEY";
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
- IntegrateCrossProjectDuplications underTest = new IntegrateCrossProjectDuplications(settings, duplicationRepository);
+ IntegrateCrossProjectDuplications underTest = new IntegrateCrossProjectDuplications(settings.asConfig(), duplicationRepository);
@Test
public void add_duplications_from_two_blocks() {
.setIndexInFile(1)
.setLines(32, 45)
.setUnit(5, 20)
- .build()
- );
+ .build());
Collection<Block> duplicatedBlocks = asList(
new Block.Builder()
assertThat(duplicationRepository.getDuplications(ORIGIN_FILE))
.containsExactly(
- crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))
- );
+ crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55)));
}
@Test
.setIndexInFile(0)
.setLines(30, 45)
.setUnit(0, 10)
- .build()
- );
+ .build());
Collection<Block> duplicatedBlocks = singletonList(
new Block.Builder()
.setBlockHash(new ByteArray("a8998353e96320ec"))
.setIndexInFile(0)
.setLines(40, 55)
- .build()
- );
+ .build());
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
assertThat(duplicationRepository.getDuplications(ORIGIN_FILE))
.containsExactly(
- crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))
- );
+ crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55)));
}
@Test
.setIndexInFile(0)
.setLines(46, 60)
.setUnit(0, 10)
- .build()
- );
+ .build());
Collection<Block> duplicatedBlocks = singletonList(
new Block.Builder()
.setBlockHash(new ByteArray("a8998353e96320ed"))
.setIndexInFile(0)
.setLines(40, 55)
- .build()
- );
+ .build());
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
.setIndexInFile(0)
.setLines(30, 45)
.setUnit(0, 4)
- .build()
- );
+ .build());
Collection<Block> duplicatedBlocks = singletonList(
new Block.Builder()
.setBlockHash(new ByteArray("a8998353e96320ec"))
.setIndexInFile(0)
.setLines(40, 55)
- .build()
- );
+ .build());
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
.setIndexInFile(0)
.setLines(30, 45)
.setUnit(0, 10)
- .build()
- );
+ .build());
underTest.computeCpd(ORIGIN_FILE, originBlocks, Collections.<Block>emptyList());
.setIndexInFile(0)
.setLines(30, 45)
.setUnit(0, 0)
- .build()
- );
+ .build());
Collection<Block> duplicatedBlocks = singletonList(
new Block.Builder()
.setBlockHash(new ByteArray("a8998353e96320ec"))
.setIndexInFile(0)
.setLines(40, 55)
- .build()
- );
+ .build());
underTest.computeCpd(javaFile, originBlocks, duplicatedBlocks);
assertThat(duplicationRepository.getDuplications(ORIGIN_FILE))
.containsExactly(
- crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))
- );
+ crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55)));
}
@Test
.setIndexInFile(0)
.setLines(30, 45)
.setUnit(0, 100)
- .build()
- );
+ .build());
Collection<Block> duplicatedBlocks = singletonList(
new Block.Builder()
.setBlockHash(new ByteArray("a8998353e96320ec"))
.setIndexInFile(0)
.setLines(40, 55)
- .build()
- );
+ .build());
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
assertThat(duplicationRepository.getDuplications(ORIGIN_FILE))
.containsExactly(
- crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))
- );
+ crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55)));
}
@Test
duplicatedBlocks.add(
blockBuilder
.setResourceId(randomAlphanumeric(16))
- .build()
- );
+ .build());
}
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
blockBuilder
.setResourceId("resource" + i)
.setBlockHash(new ByteArray(hash))
- .build()
- );
+ .build());
}
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.db.DbTester;
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolderImpl;
import org.sonar.server.computation.task.projectanalysis.analysis.Organization;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TestSettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
@Rule
public TreeRootHolderRule rootHolder = new TreeRootHolderRule().setRoot(DUMB_PROJECT);
- private Settings settings = new MapSettings();
- private SettingsRepository settingsRepository = new TestSettingsRepository(settings);
+ private MapSettings settings = new MapSettings();
+ private ConfigurationRepository settingsRepository = new TestSettingsRepository(settings.asConfig());
private AnalysisMetadataHolderImpl analysisMetadataHolder = new AnalysisMetadataHolderImpl();
private OrganizationDto organizationDto;
public class ScmAccountToUserLoaderTest {
@org.junit.Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@org.junit.Rule
public LogTester logTester = new LogTester();
import org.sonar.api.rule.RuleKey;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.computation.task.projectanalysis.component.Component;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import static java.util.Arrays.asList;
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT);
- SettingsRepository settingsRepository = mock(SettingsRepository.class);
+ ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class);
@Test
public void accept_everything_when_no_filter_properties() throws Exception {
public void ignore_many_rules() throws Exception {
IssueFilter underTest = newIssueFilter(newSettings(
asList("xoo:x1", "**/xoo/File1*", "xoo:x2", "**/xoo/File1*"),
- Collections.<String>emptyList())
- );
+ Collections.<String>emptyList()));
assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse();
assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isTrue();
public void include_many_rules() throws Exception {
IssueFilter underTest = newIssueFilter(newSettings(
Collections.<String>emptyList(),
- asList("xoo:x1", "**/xoo/File1*", "xoo:x2", "**/xoo/File1*")
- ));
+ asList("xoo:x1", "**/xoo/File1*", "xoo:x2", "**/xoo/File1*")));
assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isTrue();
assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isFalse();
newIssueFilter(newSettings(Collections.<String>emptyList(), asList("", "**")));
}
- private IssueFilter newIssueFilter(Settings settings) {
- when(settingsRepository.getSettings(PROJECT)).thenReturn(settings);
+ private IssueFilter newIssueFilter(MapSettings settings) {
+ when(settingsRepository.getConfiguration(PROJECT)).thenReturn(settings.asConfig());
return new IssueFilter(treeRootHolder, settingsRepository);
}
- private static Settings newSettings(List<String> exclusionsProperties, List<String> inclusionsProperties) {
- Settings settings = new MapSettings();
+ private static MapSettings newSettings(List<String> exclusionsProperties, List<String> inclusionsProperties) {
+ MapSettings settings = new MapSettings();
if (!exclusionsProperties.isEmpty()) {
addProperties(exclusionsProperties, "ignore", settings);
}
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.MessageException;
public class RatingSettingsTest {
- private Settings settings;
+ private MapSettings settings;
@Rule
public ExpectedException throwable = ExpectedException.none();
@Test
public void load_rating_grid() {
settings.setProperty(CoreProperties.RATING_GRID, "1,3.4,8,50");
- RatingSettings configurationLoader = new RatingSettings(settings);
+ RatingSettings configurationLoader = new RatingSettings(settings.asConfig());
double[] grid = configurationLoader.getRatingGrid().getGridValues();
assertThat(grid).hasSize(4);
@Test
public void load_work_units_for_language() {
settings.setProperty(DEVELOPMENT_COST, "50");
- RatingSettings configurationLoader = new RatingSettings(settings);
+ RatingSettings configurationLoader = new RatingSettings(settings.asConfig());
assertThat(configurationLoader.getDevCost("defaultLanguage")).isEqualTo(50L);
}
settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40");
settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY, CoreMetrics.COMPLEXITY_KEY);
- RatingSettings configurationLoader = new RatingSettings(settings);
+ RatingSettings configurationLoader = new RatingSettings(settings.asConfig());
assertThat(configurationLoader.getDevCost(aLanguage)).isEqualTo(30L);
assertThat(configurationLoader.getDevCost(anotherLanguage)).isEqualTo(40L);
@Test
public void fail_on_invalid_rating_grid_configuration() {
- RatingSettings configurationLoader = new RatingSettings(settings);
+ RatingSettings configurationLoader = new RatingSettings(settings.asConfig());
throwable.expect(IllegalArgumentException.class);
settings.setProperty(CoreProperties.RATING_GRID, "a b c");
settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY, aLanguage);
settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40");
- RatingSettings configurationLoader = new RatingSettings(settings);
+ RatingSettings configurationLoader = new RatingSettings(settings.asConfig());
assertThat(configurationLoader.getDevCost(aLanguage)).isEqualTo(40L);
}
throwable.expectMessage("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " +
"Contact your administrator to update this configuration in the global administration section of SonarQube.");
- new RatingSettings(settings);
+ new RatingSettings(settings.asConfig());
}
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.Component;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.ReportComponent;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.ViewsComponent;
import org.sonar.server.computation.task.projectanalysis.period.Period;
private PeriodHolderImpl periodsHolder = new PeriodHolderImpl();
private DbClient dbClient = dbTester.getDbClient();
- private Settings settings = new MapSettings();
- private SettingsRepository settingsRepository = mock(SettingsRepository.class);
+ private MapSettings settings = new MapSettings();
+ private ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class);
private LoadPeriodsStep underTest = new LoadPeriodsStep(dbClient, settingsRepository, treeRootHolder, analysisMetadataHolder, periodsHolder);
private void setupRoot(Component root) {
treeRootHolder.setRoot(root);
- when(settingsRepository.getSettings(root)).thenReturn(settings);
+ when(settingsRepository.getConfiguration(root)).thenReturn(settings.asConfig());
}
@DataProvider
underTest.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Leak period is set to deprecated value 'previous_analysis'. This value will be removed in next SonarQube LTS, please use another one instead.");
+ assertThat(logTester.logs(LoggerLevel.WARN))
+ .containsOnly("Leak period is set to deprecated value 'previous_analysis'. This value will be removed in next SonarQube LTS, please use another one instead.");
}
@Test
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.purge.IdUuidPair;
import org.sonar.server.computation.dbcleaner.ProjectCleaner;
import org.sonar.server.computation.task.projectanalysis.component.Component;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.MutableDbIdsRepositoryRule;
import org.sonar.server.computation.task.projectanalysis.component.MutableDisabledComponentsHolder;
import org.sonar.server.computation.task.projectanalysis.component.ReportComponent;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.ViewsComponent;
import org.sonar.server.computation.task.step.ComputationStep;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public MutableDbIdsRepositoryRule dbIdsRepository = MutableDbIdsRepositoryRule.standalone();
private ProjectCleaner projectCleaner = mock(ProjectCleaner.class);
- private SettingsRepository settingsRepository = mock(SettingsRepository.class);
+ private ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class);
private MutableDisabledComponentsHolder disabledComponentsHolder = mock(MutableDisabledComponentsHolder.class, RETURNS_DEEP_STUBS);
- private PurgeDatastoresStep underTest = new PurgeDatastoresStep(mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS), projectCleaner, dbIdsRepository, treeRootHolder, settingsRepository, disabledComponentsHolder);
+ private PurgeDatastoresStep underTest = new PurgeDatastoresStep(mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS), projectCleaner, dbIdsRepository, treeRootHolder,
+ settingsRepository, disabledComponentsHolder);
@Test
public void call_purge_method_of_the_purge_task_for_project() {
private void verify_call_purge_method_of_the_purge_task(Component project) {
treeRootHolder.setRoot(project);
- when(settingsRepository.getSettings(project)).thenReturn(new MapSettings());
+ when(settingsRepository.getConfiguration(project)).thenReturn(new MapSettings().asConfig());
dbIdsRepository.setComponentId(project, PROJECT_ID);
underTest.execute();
ArgumentCaptor<IdUuidPair> argumentCaptor = ArgumentCaptor.forClass(IdUuidPair.class);
- verify(projectCleaner).purge(any(DbSession.class), argumentCaptor.capture(), any(Settings.class), anyList());
+ verify(projectCleaner).purge(any(DbSession.class), argumentCaptor.capture(), any(Configuration.class), anyList());
assertThat(argumentCaptor.getValue().getId()).isEqualTo(PROJECT_ID);
assertThat(argumentCaptor.getValue().getUuid()).isEqualTo(PROJECT_UUID);
}
private static Object[][] dataproviderFromComponentTypeValues(Predicate<Component.Type> predicate) {
return FluentIterable.from(asList(Component.Type.values()))
- .filter(predicate)
- .transform(WrapInSingleElementArray.INSTANCE)
- .toArray(Object[].class);
+ .filter(predicate)
+ .transform(WrapInSingleElementArray.INSTANCE)
+ .toArray(Object[].class);
}
@Override
import org.junit.rules.ExpectedException;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.computation.task.projectanalysis.component.Component;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.ReportComponent;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.VisitException;
import org.sonar.server.computation.task.projectanalysis.qualitygate.Condition;
@Rule
public MutableQualityGateHolderRule mutableQualityGateHolder = new MutableQualityGateHolderRule();
- private SettingsRepository settingsRepository = mock(SettingsRepository.class);
+ private ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class);
private QualityGateService qualityGateService = mock(QualityGateService.class);
private LoadQualityGateStep underTest = new LoadQualityGateStep(treeRootHolder, settingsRepository, qualityGateService, mutableQualityGateHolder);
public void execute_sets_default_QualityGate_when_project_has_no_settings() {
ReportComponent root = ReportComponent.builder(Component.Type.PROJECT, 1).setKey(PROJECT_KEY).addChildren(ReportComponent.builder(Component.Type.FILE, 2).build()).build();
treeRootHolder.setRoot(root);
- when(settingsRepository.getSettings(root)).thenReturn(new MapSettings());
+ when(settingsRepository.getConfiguration(root)).thenReturn(new MapSettings().asConfig());
underTest.execute();
verifyNoQualityGate();
// verify only project is processed
- verify(settingsRepository).getSettings(root);
+ verify(settingsRepository).getConfiguration(root);
verifyNoMoreInteractions(settingsRepository);
}
.andMessage(format("Unsupported value (%s) in property sonar.qualitygate", "10 sds")));
treeRootHolder.setRoot(PROJECT_ALONE);
- when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", "10 sds"));
+ when(settingsRepository.getConfiguration(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", "10 sds").asConfig());
underTest.execute();
}
@Test
public void execute_sets_default_QualityGate_if_it_can_not_be_found_by_service() {
treeRootHolder.setRoot(PROJECT_ALONE);
- when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", 10));
+ when(settingsRepository.getConfiguration(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", 10).asConfig());
when(qualityGateService.findById(10)).thenReturn(Optional.<QualityGate>absent());
underTest.execute();
QualityGate qualityGate = new QualityGate(465, "name", Collections.<Condition>emptyList());
treeRootHolder.setRoot(PROJECT_ALONE);
- when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", 10));
+ when(settingsRepository.getConfiguration(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", 10).asConfig());
when(qualityGateService.findById(10)).thenReturn(Optional.of(qualityGate));
underTest.execute();
private WebhookCaller newSender() {
SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("6.2"), SonarQubeSide.SERVER);
- return new WebhookCallerImpl(system, new OkHttpClientProvider().provide(new MapSettings(), runtime));
+ return new WebhookCallerImpl(system, new OkHttpClientProvider().provide(new MapSettings().asConfig(), runtime));
}
}
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
-import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
+import org.sonar.server.computation.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.server.computation.task.projectanalysis.component.TestSettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
}
private void execute() {
- SettingsRepository settingsRepository = new TestSettingsRepository(settings);
+ ConfigurationRepository settingsRepository = new TestSettingsRepository(settings.asConfig());
WebhookPostTask task = new WebhookPostTask(rootHolder, settingsRepository, payloadFactory, caller, deliveryStorage);
PostProjectAnalysisTaskTester.of(task)
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
@Rule
public LogTester logTester = new LogTester();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private EsClientProvider underTest = new EsClientProvider();
private String localhost;
settings.setProperty(ProcessProperties.SEARCH_HOST, localhost);
settings.setProperty(ProcessProperties.SEARCH_PORT, 8080);
- EsClient client = underTest.provide(settings);
+ EsClient client = underTest.provide(settings.asConfig());
TransportClient transportClient = (TransportClient) client.nativeClient();
assertThat(transportClient.transportAddresses()).hasSize(1);
TransportAddress address = transportClient.transportAddresses().get(0);
assertThat(logTester.logs(LoggerLevel.INFO)).has(new Condition<>(s -> s.contains("Connected to local Elasticsearch: [" + localhost + ":8080]"), ""));
// keep in cache
- assertThat(underTest.provide(settings)).isSameAs(client);
+ assertThat(underTest.provide(settings.asConfig())).isSameAs(client);
}
@Test
settings.setProperty(ProcessProperties.CLUSTER_SEARCH_DISABLED, true);
settings.setProperty(ProcessProperties.CLUSTER_SEARCH_HOSTS, format("%s:8080,%s:8081", localhost, localhost));
- EsClient client = underTest.provide(settings);
+ EsClient client = underTest.provide(settings.asConfig());
TransportClient transportClient = (TransportClient) client.nativeClient();
assertThat(transportClient.transportAddresses()).hasSize(2);
TransportAddress address = transportClient.transportAddresses().get(0);
assertThat(logTester.logs(LoggerLevel.INFO)).has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [" + localhost + ":8080, " + localhost + ":8081]"), ""));
// keep in cache
- assertThat(underTest.provide(settings)).isSameAs(client);
+ assertThat(underTest.provide(settings.asConfig())).isSameAs(client);
}
@Test
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(format("Port number out of range: %s:100000", localhost));
- underTest.provide(settings);
+ underTest.provide(settings.asConfig());
}
@Test
public void es_client_provider_must_throw_ISE_when_incorrect_port_is_used() throws Exception {
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, true);
+ settings.setProperty(ProcessProperties.SEARCH_HOST, "localhost");
settings.setProperty(ProcessProperties.SEARCH_PORT, "100000");
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Port out of range: 100000");
- underTest.provide(settings);
+ underTest.provide(settings.asConfig());
}
@Test
settings.setProperty(ProcessProperties.CLUSTER_SEARCH_DISABLED, true);
settings.setProperty(ProcessProperties.CLUSTER_SEARCH_HOSTS, format("%s,%s:8081", localhost, localhost));
- EsClient client = underTest.provide(settings);
+ EsClient client = underTest.provide(settings.asConfig());
TransportClient transportClient = (TransportClient) client.nativeClient();
assertThat(transportClient.transportAddresses()).hasSize(2);
TransportAddress address = transportClient.transportAddresses().get(0);
assertThat(logTester.logs(LoggerLevel.INFO)).has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [" + localhost + ":9001, " + localhost + ":8081]"), ""));
// keep in cache
- assertThat(underTest.provide(settings)).isSameAs(client);
+ assertThat(underTest.provide(settings.asConfig())).isSameAs(client);
}
}
import org.elasticsearch.search.SearchHit;
import org.junit.rules.ExternalResource;
import org.sonar.api.config.internal.MapSettings;
+import org.sonar.core.config.ConfigurationProvider;
import org.sonar.core.platform.ComponentContainer;
import static com.google.common.base.Preconditions.checkState;
if (!indexDefinitions.isEmpty()) {
container = new ComponentContainer();
container.addSingleton(new MapSettings());
+ container.addSingleton(new ConfigurationProvider());
container.addSingletons(indexDefinitions);
container.addSingleton(client);
container.addSingleton(IndexDefinitions.class);
public void create_index() throws Exception {
assertThat(mappings()).isEmpty();
- IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new MapSettings());
+ IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new MapSettings().asConfig());
registry.start();
IndexCreator creator = new IndexCreator(es.client(), registry);
creator.start();
assertThat(mappings()).isEmpty();
// v1
- IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new MapSettings());
+ IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new MapSettings().asConfig());
registry.start();
IndexCreator creator = new IndexCreator(es.client(), registry);
creator.start();
assertThat(hashV1).isNotEmpty();
// v2
- registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinitionV2()}, new MapSettings());
+ registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinitionV2()}, new MapSettings().asConfig());
registry.start();
creator = new IndexCreator(es.client(), registry);
creator.start();
}
private void emulateStartup(StartupIndexer indexer) {
- new IndexerStartupTask(es.client(), settings, indexer).execute();
+ new IndexerStartupTask(es.client(), settings.asConfig(), indexer).execute();
}
}
@Test
public void default_shards_and_replicas() {
NewIndex index = new NewIndex("issues");
- index.configureShards(new MapSettings(), 5);
+ index.configureShards(new MapSettings().asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_SHARDS)).isEqualTo("5");
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
NewIndex index = new NewIndex("issues");
MapSettings settings = new MapSettings();
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, "true");
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_SHARDS)).isEqualTo("5");
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("1");
}
NewIndex index = new NewIndex("issues");
MapSettings settings = new MapSettings();
settings.setProperty("sonar.search.issues.shards", "3");
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_SHARDS)).isEqualTo("3");
// keep default value
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
public void default_number_of_replicas_on_standalone_instance_must_be_0() {
NewIndex index = new NewIndex("issues");
MapSettings settings = new MapSettings();
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
NewIndex index = new NewIndex("issues");
MapSettings settings = new MapSettings();
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, "false");
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
NewIndex index = new NewIndex("issues");
MapSettings settings = new MapSettings();
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, "true");
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("1");
}
MapSettings settings = new MapSettings();
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, "true");
settings.setProperty(ProcessProperties.SEARCH_REPLICAS, "0");
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
NewIndex index = new NewIndex("issues");
MapSettings settings = new MapSettings();
settings.setProperty(ProcessProperties.SEARCH_REPLICAS, "3");
- index.configureShards(settings, 5);
+ index.configureShards(settings.asConfig(), 5);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("3");
}
// authorization type
NewIndex.NewIndexType authorizationType = index.getTypes().get("authorization");
- assertThat(getAttributeAsMap(authorizationType,"_parent")).isNull();
- assertThat(getAttributeAsMap(authorizationType,"_routing")).containsExactly(entry("required", true));
+ assertThat(getAttributeAsMap(authorizationType, "_parent")).isNull();
+ assertThat(getAttributeAsMap(authorizationType, "_routing")).containsExactly(entry("required", true));
}
private static Map<String, Object> getAttributeAsMap(NewIndex.NewIndexType type, String attributeKey) {
public DbTester dbTester = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
private DbClient dbClient = dbTester.getDbClient();
private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester);
public class IssueIndexDebtTest {
@Rule
- public EsTester tester = new EsTester(new IssueIndexDefinition(new MapSettings()), new ViewIndexDefinition(new MapSettings()));
+ public EsTester tester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()), new ViewIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Test
public void define() {
- IssueIndexDefinition def = new IssueIndexDefinition(new MapSettings());
+ IssueIndexDefinition def = new IssueIndexDefinition(new MapSettings().asConfig());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
@Rule
public EsTester tester = new EsTester(
- new IssueIndexDefinition(new MapSettings()),
- new ViewIndexDefinition(new MapSettings()),
- new RuleIndexDefinition(new MapSettings()));
+ new IssueIndexDefinition(new MapSettings().asConfig()),
+ new ViewIndexDefinition(new MapSettings().asConfig()),
+ new RuleIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(system2);
@Rule
private System2 system2 = System2.INSTANCE;
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester dbTester = DbTester.create(system2);
@Rule
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.EmailSettings;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.db.DbTester;
@Rule
public DbTester db = DbTester.create();
- private Settings settings = new MapSettings().setProperty(SERVER_BASE_URL, "http://nemo.sonarsource.org");
+ private MapSettings settings = new MapSettings().setProperty(SERVER_BASE_URL, "http://nemo.sonarsource.org");
- private IssueChangesEmailTemplate underTest = new IssueChangesEmailTemplate(db.getDbClient(), new EmailSettings(settings));
+ private IssueChangesEmailTemplate underTest = new IssueChangesEmailTemplate(db.getDbClient(), new EmailSettings(settings.asConfig()));
@Test
public void should_ignore_non_issue_changes() {
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(system2);
private void verifyContentOfPreloadedSearchResponseData(IssueDto issue) {
SearchResponseData preloadedSearchResponseData = preloadedSearchResponseDataCaptor.getValue();
assertThat(preloadedSearchResponseData.getIssues())
- .extracting(IssueDto::getKey)
- .containsOnly(issue.getKey());
+ .extracting(IssueDto::getKey)
+ .containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
- .containsOnly(issue.getRuleKey());
+ .extracting(RuleDefinitionDto::getKey)
+ .containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
- .extracting(ComponentDto::uuid)
- .containsOnly(issue.getComponentUuid(), issue.getProjectUuid());
+ .extracting(ComponentDto::uuid)
+ .containsOnly(issue.getComponentUuid(), issue.getProjectUuid());
}
private UserDto insertUser(String login) {
@Rule
public DbTester db = DbTester.create();
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
public DbTester dbTester = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private void verifyContentOfPreloadedSearchResponseData(IssueDto issue) {
SearchResponseData preloadedSearchResponseData = preloadedSearchResponseDataCaptor.getValue();
assertThat(preloadedSearchResponseData.getIssues())
- .extracting(IssueDto::getKey)
- .containsOnly(issue.getKey());
+ .extracting(IssueDto::getKey)
+ .containsOnly(issue.getKey());
assertThat(preloadedSearchResponseData.getRules())
- .extracting(RuleDefinitionDto::getKey)
- .containsOnly(issue.getRuleKey());
+ .extracting(RuleDefinitionDto::getKey)
+ .containsOnly(issue.getRuleKey());
assertThat(preloadedSearchResponseData.getComponents())
- .extracting(ComponentDto::uuid)
- .containsOnly(issue.getComponentUuid(), issue.getProjectUuid());
+ .extracting(ComponentDto::uuid)
+ .containsOnly(issue.getComponentUuid(), issue.getProjectUuid());
}
}
@Rule
public DbTester dbTester = DbTester.create();
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester dbTester = DbTester.create();
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()), new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()), new RuleIndexDefinition(new MapSettings().asConfig()));
private IssueIndexer issueIndexer = new IssueIndexer(es.client(), new IssueIteratorFactory(db.getDbClient()));
private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
DbClient dbClient = db.getDbClient();
ComponentDto project;
private static final String DEFAULT_PROJECT_KEY = "project-key";
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
WsTester ws;
DbClient dbClient = db.getDbClient();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private static final GroupDto GROUP2 = newGroupDto();
@Rule
- public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
import org.sonar.server.es.EsTester;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
+import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
import org.sonar.server.permission.index.AuthorizationTypeSupport;
import org.sonar.server.permission.index.PermissionIndexerDao;
import org.sonar.server.permission.index.PermissionIndexerTester;
import static org.sonar.server.component.ws.FilterParser.Operator.GT;
import static org.sonar.server.component.ws.FilterParser.Operator.LT;
import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.INDEX_TYPE_PROJECT_MEASURES;
-import static org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
public class ProjectMeasuresIndexTextSearchTest {
private static final OrganizationDto ORG = OrganizationTesting.newOrganizationDto();
@Rule
- public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
private System2 system2 = System2.INSTANCE;
@Rule
- public EsTester esTester = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester dbTester = DbTester.create(system2);
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.db.property.PropertiesDao;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyString;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.same;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
private NotificationDispatcher commentOnIssueCreatedByMe = mock(NotificationDispatcher.class);
private NotificationDispatcher qualityGateChange = mock(NotificationDispatcher.class);
private DbClient dbClient = mock(DbClient.class);
- private NotificationService service = new NotificationService(dbClient, new NotificationDispatcher[]{commentOnIssueAssignedToMe, commentOnIssueCreatedByMe, qualityGateChange});
+ private NotificationService service = new NotificationService(dbClient, new NotificationDispatcher[] {commentOnIssueAssignedToMe, commentOnIssueCreatedByMe, qualityGateChange});
private NotificationDaemon underTest = null;
private void setUpMocks() {
when(qualityGateChange.getType()).thenReturn("qgate-changes");
when(manager.getFromQueue()).thenReturn(notification).thenReturn(null);
- Settings settings = new MapSettings().setProperty("sonar.notifications.delay", 1L);
+ MapSettings settings = new MapSettings(new PropertyDefinitions(NotificationDaemon.class)).setProperty("sonar.notifications.delay", 1L);
- underTest = new NotificationDaemon(settings, manager, service);
+ underTest = new NotificationDaemon(settings.asConfig(), manager, service);
}
/**
@Test
public void scenario3() {
setUpMocks();
- doAnswer(addUser(ASSIGNEE_SIMON, new NotificationChannel[]{emailChannel, gtalkChannel}))
+ doAnswer(addUser(ASSIGNEE_SIMON, new NotificationChannel[] {emailChannel, gtalkChannel}))
.when(commentOnIssueAssignedToMe).dispatch(same(notification), any(NotificationDispatcher.Context.class));
underTest.start();
}
private static Answer<Object> addUser(final String user, final NotificationChannel channel) {
- return addUser(user, new NotificationChannel[]{channel});
+ return addUser(user, new NotificationChannel[] {channel});
}
private static Answer<Object> addUser(final String user, final NotificationChannel[] channels) {
@Rule
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
private UserIndexer userIndexer = new UserIndexer(dbClient, es.client());
private UserIndex userIndex = new UserIndex(es.client());
private DefaultGroupCreator defaultGroupCreator = new DefaultGroupCreatorImpl(dbClient);
- private OrganizationCreationImpl underTest = new OrganizationCreationImpl(dbClient, system2, uuidFactory, organizationValidation, settings, userIndexer,
+ private OrganizationCreationImpl underTest = new OrganizationCreationImpl(dbClient, system2, uuidFactory, organizationValidation, settings.asConfig(), userIndexer,
builtInQProfileRepositoryRule, defaultGroupCreator);
private UserDto someUser;
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
private UserIndex userIndex = new UserIndex(es.client());
@Rule
public DbTester db = DbTester.create();
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.server.organization.OrganizationValidationImpl;
import org.sonar.server.organization.TestOrganizationFlags;
import org.sonar.server.qualityprofile.BuiltInQProfileRepository;
-import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.index.UserIndex;
import org.sonar.server.user.index.UserIndexDefinition;
@Rule
public DbTester dbTester = DbTester.create(system2).setDisableDefaultOrganization(true);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
private DbClient dbClient = dbTester.getDbClient();
private DbSession dbSession = dbTester.getSession();
- private Settings settings = new MapSettings()
+ private MapSettings settings = new MapSettings()
.setProperty(ORGANIZATIONS_ANYONE_CAN_CREATE, false);
private UuidFactory uuidFactory = mock(UuidFactory.class);
private OrganizationValidation organizationValidation = new OrganizationValidationImpl();
private UserIndexer userIndexer = new UserIndexer(dbClient, es.client());
private UserIndex userIndex = new UserIndex(es.client());
- private OrganizationCreation organizationCreation = new OrganizationCreationImpl(dbClient, system2, uuidFactory, organizationValidation, settings, userIndexer,
+ private OrganizationCreation organizationCreation = new OrganizationCreationImpl(dbClient, system2, uuidFactory, organizationValidation, settings.asConfig(), userIndexer,
mock(BuiltInQProfileRepository.class), new DefaultGroupCreatorImpl(dbClient));
private TestOrganizationFlags organizationFlags = TestOrganizationFlags.standalone().setEnabled(true);
private UserDto user;
- private CreateAction underTest = new CreateAction(settings, userSession, dbClient, new OrganizationsWsSupport(organizationValidation), organizationValidation,
+ private CreateAction underTest = new CreateAction(settings.asConfig(), userSession, dbClient, new OrganizationsWsSupport(organizationValidation), organizationValidation,
organizationCreation, organizationFlags);
private WsActionTester wsTester = new WsActionTester(underTest);
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot();
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create();
private DbClient dbClient = db.getDbClient();
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create();
@Rule
public EsTester esTester = new EsTester(
- new RuleIndexDefinition(new MapSettings()),
- new IssueIndexDefinition(new MapSettings()),
- new ViewIndexDefinition(new MapSettings()),
- new ProjectMeasuresIndexDefinition(new MapSettings()),
- new ComponentIndexDefinition(new MapSettings()));
+ new RuleIndexDefinition(new MapSettings().asConfig()),
+ new IssueIndexDefinition(new MapSettings().asConfig()),
+ new ViewIndexDefinition(new MapSettings().asConfig()),
+ new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()),
+ new ComponentIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
*/
package org.sonar.server.platform;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.Test;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
private static final String AN_IP = "1.2.3.4";
public static final String AN_ORGANIZATION = "corp";
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
ServerIdGenerator idGenerator = mock(ServerIdGenerator.class);
- ServerIdLoader underTest = new ServerIdLoader(settings, idGenerator);
+ ServerIdLoader underTest = new ServerIdLoader(settings.asConfig(), idGenerator);
@Test
public void get_returns_absent_if_id_property_is_not_set() {
settings.setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, AN_IP);
Optional<ServerId> serverIdOpt = underTest.get();
- assertThat(serverIdOpt.isPresent()).isFalse();
+ assertThat(serverIdOpt).isEmpty();
verifyZeroInteractions(idGenerator);
}
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarRuntime;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.Version;
public class ServerImplTest {
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private StartupMetadata state = mock(StartupMetadata.class);
private ServerFileSystem fs = mock(ServerFileSystem.class);
private UrlSettings urlSettings = mock(UrlSettings.class);
private SonarRuntime runtime = mock(SonarRuntime.class);
- private ServerImpl underTest = new ServerImpl(settings, state, fs, urlSettings, runtime);
+ private ServerImpl underTest = new ServerImpl(settings.asConfig(), state, fs, urlSettings, runtime);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
public ExpectedException expectedException = ExpectedException.none();
private LogbackHelper logbackHelper = spy(new LogbackHelper());
- private Settings settings = new MapSettings();
- private ServerLogging underTest = new ServerLogging(logbackHelper, settings);
+ private MapSettings settings = new MapSettings();
+ private ServerLogging underTest = new ServerLogging(logbackHelper, settings.asConfig());
@Rule
public LogTester logTester = new LogTester();
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.core.config.CorePropertyDefinitions;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new MapSettings(new PropertyDefinitions(CorePropertyDefinitions.all()));
+ private MapSettings settings = new MapSettings(new PropertyDefinitions(CorePropertyDefinitions.all()));
@Test
public void use_default_context_path() {
}
@Test
- public void getBaseUrl_throws_NFE_when_port_not_an_int() {
+ public void getBaseUrl_throws_when_port_not_an_int() {
settings.setProperty(PORT_PORPERTY, "not a number");
- expectedException.expect(NumberFormatException.class);
+ expectedException.expect(IllegalStateException.class);
underTest().getBaseUrl();
}
}
private UrlSettings underTest() {
- return new UrlSettings(settings);
+ return new UrlSettings(settings.asConfig());
}
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
@Test
public void cluster_is_disabled_by_default() {
- ClusterImpl underTest = new ClusterImpl(settings);
+ ClusterImpl underTest = new ClusterImpl(settings.asConfig());
assertThat(underTest.isEnabled()).isFalse();
assertThat(underTest.isStartupLeader()).isTrue();
settings.setProperty("sonar.cluster.enabled", "true");
settings.setProperty("sonar.cluster.web.startupLeader", "true");
- ClusterImpl underTest = new ClusterImpl(settings);
+ ClusterImpl underTest = new ClusterImpl(settings.asConfig());
assertThat(underTest.isEnabled()).isTrue();
assertThat(underTest.isStartupLeader()).isTrue();
public void node_is_startup_follower_by_default_in_cluster() {
settings.setProperty("sonar.cluster.enabled", "true");
- ClusterImpl underTest = new ClusterImpl(settings);
+ ClusterImpl underTest = new ClusterImpl(settings.asConfig());
assertThat(underTest.isEnabled()).isTrue();
assertThat(underTest.isStartupLeader()).isFalse();
settings.setProperty("sonar.cluster.enabled", "true");
settings.setProperty("sonar.cluster.web.startupLeader", "false");
- ClusterImpl underTest = new ClusterImpl(settings);
+ ClusterImpl underTest = new ClusterImpl(settings.asConfig());
assertThat(underTest.isEnabled()).isTrue();
assertThat(underTest.isStartupLeader()).isFalse();
package org.sonar.server.platform.db;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.database.DatabaseProperties;
import org.sonar.api.utils.System2;
public class EmbeddedDatabaseFactoryTest {
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private System2 system2 = mock(System2.class);
@Test
EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class);
- EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings, system2) {
+ EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings.asConfig(), system2) {
@Override
EmbeddedDatabase createEmbeddedDatabase() {
return embeddedDatabase;
EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class);
- EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings, system2) {
+ EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings.asConfig(), system2) {
@Override
EmbeddedDatabase createEmbeddedDatabase() {
return embeddedDatabase;
private MapSettings settings = new MapSettings();
private System2 system2 = mock(System2.class);
- private EmbeddedDatabase underTest = new EmbeddedDatabase(settings, system2);
+ private EmbeddedDatabase underTest = new EmbeddedDatabase(settings.asConfig(), system2);
@After
public void tearDown() throws Exception {
public class EsMonitorTest {
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()));
private EsMonitor underTest = new EsMonitor(esTester.client());
*/
package org.sonar.server.platform.monitoring;
-import com.google.common.base.Optional;
import java.io.File;
import java.util.Map;
+import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.platform.Server;
import org.sonar.api.security.SecurityRealm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Rule
public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
Server server = mock(Server.class);
- ServerIdLoader serverIdLoader = mock(ServerIdLoader.class, RETURNS_DEEP_STUBS);
+ ServerIdLoader serverIdLoader = mock(ServerIdLoader.class);
ServerLogging serverLogging = mock(ServerLogging.class);
SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class);
- SonarQubeMonitor underTest = new SonarQubeMonitor(settings, securityRealmFactory, identityProviderRepository, server,
+ SonarQubeMonitor underTest = new SonarQubeMonitor(settings.asConfig(), securityRealmFactory, identityProviderRepository, server,
serverLogging, serverIdLoader);
@Before
public void setUp() throws Exception {
when(serverLogging.getRootLoggerLevel()).thenReturn(LoggerLevel.DEBUG);
+ when(serverIdLoader.getRaw()).thenReturn(Optional.empty());
+ when(serverIdLoader.get()).thenReturn(Optional.empty());
}
@Test
when(serverIdLoader.getRaw()).thenReturn(Optional.of("ABC"));
assertThat(underTest.getServerId()).isEqualTo("ABC");
- when(serverIdLoader.getRaw()).thenReturn(Optional.<String>absent());
+ when(serverIdLoader.getRaw()).thenReturn(Optional.<String>empty());
assertThat(underTest.getServerId()).isNull();
}
@Test
public void attributes_do_not_contain_information_about_server_id_if_absent() {
- when(serverIdLoader.get()).thenReturn(Optional.<ServerId>absent());
+ when(serverIdLoader.get()).thenReturn(Optional.<ServerId>empty());
Map<String, Object> attributes = underTest.attributes();
assertThat(attributes).doesNotContainKeys(SERVER_ID_PROPERTY, SERVER_ID_VALIDATED_PROPERTY);
import org.junit.rules.ExpectedException;
import org.mockito.InOrder;
import org.mockito.Mockito;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
@Rule
public LogTester logTester = new LogTester();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private Platform platform = mock(Platform.class);
private ProcessCommandWrapper processCommandWrapper = mock(ProcessCommandWrapper.class);
private RestartFlagHolder restartFlagHolder = mock(RestartFlagHolder.class);
- private RestartAction sut = new RestartAction(userSessionRule, settings, platform, processCommandWrapper, restartFlagHolder);
+ private RestartAction sut = new RestartAction(userSessionRule, settings.asConfig(), platform, processCommandWrapper, restartFlagHolder);
private InOrder inOrder = Mockito.inOrder(platform, restartFlagHolder, processCommandWrapper);
private WsActionTester actionTester = new WsActionTester(sut);
package org.sonar.server.platform.ws;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.WebService;
+import org.sonar.ce.http.CeHttpClient;
import org.sonar.server.app.ProcessCommandWrapper;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.platform.Platform;
-import org.sonar.ce.http.CeHttpClient;
import org.sonar.server.tester.AnonymousMockUserSession;
import org.sonar.server.user.UserSession;
@Test
public void define() {
- RestartAction action1 = new RestartAction(mock(UserSession.class), mock(Settings.class), mock(Platform.class), mock(ProcessCommandWrapper.class), mock(RestartFlagHolder.class));
+ RestartAction action1 = new RestartAction(mock(UserSession.class), mock(Configuration.class), mock(Platform.class), mock(ProcessCommandWrapper.class),
+ mock(RestartFlagHolder.class));
InfoAction action2 = new InfoAction(new AnonymousMockUserSession(), ceHttpClient);
SystemWs ws = new SystemWs(action1, action2);
WebService.Context context = new WebService.Context();
import java.nio.charset.StandardCharsets;
import org.junit.Before;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.SonarException;
import org.sonar.api.utils.UriReader;
private static final String BASE_URL = "https://update.sonarsource.org";
private UriReader reader = mock(UriReader.class);
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private UpdateCenterClient underTest;
@Before
reader = mock(UriReader.class);
settings.setProperty(UpdateCenterClient.URL_PROPERTY, BASE_URL);
settings.setProperty(WebConstants.SONAR_UPDATECENTER_ACTIVATE, true);
- underTest = new UpdateCenterClient(reader, settings);
+ underTest = new UpdateCenterClient(reader, settings.asConfig());
}
@Test
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings()),
- new ComponentIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()),
+ new ComponentIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(system2);
private static final OrganizationDto ORG = OrganizationTesting.newOrganizationDto();
@Rule
- public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new ProjectMeasuresIndexDefinition(new MapSettings().asConfig()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings()));
+ public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private RuleIndex ruleIndex = new RuleIndex(es.client());
RuleActivation activation = RuleActivation.create(rule.getKey(), BLOCKER, null);
List<ActiveRuleChange> changes = activate(profile, activation);
-
assertThatRuleIsActivated(profile, rule, changes, BLOCKER, null, emptyMap());
assertThatProfileIsUpdatedByUser(profile);
}
expectFailure("Value 'foo' must be an integer.", () -> activate(profile, activation));
}
-
@Test
public void ignore_parameters_when_activating_custom_rule() {
RuleDefinitionDto templateRule = db.rules().insert(r -> r.setIsTemplate(true));
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings()));
+ public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig()));
private ActiveRuleIndexer underTest = new ActiveRuleIndexer(db.getDbClient(), es.client(), new ActiveRuleIteratorFactory(db.getDbClient()));
private RuleDefinitionDto rule1;
@Rule
public DbTester dbTester = new DbTester(System2.INSTANCE, null);
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
@Rule
public DbTester db = DbTester.create();
@Rule
- public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
@Rule
- public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
/*
* sonar way (2) <- companyWide (2) <- buWide (2, 1 overriding) <- (forProject1 (2), forProject2 (2))
*/
- QProfileDto sonarway = db.qualityProfiles().insert(organization, p ->
- p.setKee("xoo-sonar-way").setLanguage("xoo").setName("Sonar way").setIsBuiltIn(true));
+ QProfileDto sonarway = db.qualityProfiles().insert(organization, p -> p.setKee("xoo-sonar-way").setLanguage("xoo").setName("Sonar way").setIsBuiltIn(true));
ActiveRuleDto activeRule1 = createActiveRule(rule1, sonarway);
ActiveRuleDto activeRule2 = createActiveRule(rule2, sonarway);
@org.junit.Rule
public DbTester dbTester = DbTester.create(system);
@org.junit.Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
@org.junit.Rule
public LogTester logTester = new LogTester();
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
private RuleIndex ruleIndex = new RuleIndex(es.client());
private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
private RuleIndex ruleIndex = new RuleIndex(es.client());
private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.process.ProcessProperties;
import org.sonar.server.es.EsTester;
public class RuleIndexDefinitionTest {
- private Settings settings = new MapSettings();
- private RuleIndexDefinition underTest = new RuleIndexDefinition(settings);
+ private MapSettings settings = new MapSettings();
+ private RuleIndexDefinition underTest = new RuleIndexDefinition(settings.asConfig());
@Rule
public EsTester tester = new EsTester(underTest);
private System2 system2 = new AlwaysIncreasingSystem2();
@Rule
- public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings()));
+ public EsTester es = new EsTester(RuleIndexDefinition.createForTest(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public class RuleIndexerTest {
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester dbTester = DbTester.create();
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
@org.junit.Rule
public DbTester db = DbTester.create(system2);
@org.junit.Rule
- public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
private RuleIndex ruleIndex = new RuleIndex(es.client());
public DbTester dbTester = DbTester.create();
@org.junit.Rule
public EsTester esTester = new EsTester(
- new RuleIndexDefinition(new MapSettings()));
+ new RuleIndexDefinition(new MapSettings().asConfig()));
@org.junit.Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public DbTester dbTester = DbTester.create();
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
private DbClient dbClient = dbTester.getDbClient();
private EsClient esClient = esTester.client();
public DbTester db = DbTester.create();
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
import org.junit.Test;
import org.mockito.Mockito;
+import org.sonar.api.config.Configuration;
import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.ce.settings.ProjectSettingsFactory;
+import org.sonar.ce.settings.ProjectConfigurationFactory;
import org.sonar.db.DbClient;
import org.sonar.db.property.PropertyDto;
static final String PROJECT_KEY = "PROJECT_KEY";
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS);
- ProjectSettingsFactory underTest = new ProjectSettingsFactory(settings, dbClient);
+ ProjectConfigurationFactory underTest = new ProjectConfigurationFactory(settings, dbClient);
@Test
public void return_global_settings() {
settings.setProperty("key", "value");
- Settings projectSettings = underTest.newProjectSettings(PROJECT_KEY);
+ Configuration config = underTest.newProjectConfiguration(PROJECT_KEY);
- assertThat(projectSettings.getProperties()).hasSize(1);
- assertThat(projectSettings.getString("key")).isEqualTo("value");
+ assertThat(config.get("key")).hasValue("value");
}
@Test
when(dbClient.propertiesDao().selectProjectProperties(PROJECT_KEY)).thenReturn(newArrayList(
new PropertyDto().setKey("1").setValue("val1"),
new PropertyDto().setKey("2").setValue("val2"),
- new PropertyDto().setKey("3").setValue("val3"))
- );
+ new PropertyDto().setKey("3").setValue("val3")));
- Settings projectSettings = underTest.newProjectSettings(PROJECT_KEY);
+ Configuration config = underTest.newProjectConfiguration(PROJECT_KEY);
- assertThat(projectSettings.getString("1")).isEqualTo("val1");
- assertThat(projectSettings.getString("2")).isEqualTo("val2");
- assertThat(projectSettings.getString("3")).isEqualTo("val3");
+ assertThat(config.get("1")).hasValue("val1");
+ assertThat(config.get("2")).hasValue("val2");
+ assertThat(config.get("3")).hasValue("val3");
}
@Test
public void project_settings_override_global_settings() {
settings.setProperty("key", "value");
when(dbClient.propertiesDao().selectProjectProperties(PROJECT_KEY)).thenReturn(newArrayList(
- new PropertyDto().setKey("key").setValue("value2"))
- );
+ new PropertyDto().setKey("key").setValue("value2")));
- Settings projectSettings = underTest.newProjectSettings(PROJECT_KEY);
- assertThat(projectSettings.getString("key")).isEqualTo("value2");
+ Configuration projectConfig = underTest.newProjectConfiguration(PROJECT_KEY);
+ assertThat(projectConfig.get("key")).hasValue("value2");
}
}
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private Encryption encryption = settings.getEncryption();
private CheckSecretKeyAction underTest = new CheckSecretKeyAction(settings, userSession);
private WsActionTester ws = new WsActionTester(underTest);
@Rule
public TemporaryFolder folder = new TemporaryFolder();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private Encryption encryption = settings.getEncryption();
private EncryptAction underTest = new EncryptAction(userSession, settings);
private WsActionTester ws = new WsActionTester(underTest);
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private Encryption encryption = settings.getEncryption();
private GenerateSecretKeyAction underTest = new GenerateSecretKeyAction(settings, userSession);
private WsActionTester ws = new WsActionTester(underTest);
public class TestIndexTest {
@Rule
- public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig()));
TestIndex underTest = new TestIndex(es.client());
private System2 system2 = System2.INSTANCE;
@Rule
- public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.platform.Server;
import org.sonar.api.resources.ResourceType;
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private Server server = mock(Server.class);
private DbClient dbClient = mock(DbClient.class, RETURNS_DEEP_STUBS);
}
}});
pageRepository.start();
- ws = new WsActionTester(new GlobalAction(pageRepository, settings, new ResourceTypes(resourceTypeTrees), server,
+ ws = new WsActionTester(new GlobalAction(pageRepository, settings.asConfig(), new ResourceTypes(resourceTypeTrees), server,
dbClient, organizationFlags, defaultOrganizationProvider, userSession));
}
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.PageDefinition;
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private WsActionTester ws;
context.addPage(page);
}
}});
- ws = new WsActionTester(new SettingsAction(pageRepository, settings, userSessionRule));
+ ws = new WsActionTester(new SettingsAction(pageRepository, settings.asConfig(), userSessionRule));
pageRepository.start();
}
import org.junit.Test;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.security.LoginPasswordAuthenticator;
import org.sonar.api.security.SecurityRealm;
public class SecurityRealmFactoryTest {
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
/**
* Typical usage.
SecurityRealm realm = spy(new FakeRealm());
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_REALM, realm.getName());
- SecurityRealmFactory factory = new SecurityRealmFactory(settings, new SecurityRealm[] {realm});
+ SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm});
factory.start();
assertThat(factory.getRealm()).isSameAs(realm);
assertThat(factory.hasExternalAuthentication()).isTrue();
@Test
public void do_not_fail_if_no_realms() {
- SecurityRealmFactory factory = new SecurityRealmFactory(settings);
+ SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig());
factory.start();
assertThat(factory.getRealm()).isNull();
assertThat(factory.hasExternalAuthentication()).isFalse();
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_REALM, "Fake");
try {
- new SecurityRealmFactory(settings);
+ new SecurityRealmFactory(settings.asConfig());
fail();
} catch (SonarException e) {
assertThat(e.getMessage()).contains("Realm 'Fake' not found.");
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, FakeAuthenticator.class.getName());
LoginPasswordAuthenticator authenticator = new FakeAuthenticator();
- SecurityRealmFactory factory = new SecurityRealmFactory(settings, new LoginPasswordAuthenticator[] {authenticator});
+ SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new LoginPasswordAuthenticator[] {authenticator});
SecurityRealm realm = factory.getRealm();
assertThat(realm).isInstanceOf(CompatibilityRealm.class);
}
LoginPasswordAuthenticator authenticator = new FakeAuthenticator();
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, FakeAuthenticator.class.getName());
- SecurityRealmFactory factory = new SecurityRealmFactory(settings, new SecurityRealm[] {realm},
+ SecurityRealmFactory factory = new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm},
new LoginPasswordAuthenticator[] {authenticator});
assertThat(factory.getRealm()).isSameAs(realm);
}
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_CLASS, "Fake");
try {
- new SecurityRealmFactory(settings);
+ new SecurityRealmFactory(settings.asConfig());
fail();
} catch (SonarException e) {
assertThat(e.getMessage()).contains("Authenticator 'Fake' not found.");
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_REALM, realm.getName());
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_IGNORE_STARTUP_FAILURE, true);
- new SecurityRealmFactory(settings, new SecurityRealm[] {realm}).start();
+ new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}).start();
verify(realm).init();
}
settings.setProperty(CoreProperties.CORE_AUTHENTICATOR_REALM, realm.getName());
try {
- new SecurityRealmFactory(settings, new SecurityRealm[] {realm}).start();
+ new SecurityRealmFactory(settings.asConfig(), new SecurityRealm[] {realm}).start();
fail();
} catch (SonarException e) {
assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
public ExpectedException expectedException = ExpectedException.none();
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public DbTester db = DbTester.create(system2);
private TestOrganizationFlags organizationFlags = TestOrganizationFlags.standalone();
private MapSettings settings = new MapSettings();
private UserUpdater underTest = new UserUpdater(newUserNotifier, dbClient, userIndexer, system2, organizationFlags, defaultOrganizationProvider, organizationCreation,
- new DefaultGroupFinder(dbClient), settings);
+ new DefaultGroupFinder(dbClient), settings.asConfig());
@Test
public void create_user() {
@Test
public void define() {
- UserIndexDefinition def = new UserIndexDefinition(new MapSettings());
+ UserIndexDefinition def = new UserIndexDefinition(new MapSettings().asConfig());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
private static final long DATE_2 = 1_500_000_000_001L;
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
private UserIndex underTest;
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
private UserIndexer underTest = new UserIndexer(db.getDbClient(), es.client());
@Rule
public DbTester db = DbTester.create();
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn();
TestDefaultOrganizationProvider.from(db),
mock(OrganizationCreation.class),
new DefaultGroupFinder(db.getDbClient()),
- new MapSettings());
+ new MapSettings().asConfig());
private WsTester tester = new WsTester(new UsersWs(new ChangePasswordAction(db.getDbClient(), userUpdater, userSessionRule)));
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
public class CreateActionTest {
private static final String DEFAULT_GROUP_NAME = "sonar-users";
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(settings));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(settings.asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
private WsActionTester tester = new WsActionTester(new CreateAction(
db.getDbClient(),
new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), userIndexer, system2, organizationFlags, defaultOrganizationProvider,
- organizationCreation, new DefaultGroupFinder(db.getDbClient()), settings),
+ organizationCreation, new DefaultGroupFinder(db.getDbClient()), settings.asConfig()),
userSessionRule));
@Before
public DbTester db = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private System2 system2 = System2.INSTANCE;
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
private static final OrganizationCreation ORGANIZATION_CREATION_NOT_USED_FOR_UPDATE = null;
- private final Settings settings = new MapSettings();
+ private final MapSettings settings = new MapSettings();
private System2 system2 = new System2();
@Rule
public DbTester dbTester = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(settings));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(settings.asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn().setSystemAdministrator();
userIndexer = new UserIndexer(dbClient, esTester.client());
tester = new WsTester(new UsersWs(new UpdateAction(
new UserUpdater(mock(NewUserNotifier.class), dbClient, userIndexer, system2, organizationFlags, defaultOrganizationProvider, ORGANIZATION_CREATION_NOT_USED_FOR_UPDATE,
- new DefaultGroupFinder(dbTester.getDbClient()), settings),
+ new DefaultGroupFinder(dbTester.getDbClient()), settings.asConfig()),
userSessionRule,
new UserJsonWriter(userSessionRule), dbClient)));
}
import org.junit.Test;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.Version;
public class OkHttpClientProviderTest {
- private Settings settings = new MapSettings();
+ private MapSettings settings = new MapSettings();
private SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("6.2"), SonarQubeSide.SERVER);
private final OkHttpClientProvider underTest = new OkHttpClientProvider();
@Test
public void get_returns_a_OkHttpClient_with_default_configuration() throws Exception {
- OkHttpClient client = underTest.provide(settings, runtime);
+ OkHttpClient client = underTest.provide(settings.asConfig(), runtime);
assertThat(client.connectTimeoutMillis()).isEqualTo(10_000);
assertThat(client.readTimeoutMillis()).isEqualTo(10_000);
settings.setProperty("http.proxyUser", "the-login");
settings.setProperty("http.proxyPassword", "the-password");
- OkHttpClient client = underTest.provide(settings, runtime);
+ OkHttpClient client = underTest.provide(settings.asConfig(), runtime);
Response response = new Response.Builder().protocol(Protocol.HTTP_1_1).request(new Request.Builder().url("http://foo").build()).code(407).build();
Request request = client.proxyAuthenticator().authenticate(null, response);
@Test
public void get_returns_a_singleton() {
- OkHttpClient client1 = underTest.provide(settings, runtime);
- OkHttpClient client2 = underTest.provide(settings, runtime);
+ OkHttpClient client1 = underTest.provide(settings.asConfig(), runtime);
+ OkHttpClient client2 = underTest.provide(settings.asConfig(), runtime);
assertThat(client2).isNotNull().isSameAs(client1);
}
@Test
public void define() {
- ViewIndexDefinition def = new ViewIndexDefinition(new MapSettings());
+ ViewIndexDefinition def = new ViewIndexDefinition(new MapSettings().asConfig());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
public class ViewIndexTest {
@Rule
- public EsTester esTester = new EsTester(new ViewIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new ViewIndexDefinition(new MapSettings().asConfig()));
ViewIndex index = new ViewIndex(esTester.client());
public DbTester dbTester = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()), new ViewIndexDefinition(new MapSettings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings().asConfig()), new ViewIndexDefinition(new MapSettings().asConfig()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Test
public void clear_views_lookup_cache_on_index_view_uuid() {
- IssueIndex issueIndex = new IssueIndex(esTester.client(), System2.INSTANCE, userSessionRule, new AuthorizationTypeSupport(userSessionRule)
- );
+ IssueIndex issueIndex = new IssueIndex(esTester.client(), System2.INSTANCE, userSessionRule, new AuthorizationTypeSupport(userSessionRule));
IssueIndexer issueIndexer = new IssueIndexer(esTester.client(), new IssueIteratorFactory(dbClient));
String viewUuid = "ABCD";
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program 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.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.core.config;
+
+import org.picocontainer.injectors.ProviderAdapter;
+import org.sonar.api.config.Configuration;
+import org.sonar.api.config.Settings;
+import org.sonar.api.config.internal.ConfigurationBridge;
+
+public class ConfigurationProvider extends ProviderAdapter {
+
+ private Configuration configuration;
+
+ public Configuration provide(Settings settings) {
+ if (configuration == null) {
+ configuration = new ConfigurationBridge(settings);
+ }
+ return configuration;
+ }
+
+}
import java.util.Date;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.Configuration;
import org.sonar.api.i18n.I18n;
import static com.google.common.base.Preconditions.checkArgument;
public class Periods {
- private final Settings settings;
+ private final Configuration config;
private final I18n i18n;
- public Periods(Settings settings, I18n i18n) {
- this.settings = settings;
+ public Periods(Configuration config, I18n i18n) {
+ this.config = config;
this.i18n = i18n;
}
@CheckForNull
public String label(int periodIndex) {
- String periodProperty = settings.getString(LEAK_PERIOD + periodIndex);
+ String periodProperty = config.get(LEAK_PERIOD + periodIndex).orElse(null);
PeriodParameters periodParameters = new PeriodParameters(periodProperty);
return label(periodParameters.getMode(), periodParameters.getParam(), periodParameters.getDate());
}
@CheckForNull
public String abbreviation(int periodIndex) {
- String periodProperty = settings.getString(LEAK_PERIOD + periodIndex);
+ String periodProperty = config.get(LEAK_PERIOD + periodIndex).orElse(null);
PeriodParameters periodParameters = new PeriodParameters(periodProperty);
return abbreviation(periodParameters.getMode(), periodParameters.getParam(), periodParameters.getDate());
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.i18n.I18n;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.isNull;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.api.utils.DateUtils.parseDate;
static int PERIOD_INDEX = 1;
@Rule
public ExpectedException thrown = ExpectedException.none();
- Settings settings = new MapSettings();
+ MapSettings settings = new MapSettings();
I18n i18n = mock(I18n.class);
- Periods periods = new Periods(settings, i18n);
+ Periods periods = new Periods(settings.asConfig(), i18n);
@Test
public void return_over_x_days_label_when_no_date() {
public static final String PREFIX = "email.prefix";
public static final String PREFIX_DEFAULT = "[SONARQUBE]";
- private final Settings settings;
+ private final Configuration config;
- public EmailSettings(Settings settings) {
- this.settings = settings;
+ public EmailSettings(Configuration config) {
+ this.config = config;
}
public String getSmtpHost() {
}
private String get(String key, String defaultValue) {
- String value = settings.getString(key);
- return value != null ? value : defaultValue;
+ return config.get(key).orElse(defaultValue);
}
/**
import static org.sonar.api.PropertyType.SINGLE_SELECT_LIST;
/**
- * Declare a plugin property. Values are available at runtime through the components {@link Settings} or {@link org.sonar.api.Configuration.SettingsReader}.
+ * Declare a plugin property. Values are available at runtime through the component {@link Configuration}.
* <br>
* It's the programmatic alternative to the annotation {@link org.sonar.api.Property}. It is more
* testable and adds new features like sub-categories and ordering.
return this;
}
+ @Override
+ public MapSettings setProperty(String key, String value) {
+ return (MapSettings) super.setProperty(key, value);
+ }
+
+ @Override
+ public MapSettings setProperty(String key, Integer value) {
+ return (MapSettings) super.setProperty(key, value);
+ }
+
+ @Override
+ public MapSettings setProperty(String key, Boolean value) {
+ return (MapSettings) super.setProperty(key, value);
+ }
+
+ @Override
+ public MapSettings setProperty(String key, Long value) {
+ return (MapSettings) super.setProperty(key, value);
+ }
+
/**
* @return a {@link Configuration} proxy on top of this existing {@link Settings} implementation. Changes are reflected in the {@link Configuration} object.
* @since 6.5
public class EmailSettingsTest {
- private EmailSettings underTest = new EmailSettings(new MapSettings());
+ private EmailSettings underTest = new EmailSettings(new MapSettings().asConfig());
@Test
public void should_return_default_values() {