* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
+
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
import org.sonar.api.security.UserDetails;
@Before
public void setUp() {
- settings = new Settings();
+ settings = new MapSettings();
authenticator = new FakeAuthenticator(settings);
authenticator.init();
}
import java.io.File;
import java.io.IOException;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
baseDir = temp.newFolder();
fileSystem = new DefaultFileSystem(baseDir.toPath());
when(context.fileSystem()).thenReturn(fileSystem);
- settings = new Settings();
+ settings = new MapSettings();
when(context.settings()).thenReturn(settings);
}
import org.sonar.ce.db.ReadOnlyPropertiesDao;
import org.sonar.ce.es.EsIndexerEnabler;
import org.sonar.ce.platform.ComputeEngineExtensionInstaller;
-import org.sonar.ce.settings.ComputeEngineSettings;
+import org.sonar.ce.settings.ProjectSettingsFactory;
import org.sonar.ce.user.CeUserSession;
import org.sonar.core.component.DefaultResourceTypes;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.platform.DatabaseServerCompatibility;
import org.sonar.server.platform.DefaultServerUpgradeStatus;
-import org.sonar.server.platform.PersistentSettings;
import org.sonar.server.platform.ServerFileSystemImpl;
import org.sonar.server.platform.ServerImpl;
import org.sonar.server.platform.ServerLifecycleNotifier;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.search.EsSearchModule;
-import org.sonar.server.setting.ProjectSettingsFactory;
+import org.sonar.server.setting.DatabaseSettingLoader;
+import org.sonar.server.setting.DatabaseSettingsEnabler;
+import org.sonar.server.setting.ThreadLocalSettings;
import org.sonar.server.startup.LogServerId;
import org.sonar.server.test.index.TestIndexer;
import org.sonar.server.user.DefaultUserFinder;
private static Object[] level1Components() {
Version apiVersion = ApiVersion.load(System2.INSTANCE);
return new Object[] {
- ComputeEngineSettings.class,
+ ThreadLocalSettings.class,
new SonarQubeVersion(apiVersion),
SonarRuntimeImpl.forSonarQube(ApiVersion.load(System2.INSTANCE), SonarQubeSide.COMPUTE_ENGINE),
UuidFactoryImpl.INSTANCE,
- UrlSettings.class,
ClusterImpl.class,
DefaultDatabase.class,
DatabaseChecker.class,
private static Object[] level2Components() {
return new Object[] {
+ DatabaseSettingLoader.class,
+ DatabaseSettingsEnabler.class,
+ UrlSettings.class,
+
// add ReadOnlyPropertiesDao at level2 again so that it shadows PropertiesDao
ReadOnlyPropertiesDao.class,
DefaultServerUpgradeStatus.class,
private static Object[] level3Components() {
return new Object[] {
new StartupMetadataProvider(),
- PersistentSettings.class,
UriReader.class,
ServerImpl.class
};
);
assertThat(picoContainer.getParent().getComponentAdapters()).hasSize(
CONTAINER_ITSELF
- + 4 // level 3
+ + 3 // level 3
);
assertThat(picoContainer.getParent().getParent().getComponentAdapters()).hasSize(
CONTAINER_ITSELF
- + 11 // level 2
+ + 14 // level 2
);
assertThat(picoContainer.getParent().getParent().getParent().getComponentAdapters()).hasSize(
COMPONENTS_IN_LEVEL_1_AT_CONSTRUCTION
- + 25 // level 1
+ + 24 // level 1
+ 49 // content of DaoModule
+ 2 // content of EsSearchModule
+ 54 // content of CorePropertyDefinitions
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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 com.google.common.base.MoreObjects;
-import com.google.common.collect.Maps;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.config.Encryption;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.Settings;
-import org.sonar.core.platform.ComponentContainer;
-import org.sonar.db.DbClient;
-import org.sonar.db.property.PropertyDto;
-import org.sonar.server.platform.ServerSettings;
-
-import static com.google.common.base.Preconditions.checkState;
-
-/**
- * This class implements ServerSettings and extends Settings so that it can be injected in any component depending upon
- * either ServerSettings or Settings.
- *
- * <p>
- * In order to honor both Settings and ThreadLocalSettings contracts, none of the code inherited from the Settings super
- * class is actually used. Every public method of Settings is override and their implementation is delegated to
- * an inner object which can either be the default one or one specific to the current Thread. Selected of the inner
- * object will depend on whether the current Thread made use of method {@link #load()} or not. This approach also greatly
- * simplifies delegation code (see {@link #currentDelegate()}).
- * </p>
- */
-public class ComputeEngineSettings extends Settings implements ThreadLocalSettings, ServerSettings {
- private final ServerSettings defaultDelegate;
- private final ThreadLocal<ServerSettings> threadLocalDelegate = new ThreadLocal<>();
-
- private final Properties rootProperties;
- private final ComponentContainer componentContainer;
- // we can't get injected with DBClient because it creates a circular dependency
- private volatile DbClient dbClient;
-
- public ComputeEngineSettings(PropertyDefinitions definitions, Properties rootProperties, ComponentContainer componentContainer) {
- super(definitions);
- this.rootProperties = rootProperties;
- this.componentContainer = componentContainer;
-
- this.defaultDelegate = new ServerSettingsImpl(definitions, rootProperties);
- }
-
- @Override
- public void load() {
- checkState(
- this.threadLocalDelegate.get() == null,
- "loadLocal called twice for Thread '%s' or state wasn't cleared last time it was used",
- Thread.currentThread().getName());
- this.threadLocalDelegate.set(loadServerSettings());
- }
-
- @Override
- public void unload() {
- this.threadLocalDelegate.remove();
- }
-
- private ServerSettings loadServerSettings() {
- ServerSettings res = new ServerSettingsImpl(this.definitions, this.rootProperties);
- Map<String, String> databaseProperties = Maps.newHashMap();
- for (PropertyDto property : getDbClient().propertiesDao().selectGlobalProperties()) {
- databaseProperties.put(property.getKey(), property.getValue());
- }
- res.activateDatabaseSettings(databaseProperties);
- return res;
- }
-
- private DbClient getDbClient() {
- if (dbClient == null) {
- this.dbClient = componentContainer.getComponentByType(DbClient.class);
- }
- return dbClient;
- }
-
- private ServerSettings currentDelegate() {
- return MoreObjects.firstNonNull(threadLocalDelegate.get(), defaultDelegate);
- }
-
- private Settings currentSettings() {
- return currentDelegate().getSettings();
- }
-
- @Override
- public ServerSettings activateDatabaseSettings(Map<String, String> databaseProperties) {
- checkState(threadLocalDelegate.get() == null, "activateDatabaseSettings must not be called from a Worker");
-
- return defaultDelegate.activateDatabaseSettings(databaseProperties);
- }
-
- private static final class ServerSettingsImpl extends Settings implements ServerSettings {
-
- private final Properties rootProperties;
-
- public ServerSettingsImpl(PropertyDefinitions definitions, Properties rootProperties) {
- super(definitions);
- this.rootProperties = rootProperties;
- super.addProperties(rootProperties);
- // Secret key is loaded from conf/sonar.properties
- super.getEncryption().setPathToSecretKey(super.getString(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
- }
-
- @Override
- public ServerSettings activateDatabaseSettings(Map<String, String> databaseProperties) {
- super.clear();
-
- // order is important : the last override the first
- super.addProperties(databaseProperties);
- super.addProperties(rootProperties);
-
- return this;
- }
-
- @Override
- public Settings getSettings() {
- return this;
- }
- }
-
- @Override
- public Settings getSettings() {
- return this;
- }
-
- @Override
- public Encryption getEncryption() {
- return currentSettings().getEncryption();
- }
-
- @Override
- @CheckForNull
- public String getDefaultValue(String key) {
- return currentSettings().getDefaultValue(key);
- }
-
- @Override
- public boolean hasKey(String key) {
- return currentSettings().hasKey(key);
- }
-
- @Override
- public boolean hasDefaultValue(String key) {
- return currentSettings().hasDefaultValue(key);
- }
-
- @Override
- @CheckForNull
- public String getString(String key) {
- return currentDelegate().getString(key);
- }
-
- @Override
- public boolean getBoolean(String key) {
- return currentSettings().getBoolean(key);
- }
-
- @Override
- public int getInt(String key) {
- return currentSettings().getInt(key);
- }
-
- @Override
- public long getLong(String key) {
- return currentSettings().getLong(key);
- }
-
- @Override
- @CheckForNull
- public Date getDate(String key) {
- return currentSettings().getDate(key);
- }
-
- @Override
- @CheckForNull
- public Date getDateTime(String key) {
- return currentSettings().getDateTime(key);
- }
-
- @Override
- @CheckForNull
- public Float getFloat(String key) {
- return currentSettings().getFloat(key);
- }
-
- @Override
- @CheckForNull
- public Double getDouble(String key) {
- return currentSettings().getDouble(key);
- }
-
- @Override
- public String[] getStringArray(String key) {
- return currentSettings().getStringArray(key);
- }
-
- @Override
- public String[] getStringLines(String key) {
- return currentSettings().getStringLines(key);
- }
-
- @Override
- public String[] getStringArrayBySeparator(String key, String separator) {
- return currentSettings().getStringArrayBySeparator(key, separator);
- }
-
- @Override
- public List<String> getKeysStartingWith(String prefix) {
- return currentSettings().getKeysStartingWith(prefix);
- }
-
- @Override
- public Settings appendProperty(String key, String value) {
- return currentSettings().appendProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable String[] values) {
- return currentSettings().setProperty(key, values);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable String value) {
- return currentSettings().setProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Boolean value) {
- return currentSettings().setProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Integer value) {
- return currentSettings().setProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Long value) {
- return currentSettings().setProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Double value) {
- return currentSettings().setProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Float value) {
- return currentSettings().setProperty(key, value);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Date date) {
- return currentSettings().setProperty(key, date);
- }
-
- @Override
- public Settings addProperties(Map<String, String> props) {
- return currentSettings().addProperties(props);
- }
-
- @Override
- public Settings addProperties(Properties props) {
- return currentSettings().addProperties(props);
- }
-
- @Override
- public Settings setProperties(Map<String, String> props) {
- return currentSettings().setProperties(props);
- }
-
- @Override
- public Settings setProperty(String key, @Nullable Date date, boolean includeTime) {
- return currentSettings().setProperty(key, date, includeTime);
- }
-
- @Override
- public Settings removeProperty(String key) {
- return currentSettings().removeProperty(key);
- }
-
- @Override
- public Settings clear() {
- return currentSettings().clear();
- }
-
- @Override
- public Map<String, String> getProperties() {
- return currentSettings().getProperties();
- }
-
- @Override
- public PropertyDefinitions getDefinitions() {
- return currentSettings().getDefinitions();
- }
-
-}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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 java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import org.sonar.api.ce.ComputeEngineSide;
+import org.sonar.api.config.Settings;
+
+@ComputeEngineSide
+public class ProjectSettings extends Settings {
+
+ private final Map<String, String> projectProps = new HashMap<>();
+ private final Settings globalSettings;
+
+ public ProjectSettings(Settings globalSettings) {
+ super(globalSettings.getDefinitions(), globalSettings.getEncryption());
+ this.globalSettings = globalSettings;
+ }
+
+ @Override
+ protected Optional<String> get(String key) {
+ String value = projectProps.get(key);
+ if (value != null) {
+ return Optional.of(value);
+ }
+ return globalSettings.getRawString(key);
+ }
+
+ @Override
+ protected void set(String key, String value) {
+ projectProps.put(key, value);
+ }
+
+ @Override
+ protected void remove(String key) {
+ projectProps.remove(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ // order is important. Project properties override global properties.
+ Map<String, String> result = new HashMap<>();
+ result.putAll(globalSettings.getProperties());
+ result.putAll(projectProps);
+ return result;
+ }
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.ce.settings;
import org.picocontainer.Startable;
+import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.server.computation.task.container.EagerStart;
import org.sonar.server.computation.task.container.TaskContainerImpl;
+import org.sonar.server.setting.ThreadLocalSettings;
/**
* Add this class as the first components in the {@link TaskContainerImpl}
* to trigger loading of Thread local specific {@link org.sonar.api.config.Settings} in {@link ThreadLocalSettings}.
*/
@EagerStart
+@ComputeEngineSide
public class SettingsLoader implements Startable {
private final ThreadLocalSettings threadLocalSettings;
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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;
-
-public interface ThreadLocalSettings {
- /**
- * Loads up-to-date Settings specific to the current thread.
- *
- * @throws IllegalStateException if the current thread already has specific Settings
- */
- void load();
-
- /**
- * Clears the Settings specific to the current thread (if any).
- */
- void unload();
-}
package org.sonar.server.authentication;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static io.jsonwebtoken.impl.crypto.MacProvider.generateKey;
-import static java.util.Objects.requireNonNull;
-
+import com.google.common.annotations.VisibleForTesting;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import org.sonar.core.util.UuidFactory;
import org.sonar.server.exceptions.UnauthorizedException;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static io.jsonwebtoken.impl.crypto.MacProvider.generateKey;
+import static java.util.Objects.requireNonNull;
+
/**
* This class can be used to encode or decode a JWT token
*/
this.uuidFactory = uuidFactory;
}
+ @VisibleForTesting
+ SecretKey getSecretKey() {
+ return secretKey;
+ }
+
@Override
public void start() {
String encodedKey = settings.getString(SECRET_KEY_PROPERTY);
if (encodedKey == null) {
- SecretKey newSecretKey = generateSecretKey();
- settings.setProperty(SECRET_KEY_PROPERTY, Base64.getEncoder().encodeToString(newSecretKey.getEncoded()));
- this.secretKey = newSecretKey;
+ this.secretKey = generateSecretKey();
} else {
this.secretKey = decodeSecretKeyProperty(encodedKey);
}
}
public void removeUserSession() {
- threadLocalSession.remove();
+ threadLocalSession.unload();
}
// Try first to authenticate from JWT token, then try from basic http header
import java.util.Collection;
import java.util.Map;
import org.sonar.api.config.Settings;
-import org.sonar.server.setting.ProjectSettingsFactory;
+import org.sonar.ce.settings.ProjectSettingsFactory;
import org.sonar.server.util.cache.CacheLoader;
import org.sonar.server.util.cache.MemoryCache;
import org.sonar.ce.queue.CeTask;
import org.sonar.ce.queue.CeTaskResult;
import org.sonar.ce.settings.SettingsLoader;
-import org.sonar.ce.settings.ThreadLocalSettings;
import org.sonar.ce.taskprocessor.CeTaskProcessor;
import org.sonar.core.platform.ComponentContainer;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.server.computation.task.projectanalysis.container.ContainerFactory;
import org.sonar.server.computation.task.step.ComputationStepExecutor;
import org.sonar.server.computation.taskprocessor.TaskResultHolder;
+import org.sonar.server.setting.ThreadLocalSettings;
public class ReportTaskProcessor implements CeTaskProcessor {
*/
package org.sonar.server.permission.ws.template;
-import static org.sonar.server.permission.DefaultPermissionTemplates.defaultRootQualifierTemplateProperty;
-import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
-import static org.sonar.server.permission.ws.PermissionRequestValidator.validateQualifier;
-import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
-import static org.sonar.server.permission.ws.WsTemplateRef.newTemplateRef;
-import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
-import static org.sonar.server.ws.WsParameterBuilder.createRootQualifierParameter;
-import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
-import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
-import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
-
import org.sonar.api.i18n.I18n;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.permission.SetDefaultTemplateWsRequest;
+import static org.sonar.server.permission.DefaultPermissionTemplates.defaultRootQualifierTemplateProperty;
+import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
+import static org.sonar.server.permission.ws.PermissionRequestValidator.validateQualifier;
+import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
+import static org.sonar.server.permission.ws.WsTemplateRef.newTemplateRef;
+import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
+import static org.sonar.server.ws.WsParameterBuilder.createRootQualifierParameter;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
+
public class SetDefaultTemplateAction implements PermissionsWsAction {
private final DbClient dbClient;
private final PermissionDependenciesFinder finder;
*/
package org.sonar.server.platform;
-import com.google.common.collect.Maps;
-import java.util.List;
-import java.util.Map;
+import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.picocontainer.Startable;
import org.sonar.api.config.Settings;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
-/**
- * @since 3.2
- */
-public class PersistentSettings implements Startable {
+public class PersistentSettings {
+
+ private final Settings delegate;
private final DbClient dbClient;
- private final PropertiesDao propertiesDao;
- private final ServerSettings serverSettings;
+ private final SettingsChangeNotifier changeNotifier;
- public PersistentSettings(DbClient dbClient, ServerSettings serverSettings) {
+ public PersistentSettings(Settings delegate, DbClient dbClient, SettingsChangeNotifier changeNotifier) {
+ this.delegate = delegate;
this.dbClient = dbClient;
- this.propertiesDao = dbClient.propertiesDao();
- this.serverSettings = serverSettings;
+ this.changeNotifier = changeNotifier;
}
- @Override
- public void start() {
- Map<String, String> databaseProperties = Maps.newHashMap();
- for (PropertyDto property : getGlobalProperties()) {
- databaseProperties.put(property.getKey(), property.getValue());
- }
- serverSettings.activateDatabaseSettings(databaseProperties);
+ @CheckForNull
+ public String getString(String key) {
+ return delegate.getString(key);
}
- @Override
- public void stop() {
- // nothing to do
+ /**
+ * Insert property into database if value is not {@code null}, else delete property from
+ * database. Session is not committed but {@link org.sonar.api.config.GlobalPropertyChangeHandler}
+ * are executed.
+ */
+ public PersistentSettings saveProperty(DbSession dbSession, String key, @Nullable String value) {
+ if (value == null) {
+ dbClient.propertiesDao().deleteGlobalProperty(key, dbSession);
+ } else {
+ dbClient.propertiesDao().insertProperty(dbSession, new PropertyDto().setKey(key).setValue(value));
+ }
+ // refresh the cache of settings
+ delegate.setProperty(key, value);
+
+ changeNotifier.onGlobalPropertyChange(key, value);
+ return this;
}
+ /**
+ * Same as {@link #saveProperty(DbSession, String, String)} but a new database session is
+ * opened and committed.
+ */
public PersistentSettings saveProperty(String key, @Nullable String value) {
- DbSession dbSession = dbClient.openSession(false);
- try {
+ try (DbSession dbSession = dbClient.openSession(false)) {
saveProperty(dbSession, key, value);
dbSession.commit();
- } finally {
- dbClient.closeSession(dbSession);
+ return this;
}
- return this;
- }
-
- public PersistentSettings saveProperty(DbSession dbSession, String key, @Nullable String value) {
- serverSettings.setProperty(key, value);
- propertiesDao.insertProperty(dbSession, new PropertyDto().setKey(key).setValue(value));
- return this;
- }
-
- public PersistentSettings deleteProperty(String key) {
- serverSettings.removeProperty(key);
- propertiesDao.deleteGlobalProperty(key);
- return this;
- }
-
- public PersistentSettings deleteProperties() {
- serverSettings.clear();
- propertiesDao.deleteGlobalProperties();
- return this;
- }
-
- public PersistentSettings saveProperties(Map<String, String> properties) {
- serverSettings.addProperties(properties);
- propertiesDao.insertGlobalProperties(properties);
- return this;
- }
-
- public String getString(String key) {
- return serverSettings.getString(key);
- }
-
- public Map<String, String> getProperties() {
- return serverSettings.getProperties();
}
public Settings getSettings() {
- return serverSettings.getSettings();
- }
-
- public List<PropertyDto> getGlobalProperties() {
- return propertiesDao.selectGlobalProperties();
+ return delegate;
}
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.platform;
-
-import java.util.Map;
-import javax.annotation.Nullable;
-import org.sonar.api.config.Settings;
-
-/**
- * Defines some of the methods of {@link Settings} plus some specific to load db properties on the server side
- * (see {@link PersistentSettings}).
- */
-public interface ServerSettings {
- ServerSettings activateDatabaseSettings(Map<String, String> databaseProperties);
-
- Settings getSettings();
-
- /**
- * @see Settings#getString(String)
- */
- String getString(String key);
-
- /**
- * @see Settings#getProperties()
- */
- Map<String, String> getProperties();
-
- /**
- * @see Settings#hasKey(String)
- */
- boolean hasKey(String foo);
-
- /**
- * @see Settings#setProperty(String, String)
- */
- Settings setProperty(String key, @Nullable String value);
-
- /**
- * @see Settings#removeProperty(String)
- */
- Settings removeProperty(String key);
-
- /**
- * @see Settings#clear()
- */
- Settings clear();
-
- /**
- * @see Settings#addProperties(Map)
- */
- Settings addProperties(Map<String, String> properties);
-}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.platform;
-
-import org.sonar.api.CoreProperties;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.api.config.Settings;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * Load settings in the following order (the last override the first) :
- * <ol>
- * <li>general settings persisted in database</li>
- * <li>file $SONAR_HOME/conf/sonar.properties</li>
- * <li>environment variables</li>
- * <li>system properties</li>
- * </ol>
- */
-public class ServerSettingsImpl extends Settings implements ServerSettings {
-
- private final Properties bootstrapProperties;
-
- public ServerSettingsImpl(PropertyDefinitions definitions, Properties bootstrapProperties) {
- super(definitions);
- this.bootstrapProperties = bootstrapProperties;
- load(Collections.emptyMap());
- // Secret key is loaded from conf/sonar.properties
- getEncryption().setPathToSecretKey(getString(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
- }
-
- @Override
- public ServerSettings activateDatabaseSettings(Map<String, String> databaseProperties) {
- return load(databaseProperties);
- }
-
- @Override
- public Settings getSettings() {
- return this;
- }
-
- private ServerSettings load(Map<String, String> databaseSettings) {
- clear();
-
- // order is important : the last override the first
- addProperties(databaseSettings);
- addProperties(bootstrapProperties);
-
- return this;
- }
-}
*/
package org.sonar.server.platform;
-import com.google.common.collect.ImmutableMap;
import java.util.Date;
import org.sonar.api.CoreProperties;
import org.sonar.api.Startable;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.DateUtils;
import org.sonar.db.DbClient;
+import org.sonar.db.property.PropertyDto;
/**
* The server node marked as "startup leader" generates some information about startup. These
public class StartupMetadataPersister implements Startable {
private final StartupMetadata metadata;
- private final PersistentSettings persistentSettings;
+ // PersistentSettings can not be used as it has to be
+ // instantiated in level 4 of container, whereas
+ // StartupMetadataPersister is level 3.
+ private final DbClient dbClient;
- public StartupMetadataPersister(StartupMetadata metadata, PersistentSettings persistentSettings) {
+ public StartupMetadataPersister(StartupMetadata metadata, DbClient dbClient) {
this.metadata = metadata;
- this.persistentSettings = persistentSettings;
+ this.dbClient = dbClient;
}
@Override
public void start() {
String startedAt = DateUtils.formatDateTime(new Date(metadata.getStartedAt()));
- persistentSettings.saveProperties(ImmutableMap.of(
- CoreProperties.SERVER_ID, metadata.getStartupId(),
- CoreProperties.SERVER_STARTTIME, startedAt));
+ save(CoreProperties.SERVER_ID, metadata.getStartupId());
+ save(CoreProperties.SERVER_STARTTIME, startedAt);
+ }
+
+ private void save(String key, String value) {
+ dbClient.propertiesDao().insertProperty(new PropertyDto().setKey(key).setValue(value));
}
@Override
import org.sonar.server.platform.LogServerVersion;
import org.sonar.server.platform.Platform;
import org.sonar.server.platform.ServerFileSystemImpl;
-import org.sonar.server.platform.ServerSettingsImpl;
import org.sonar.server.platform.TempFolderProvider;
import org.sonar.server.platform.UrlSettings;
import org.sonar.server.platform.cluster.ClusterImpl;
import org.sonar.server.ruby.PlatformRackBridge;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.search.EsSearchModule;
+import org.sonar.server.setting.ThreadLocalSettings;
import org.sonar.server.user.ThreadLocalUserSession;
public class PlatformLevel1 extends PlatformLevel {
add(
new SonarQubeVersion(apiVersion),
SonarRuntimeImpl.forSonarQube(apiVersion, SonarQubeSide.SERVER),
+ ThreadLocalSettings.class,
LogServerVersion.class,
ProcessCommandWrapperImpl.class,
RestartFlagHolderImpl.class,
- ServerSettingsImpl.class,
DefaultHttpDownloader.class,
UuidFactoryImpl.INSTANCE,
UrlSettings.class,
*/
package org.sonar.server.platform.platformlevel;
-import org.sonar.api.utils.Durations;
import org.sonar.core.i18n.DefaultI18n;
import org.sonar.core.i18n.RuleI18nManager;
import org.sonar.core.platform.PluginClassloaderFactory;
import org.sonar.server.plugins.ServerPluginRepository;
import org.sonar.server.plugins.WebServerExtensionInstaller;
import org.sonar.server.ruby.PlatformRubyBridge;
-import org.sonar.server.ui.JRubyI18n;
public class PlatformLevel2 extends PlatformLevel {
public PlatformLevel2(PlatformLevel parent) {
// depends on plugins
RailsAppsDeployer.class,
- JRubyI18n.class,
DefaultI18n.class,
RuleI18nManager.class,
- Durations.class,
+
// DB migration
PlatformDatabaseMigrationExecutorServiceImpl.class,
PlatformDatabaseMigration.class,
*/
package org.sonar.server.platform.platformlevel;
+import org.sonar.api.utils.Durations;
import org.sonar.api.utils.UriReader;
-import org.sonar.server.platform.PersistentSettings;
import org.sonar.server.platform.ServerIdGenerator;
import org.sonar.server.platform.ServerIdLoader;
import org.sonar.server.platform.StartupMetadataPersister;
+import org.sonar.server.setting.DatabaseSettingLoader;
+import org.sonar.server.setting.DatabaseSettingsEnabler;
import org.sonar.server.startup.LogServerId;
+import org.sonar.server.ui.JRubyI18n;
public class PlatformLevel3 extends PlatformLevel {
public PlatformLevel3(PlatformLevel parent) {
protected void configureLevel() {
addIfStartupLeader(StartupMetadataPersister.class);
add(
- PersistentSettings.class,
+ DatabaseSettingLoader.class,
+ DatabaseSettingsEnabler.class,
+ Durations.class,
+ JRubyI18n.class,
UriReader.class,
ServerIdLoader.class,
ServerIdGenerator.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.core.component.DefaultResourceTypes;
import org.sonar.core.timemachine.Periods;
import org.sonar.db.permission.PermissionRepository;
import org.sonar.server.permission.PermissionUpdater;
import org.sonar.server.permission.ws.PermissionsWsModule;
import org.sonar.server.platform.BackendCleanup;
+import org.sonar.server.platform.PersistentSettings;
import org.sonar.server.platform.ServerLogging;
import org.sonar.server.platform.SettingsChangeNotifier;
import org.sonar.server.platform.monitoring.DatabaseMonitor;
import org.sonar.server.rule.ws.RulesWs;
import org.sonar.server.rule.ws.TagsAction;
import org.sonar.server.serverid.ws.ServerIdWsModule;
-import org.sonar.server.setting.ProjectSettingsFactory;
import org.sonar.server.setting.ws.SettingsWsModule;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
WebServiceFilter.class,
// localization
+
L10nWs.class,
// authentication
TestIndexer.class,
// Settings
+ PersistentSettings.class,
PropertiesWs.class,
SettingsWsModule.class,
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
-import org.sonar.api.config.Settings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
private final PropertiesDao propertiesDao;
private final ComponentDao componentDao;
private final UserSession userSession;
- private final Settings settings;
- public QualityGates(DbClient dbClient, MetricFinder metricFinder, UserSession userSession, Settings settings) {
+ public QualityGates(DbClient dbClient, MetricFinder metricFinder, UserSession userSession) {
this.dbClient = dbClient;
this.dao = dbClient.qualityGateDao();
this.conditionDao = dbClient.gateConditionDao();
this.propertiesDao = dbClient.propertiesDao();
this.componentDao = dbClient.componentDao();
this.userSession = userSession;
- this.settings = settings;
}
public QualityGateDto create(String name) {
checkPermission();
if (idToUseAsDefault == null) {
propertiesDao.deleteGlobalProperty(SONAR_QUALITYGATE_PROPERTY);
- settings.removeProperty(SONAR_QUALITYGATE_PROPERTY);
} else {
QualityGateDto newDefault = getNonNullQgate(idToUseAsDefault);
propertiesDao.insertProperty(new PropertyDto().setKey(SONAR_QUALITYGATE_PROPERTY).setValue(newDefault.getId().toString()));
- settings.setProperty(SONAR_QUALITYGATE_PROPERTY, idToUseAsDefault);
}
}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.collect.ImmutableMap;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.property.PropertyDto;
+
+import static org.apache.commons.lang.StringUtils.defaultString;
+
+public class DatabaseSettingLoader implements SettingLoader {
+
+ private final DbClient dbClient;
+
+ public DatabaseSettingLoader(DbClient dbClient) {
+ this.dbClient = dbClient;
+ }
+
+ @Override
+ public String load(String key) {
+ PropertyDto dto = dbClient.propertiesDao().selectGlobalProperty(key);
+ if (dto != null) {
+ return defaultString(dto.getValue());
+ }
+ return null;
+ }
+
+ @Override
+ public void loadAll(ImmutableMap.Builder<String, String> appendTo) {
+ try (DbSession dbSession = dbClient.openSession(false)) {
+ dbClient.propertiesDao().selectGlobalProperties(dbSession)
+ .forEach(p -> appendTo.put(p.getKey(), defaultString(p.getValue())));
+ }
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import org.sonar.api.Startable;
+import org.sonar.api.ce.ComputeEngineSide;
+import org.sonar.api.server.ServerSide;
+
+@ComputeEngineSide
+@ServerSide
+public class DatabaseSettingsEnabler implements Startable {
+
+ private final ThreadLocalSettings settings;
+ private final DatabaseSettingLoader loader;
+
+ public DatabaseSettingsEnabler(ThreadLocalSettings settings, DatabaseSettingLoader loader) {
+ this.settings = settings;
+ this.loader = loader;
+ }
+
+ @Override
+ public void start() {
+ settings.setSettingLoader(loader);
+ }
+
+ @Override
+ public void stop() {
+ // nothing to do
+ }
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.collect.ImmutableMap;
+
+public class NopSettingLoader implements SettingLoader {
+ @Override
+ public String load(String key) {
+ return null;
+ }
+
+ @Override
+ public void loadAll(ImmutableMap.Builder<String, String> appendTo) {
+ // nothing to load
+ }
+
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.setting;
-
-import java.util.List;
-import org.sonar.api.ce.ComputeEngineSide;
-import org.sonar.api.config.Settings;
-import org.sonar.api.server.ServerSide;
-import org.sonar.db.property.PropertiesDao;
-import org.sonar.db.property.PropertyDto;
-
-@ServerSide
-@ComputeEngineSide
-public class ProjectSettingsFactory {
-
- private final PropertiesDao dao;
- private final Settings settings;
-
- public ProjectSettingsFactory(Settings settings, PropertiesDao dao) {
- this.dao = dao;
- this.settings = settings;
- }
-
- public Settings newProjectSettings(String projectKey) {
- List<PropertyDto> propertyList = dao.selectProjectProperties(projectKey);
- Settings projectSettings = new Settings(settings);
- for (PropertyDto property : propertyList) {
- projectSettings.setProperty(property.getKey(), property.getValue());
- }
- return projectSettings;
- }
-}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.collect.ImmutableMap;
+import javax.annotation.CheckForNull;
+
+public interface SettingLoader {
+
+ @CheckForNull
+ String load(String key);
+
+ void loadAll(ImmutableMap.Builder<String, String> appendTo);
+
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Properties;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.ce.ComputeEngineSide;
+import org.sonar.api.config.Encryption;
+import org.sonar.api.config.PropertyDefinitions;
+import org.sonar.api.config.Settings;
+import org.sonar.api.server.ServerSide;
+
+import static com.google.common.base.Preconditions.checkState;
+
+/**
+ * Merge of {@link SystemSettings} and the global properties stored in the db table "properties". These
+ * settings do not contain the settings specific to a project.
+ *
+ * <p>
+ * System settings have precedence on others.
+ * </p>
+ *
+ * <p>
+ * The thread-local cache is optional. It is disabled when the method {@link #unload()} has not
+ * been called. That allows to remove complexity with handling of cleanup of thread-local cache
+ * on daemon threads (notifications) or startup "main" thread.
+ * </p>
+ */
+@ComputeEngineSide
+@ServerSide
+public class ThreadLocalSettings extends Settings {
+
+ private final Properties systemProps;
+ private static final ThreadLocal<Map<String, String>> CACHE = new ThreadLocal<>();
+ private SettingLoader settingLoader;
+
+ public ThreadLocalSettings(PropertyDefinitions definitions, Properties props) {
+ this(definitions, props, new NopSettingLoader());
+ }
+
+ @VisibleForTesting
+ ThreadLocalSettings(PropertyDefinitions definitions, Properties props, SettingLoader settingLoader) {
+ super(definitions, new Encryption(null));
+ this.settingLoader = settingLoader;
+ this.systemProps = props;
+
+ // TODO something wrong about lifecycle here. It could be improved
+ getEncryption().setPathToSecretKey(props.getProperty(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
+ }
+
+ @VisibleForTesting
+ SettingLoader getSettingLoader() {
+ return settingLoader;
+ }
+
+ protected void setSettingLoader(SettingLoader settingLoader) {
+ this.settingLoader = Objects.requireNonNull(settingLoader);
+ }
+
+ @Override
+ protected Optional<String> get(String key) {
+ // search for the first value available in
+ // 1. system properties
+ // 2. thread local cache (if enabled)
+ // 3. db
+
+ String value = systemProps.getProperty(key);
+ if (value != null) {
+ return Optional.of(value);
+ }
+
+ Map<String, String> dbProps = CACHE.get();
+ // caching is disabled
+ if (dbProps == null) {
+ return Optional.ofNullable(settingLoader.load(key));
+ }
+
+ String loadedValue;
+ if (dbProps.containsKey(key)) {
+ // property may not exist in db. In this case key is present
+ // in cache but value is null
+ loadedValue = dbProps.get(key);
+ } else {
+ // cache the effective value (null if the property
+ // is not persisted)
+ loadedValue = settingLoader.load(key);
+ dbProps.put(key, loadedValue);
+ }
+ return Optional.ofNullable(loadedValue);
+ }
+
+ @Override
+ protected void set(String key, String value) {
+ Map<String, String> dbProps = CACHE.get();
+ if (dbProps != null) {
+ dbProps.put(key, value);
+ }
+ }
+
+ @Override
+ protected void remove(String key) {
+ Map<String, String> dbProps = CACHE.get();
+ if (dbProps != null) {
+ dbProps.remove(key);
+ }
+ }
+
+ /**
+ * Enables the thread specific cache of settings.
+ *
+ * @throws IllegalStateException if the current thread already has specific cache
+ */
+ public void load() {
+ checkState(CACHE.get() == null,
+ "load called twice for thread '%s' or state wasn't cleared last time it was used", Thread.currentThread().getName());
+ CACHE.set(new HashMap<>());
+ }
+
+ /**
+ * Clears the cache specific to the current thread (if any).
+ */
+ public void unload() {
+ CACHE.remove();
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
+ settingLoader.loadAll(builder);
+ systemProps.entrySet().forEach(entry -> builder.put((String) entry.getKey(), (String) entry.getValue()));
+ return builder.build();
+ }
+}
import org.sonar.process.ProcessProperties;
import org.sonar.server.authentication.IdentityProviderRepository;
import org.sonar.server.component.ComponentCleanerService;
-import org.sonar.server.platform.db.migrations.DatabaseMigrator;
import org.sonar.server.measure.MeasureFilterEngine;
import org.sonar.server.measure.MeasureFilterResult;
import org.sonar.server.platform.Platform;
import org.sonar.server.platform.ServerIdGenerator;
-import org.sonar.server.platform.ServerSettings;
-import org.sonar.server.platform.SettingsChangeNotifier;
+import org.sonar.server.platform.db.migrations.DatabaseMigrator;
import org.sonar.server.platform.ws.UpgradesAction;
import org.sonar.server.rule.RuleRepositories;
+import org.sonar.server.platform.PersistentSettings;
import org.sonar.server.user.NewUserNotifier;
import static com.google.common.collect.Lists.newArrayList;
}
public void setGlobalProperty(String key, @Nullable String value) {
- get(ServerSettings.class).setProperty(key, value);
- get(SettingsChangeNotifier.class).onGlobalPropertyChange(key, value);
+ get(PersistentSettings.class).saveProperty(key, value);
}
public Settings getSettings() {
}
private void stop() {
- threadLocalUserSession.remove();
+ threadLocalUserSession.unload();
if (oldUserSession != null) {
threadLocalUserSession.set(oldUserSession);
}
import org.apache.commons.lang.StringUtils;
import org.picocontainer.Startable;
import org.sonar.api.CoreProperties;
-import org.sonar.api.server.ServerSide;
import org.sonar.api.config.Settings;
import org.sonar.api.security.LoginPasswordAuthenticator;
import org.sonar.api.security.SecurityRealm;
+import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.SonarException;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
*/
public class ThreadLocalUserSession implements UserSession {
- private static final ThreadLocal<UserSession> THREAD_LOCAL = new ThreadLocal<>();
+ private static final ThreadLocal<UserSession> DELEGATE = new ThreadLocal<>();
public UserSession get() {
- UserSession currentUserSession = THREAD_LOCAL.get();
- if (currentUserSession != null) {
- return currentUserSession;
+ UserSession session = DELEGATE.get();
+ if (session != null) {
+ return session;
}
throw new UnauthorizedException();
}
public void set(UserSession session) {
- THREAD_LOCAL.set(session);
+ DELEGATE.set(session);
}
- public void remove() {
- THREAD_LOCAL.remove();
+ public void unload() {
+ DELEGATE.remove();
}
public boolean hasSession() {
- return THREAD_LOCAL.get() != null;
+ return DELEGATE.get() != null;
}
@Override
import javax.servlet.http.HttpServletResponse;
import org.sonar.server.authentication.UserSessionInitializer;
import org.sonar.server.platform.Platform;
+import org.sonar.server.setting.ThreadLocalSettings;
public class UserSessionFilter implements Filter {
private final Platform platform;
- private UserSessionInitializer userSessionInitializer;
public UserSessionFilter() {
this.platform = Platform.getInstance();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpServletResponse response = (HttpServletResponse) servletResponse;
+
+ ThreadLocalSettings settings = platform.getContainer().getComponentByType(ThreadLocalSettings.class);
+ UserSessionInitializer userSessionInitializer = platform.getContainer().getComponentByType(UserSessionInitializer.class);
+
+ settings.load();
try {
- HttpServletRequest request = (HttpServletRequest) servletRequest;
- HttpServletResponse response = (HttpServletResponse) servletResponse;
- init();
- if (!isInitialized() || userSessionInitializer.initUserSession(request, response)) {
+ if (userSessionInitializer == null || userSessionInitializer.initUserSession(request, response)) {
chain.doFilter(servletRequest, servletResponse);
}
} finally {
- if (isInitialized()) {
+ if (userSessionInitializer != null) {
userSessionInitializer.removeUserSession();
}
- }
- }
-
- private boolean isInitialized() {
- return userSessionInitializer != null;
- }
-
- private void init() {
- if (userSessionInitializer == null) {
- userSessionInitializer = platform.getContainer().getComponentByType(UserSessionInitializer.class);
+ settings.unload();
}
}
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.DefaultProcessCommands;
@Before
public void setUp() throws Exception {
ipcSharedDir = temp.newFolder();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(ProcessEntryPoint.PROPERTY_SHARED_PATH, ipcSharedDir.getAbsolutePath());
underTest = new CeHttpClient(settings);
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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 com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.CountDownLatch;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Encryption;
-import org.sonar.api.config.PropertyDefinitions;
-import org.sonar.core.platform.ComponentContainer;
-import org.sonar.db.DbClient;
-import org.sonar.db.property.PropertiesDao;
-import org.sonar.db.property.PropertyDto;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.entry;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class ComputeEngineSettingsTest {
- private static final String PROPERTY_KEY_1 = "property key 1";
- private static final String PROPERTY_VALUE_1 = "property value 1";
- private static final String PROPERTY_KEY_2 = "property key 2";
- private static final String PROPERTY_VALUE_2 = "property value 2";
- private static final String OTHER_PROP_1 = "otherProp1";
- private static final String OTHER_PROP_1_VALUE = "otherProp1Value";
- private static final String OTHER_PROP_2 = "otherProp2";
- private static final String OTHER_PROP_2_VALUE = "otherProp2Value";
- private static final String PROPERTY_3 = "property 3";
- private static final String PROPERTY_VALUE_3 = "property value 3";
- private static final String THREAD_PROPERTY = "thread";
- private static final String MAIN = "main";
- private static final String CAPTOR = "captor";
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- private PropertyDefinitions propertyDefinitions = new PropertyDefinitions();
- private Properties rootProperties = new Properties();
- private ComponentContainer container = new ComponentContainer();
- private DbClient dbClient = mock(DbClient.class);
- private PropertiesDao propertiesDao = mock(PropertiesDao.class);
- private ComputeEngineSettings underTest = new ComputeEngineSettings(propertyDefinitions, rootProperties, container);
-
- @Before
- public void setUp() throws Exception {
- rootProperties.setProperty(PROPERTY_KEY_1, PROPERTY_VALUE_1);
- rootProperties.setProperty(PROPERTY_KEY_2, PROPERTY_VALUE_2);
- container.add(dbClient);
- when(dbClient.propertiesDao()).thenReturn(propertiesDao);
- when(propertiesDao.selectGlobalProperties()).thenReturn(ImmutableList.of(
- new PropertyDto().setKey(PROPERTY_KEY_1).setValue(PROPERTY_VALUE_1),
- new PropertyDto().setKey(PROPERTY_KEY_2).setValue(PROPERTY_VALUE_2)));
- }
-
- @After
- public void tearDown() throws Exception {
- // prevent ThreadLocal leak
- underTest.unload();
- }
-
- @Test
- public void activateDatabaseSettings_populates_default_settings_with_content_of_root_properties_plus_map_argument_content() {
- assertThat(underTest.getProperties()).isEmpty();
-
- ImmutableMap<String, String> properties = ImmutableMap.of(OTHER_PROP_1, OTHER_PROP_1_VALUE, OTHER_PROP_2, OTHER_PROP_2_VALUE);
- underTest.activateDatabaseSettings(properties);
-
- assertThat(underTest.getProperties()).containsOnly(
- entry(PROPERTY_KEY_1, PROPERTY_VALUE_1),
- entry(PROPERTY_KEY_2, PROPERTY_VALUE_2),
- entry(OTHER_PROP_1, OTHER_PROP_1_VALUE),
- entry(OTHER_PROP_2, OTHER_PROP_2_VALUE));
-
- }
-
- @Test
- public void load_creates_a_thread_specific_properties_map() throws InterruptedException {
- Map<String, String> defaultProperties = underTest.getProperties();
- assertThat(defaultProperties).isEmpty();
-
- rootProperties.setProperty(THREAD_PROPERTY, MAIN);
- underTest.load();
-
- assertThat(underTest.getProperties()).contains(entry(THREAD_PROPERTY, MAIN));
-
- PropertiesCaptorThread loadPropertiesCaptor = new PropertiesCaptorThread(true);
-
- loadPropertiesCaptor.blockingExecute();
- assertThat(loadPropertiesCaptor.properties).contains(entry(THREAD_PROPERTY, CAPTOR));
-
- PropertiesCaptorThread noLoadPropertiesCaptor = new PropertiesCaptorThread(false);
-
- noLoadPropertiesCaptor.blockingExecute();
- assertThat(noLoadPropertiesCaptor.properties).isEmpty();
-
- underTest.unload();
-
- assertThat(underTest.getProperties()).isEmpty();
- }
-
- @Test
- public void load_throws_ISE_if_load_called_twice_without_unload_in_between() {
- underTest.load();
-
- expectedException.expect(IllegalStateException.class);
- expectedException.expectMessage("loadLocal called twice for Thread '" + Thread.currentThread().getName()
- + "' or state wasn't cleared last time it was used");
-
- underTest.load();
- }
-
- @Test
- public void getEncryption_returns_object_specific_to_current_thread_after_load() throws InterruptedException {
- Encryption defaultEncryption = underTest.getEncryption();
-
- underTest.load();
-
- Encryption mainEncryption = underTest.getEncryption();
- assertThat(mainEncryption).isNotSameAs(defaultEncryption);
-
- EncryptionCaptorThread loadEncryptionCaptor = new EncryptionCaptorThread(true);
- loadEncryptionCaptor.blockingExecute();
-
- assertThat(loadEncryptionCaptor.encryption).isNotSameAs(defaultEncryption);
- assertThat(loadEncryptionCaptor.encryption).isNotSameAs(mainEncryption);
-
- EncryptionCaptorThread noLoadEncryptionCaptor = new EncryptionCaptorThread(false);
- noLoadEncryptionCaptor.blockingExecute();
-
- assertThat(noLoadEncryptionCaptor.encryption).isSameAs(defaultEncryption);
-
- underTest.unload();
-
- assertThat(underTest.getEncryption()).isSameAs(defaultEncryption);
- }
-
- @Test
- public void getSettings_always_returns_current_ComputeEngineSettings_object() {
- assertThat(underTest.getSettings()).isSameAs(underTest);
-
- underTest.load();
-
- assertThat(underTest.getSettings()).isSameAs(underTest);
-
- underTest.unload();
-
- assertThat(underTest.getSettings()).isSameAs(underTest);
- }
-
- @Test
- public void clear_clears_settings_specific_to_current_thread_if_any() {
- underTest.activateDatabaseSettings(Collections.<String, String>emptyMap());
- assertThat(underTest.getProperties()).isNotEmpty();
-
- underTest.load();
-
- assertThat(underTest.getProperties()).isNotEmpty();
-
- underTest.clear();
-
- assertThat(underTest.getProperties()).isEmpty();
-
- underTest.unload();
-
- assertThat(underTest.getProperties()).isNotEmpty();
-
- underTest.clear();
-
- assertThat(underTest.getProperties()).isEmpty();
- }
-
- @Test
- public void removeProperty_removes_property_in_settings_specific_to_current_thread_if_any() {
- underTest.activateDatabaseSettings(Collections.<String, String>emptyMap());
- assertThat(underTest.getProperties()).containsKey(PROPERTY_KEY_2);
-
- underTest.load();
-
- assertThat(underTest.getProperties()).containsKey(PROPERTY_KEY_2);
-
- underTest.removeProperty(PROPERTY_KEY_2);
-
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_KEY_2);
-
- underTest.unload();
-
- assertThat(underTest.getProperties()).containsKey(PROPERTY_KEY_2);
-
- underTest.clear();
-
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_KEY_2);
- }
-
- @Test
- public void setProperty_sets_property_in_settings_specific_to_current_thread_if_any() {
- underTest.activateDatabaseSettings(Collections.<String, String>emptyMap());
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_3);
-
- underTest.load();
-
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_3);
-
- underTest.setProperty(PROPERTY_3, PROPERTY_VALUE_3);
-
- assertThat(underTest.getProperties()).contains(entry(PROPERTY_3, PROPERTY_VALUE_3));
-
- underTest.unload();
-
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_3);
-
- underTest.setProperty(PROPERTY_3, PROPERTY_VALUE_3);
-
- assertThat(underTest.getProperties()).contains(entry(PROPERTY_3, PROPERTY_VALUE_3));
- }
-
- @Test
- public void setProperties_sets_property_in_settings_specific_to_current_thread_if_any() {
- underTest.activateDatabaseSettings(Collections.<String, String>emptyMap());
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_3);
-
- underTest.load();
-
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_3);
-
- underTest.setProperties(ImmutableMap.of(PROPERTY_3, PROPERTY_VALUE_3));
-
- assertThat(underTest.getProperties()).contains(entry(PROPERTY_3, PROPERTY_VALUE_3));
-
- underTest.unload();
-
- assertThat(underTest.getProperties()).doesNotContainKey(PROPERTY_3);
-
- underTest.setProperties(ImmutableMap.of(PROPERTY_3, PROPERTY_VALUE_3));
-
- assertThat(underTest.getProperties()).contains(entry(PROPERTY_3, PROPERTY_VALUE_3));
- }
-
- @Test
- public void getString_gets_property_value_in_settings_specific_to_current_thread_if_any() {
- underTest.activateDatabaseSettings(Collections.<String, String>emptyMap());
- assertThat(underTest.getString(THREAD_PROPERTY)).isNull();
-
- rootProperties.setProperty(THREAD_PROPERTY, MAIN);
- underTest.load();
-
- assertThat(underTest.getString(THREAD_PROPERTY)).isEqualTo(MAIN);
-
- underTest.unload();
-
- assertThat(underTest.getString(THREAD_PROPERTY)).isNull();
- }
-
- @Test
- public void hasKey_checks_property_key_in_settings_specific_to_current_thread_if_any() {
- underTest.activateDatabaseSettings(Collections.<String, String>emptyMap());
- assertThat(underTest.hasKey(THREAD_PROPERTY)).isFalse();
-
- rootProperties.setProperty(THREAD_PROPERTY, MAIN);
- underTest.load();
-
- assertThat(underTest.hasKey(THREAD_PROPERTY)).isTrue();
-
- underTest.unload();
-
- assertThat(underTest.hasKey(THREAD_PROPERTY)).isFalse();
- }
-
- private abstract class CaptorThread extends Thread {
- private final boolean callLoad;
- private final CountDownLatch latch;
-
- public CaptorThread(boolean callLoad) {
- this.callLoad = callLoad;
- this.latch = new CountDownLatch(1);
- }
-
- public void blockingExecute() throws InterruptedException {
- this.start();
- this.latch.await(5, SECONDS);
- }
-
- @Override
- public void run() {
- if (callLoad) {
- try {
- rootProperties.setProperty(THREAD_PROPERTY, CAPTOR);
- underTest.load();
- doCapture();
- latch.countDown();
- } finally {
- underTest.unload();
- }
- } else {
- doCapture();
- latch.countDown();
- }
- }
-
- protected abstract void doCapture();
- }
-
- private class PropertiesCaptorThread extends CaptorThread {
- private Map<String, String> properties;
-
- public PropertiesCaptorThread(boolean callLoad) {
- super(callLoad);
- }
-
- protected void doCapture() {
- this.properties = underTest.getProperties();
- }
- }
-
- private class EncryptionCaptorThread extends CaptorThread {
- private Encryption encryption;
-
- public EncryptionCaptorThread(boolean callLoad) {
- super(callLoad);
- }
-
- protected void doCapture() {
- this.encryption = underTest.getEncryption();
- }
- }
-}
package org.sonar.ce.settings;
import org.junit.Test;
+import org.sonar.server.setting.ThreadLocalSettings;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new ActivityIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new ActivityIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().login();
package org.sonar.server.activity.index;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.NewIndex;
@Test
public void define() {
- ActivityIndexDefinition def = new ActivityIndexDefinition(new Settings());
+ ActivityIndexDefinition def = new ActivityIndexDefinition(new MapSettings());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.activity.Activity;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
public class ActivityIndexTest {
@Rule
- public EsTester es = new EsTester(new ActivityIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new ActivityIndexDefinition(new MapSettings()));
ActivityIndex underTest;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.process.DefaultProcessCommands;
import static org.assertj.core.api.Assertions.assertThat;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
@Test
public void requestSQRestart_throws_IAE_if_process_index_property_not_set() throws Exception {
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
HttpSession httpSession = mock(HttpSession.class);
System2 system2 = mock(System2.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
JwtSerializer jwtSerializer = mock(JwtSerializer.class);
JwtCsrfVerifier jwtCsrfVerifier = mock(JwtCsrfVerifier.class);
package org.sonar.server.authentication;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.sonar.server.authentication.JwtSerializer.JwtSession;
-
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
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.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.server.exceptions.UnauthorizedException;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.sonar.server.authentication.JwtSerializer.JwtSession;
+
public class JwtSerializerTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
- static final String SECRET_KEY = "HrPSavOYLNNrwTY+SOqpChr7OwvbR/zbDLdVXRN0+Eg=";
+ static final String A_SECRET_KEY = "HrPSavOYLNNrwTY+SOqpChr7OwvbR/zbDLdVXRN0+Eg=";
static final String USER_LOGIN = "john";
- Settings settings = new Settings();
- System2 system2 = System2.INSTANCE;
- UuidFactory uuidFactory = UuidFactoryImpl.INSTANCE;
-
- JwtSerializer underTest = new JwtSerializer(settings, system2, uuidFactory);
+ private Settings settings = new MapSettings();
+ private System2 system2 = System2.INSTANCE;
+ private UuidFactory uuidFactory = UuidFactoryImpl.INSTANCE;
+ private JwtSerializer underTest = new JwtSerializer(settings, system2, uuidFactory);
@Test
public void generate_token() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = underTest.encode(new JwtSession(USER_LOGIN, 10));
@Test
public void generate_token_with_expiration_date() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
+
underTest.start();
Date now = new Date();
assertThat(token).isNotEmpty();
Claims claims = underTest.decode(token).get();
- // Check expiration date it set to more than 9 seconds in the futur
+ // Check expiration date it set to more than 9 seconds in the future
assertThat(claims.getExpiration()).isAfterOrEqualsTo(new Date(now.getTime() + 9 * 1000));
}
@Test
public void generate_token_with_property() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = underTest.encode(new JwtSession(USER_LOGIN, 10, ImmutableMap.of("custom", "property")));
@Test
public void decode_token() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
Date now = new Date();
assertThat(claims.getSubject()).isEqualTo(USER_LOGIN);
assertThat(claims.getExpiration()).isNotNull();
assertThat(claims.getIssuedAt()).isNotNull();
- // Check expiration date it set to more than 19 minutes in the futur
+ // Check expiration date it set to more than 19 minutes in the future
assertThat(claims.getExpiration()).isAfterOrEqualsTo(new Date(now.getTime() + 19 * 60 * 1000));
}
@Test
public void return_no_token_when_expiration_date_is_reached() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder()
.setId("123")
.setIssuedAt(new Date(system2.now()))
.setExpiration(new Date(system2.now()))
- .signWith(SignatureAlgorithm.HS256, decodeSecretKey(SECRET_KEY))
+ .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY))
.compact();
assertThat(underTest.decode(token)).isEmpty();
@Test
public void return_no_token_when_secret_key_has_changed() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder()
@Test
public void fail_to_decode_token_when_no_id() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder()
.setIssuer("sonarqube")
.setIssuedAt(new Date(system2.now()))
.setExpiration(new Date(system2.now() + 20 * 60 * 1000))
- .signWith(SignatureAlgorithm.HS256, decodeSecretKey(SECRET_KEY))
+ .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY))
.compact();
expectedException.expect(UnauthorizedException.class);
@Test
public void fail_to_decode_token_when_no_subject() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder()
.setIssuer("sonarqube")
.setIssuedAt(new Date(system2.now()))
.setExpiration(new Date(system2.now() + 20 * 60 * 1000))
- .signWith(SignatureAlgorithm.HS256, decodeSecretKey(SECRET_KEY))
+ .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY))
.compact();
expectedException.expect(UnauthorizedException.class);
@Test
public void fail_to_decode_token_when_no_expiration_date() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder()
.setIssuer("sonarqube")
.setSubject(USER_LOGIN)
.setIssuedAt(new Date(system2.now()))
- .signWith(SignatureAlgorithm.HS256, decodeSecretKey(SECRET_KEY))
+ .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY))
.compact();
expectedException.expect(UnauthorizedException.class);
@Test
public void fail_to_decode_token_when_no_creation_date() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = Jwts.builder()
.setId("123")
.setSubject(USER_LOGIN)
.setExpiration(new Date(system2.now() + 20 * 60 * 1000))
- .signWith(SignatureAlgorithm.HS256, decodeSecretKey(SECRET_KEY))
+ .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY))
.compact();
expectedException.expect(UnauthorizedException.class);
}
@Test
- public void generate_new_secret_key_in_start() throws Exception {
- settings.setProperty("sonar.jwt.base64hs256secretKey", (String) null);
+ public void generate_new_secret_key_if_not_set_by_settings() throws Exception {
+ assertThat(underTest.getSecretKey()).isNull();
underTest.start();
- assertThat(settings.getString("sonar.auth.jwtBase64Hs256Secret")).isNotEmpty();
+ assertThat(underTest.getSecretKey()).isNotNull();
+ assertThat(underTest.getSecretKey().getAlgorithm()).isEqualTo(SignatureAlgorithm.HS256.getJcaName());
}
@Test
- public void does_not_generate_new_secret_key_in_start_if_already_exists() throws Exception {
- setDefaultSecretKey();
+ public void load_secret_key_from_settings() throws Exception {
+ setSecretKey(A_SECRET_KEY);
underTest.start();
- assertThat(settings.getString("sonar.auth.jwtBase64Hs256Secret")).isEqualTo(SECRET_KEY);
+ assertThat(settings.getString("sonar.auth.jwtBase64Hs256Secret")).isEqualTo(A_SECRET_KEY);
}
@Test
public void refresh_token() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
Date now = new Date();
@Test
public void refresh_token_generate_a_new_hash() throws Exception {
- setDefaultSecretKey();
+ setSecretKey(A_SECRET_KEY);
underTest.start();
String token = underTest.encode(new JwtSession(USER_LOGIN, 30));
Optional<Claims> claims = underTest.decode(token);
underTest.refresh(new DefaultClaims(), 10);
}
- private void setDefaultSecretKey() {
- settings.setProperty("sonar.auth.jwtBase64Hs256Secret", SECRET_KEY);
- }
-
private SecretKey decodeSecretKey(String encodedKey) {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
return new SecretKeySpec(decodedKey, 0, decodedKey.length, SignatureAlgorithm.HS256.getJcaName());
}
+
+ private void setSecretKey(String s) {
+ settings.setProperty("sonar.auth.jwtBase64Hs256Secret", s);
+ }
}
package org.sonar.server.authentication;
-import static java.util.Arrays.asList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.rules.ExpectedException.none;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.sonar.db.user.UserTesting.newUserDto;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
import org.sonar.api.security.Authenticator;
import org.sonar.api.security.ExternalGroupsProvider;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.user.SecurityRealmFactory;
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.rules.ExpectedException.none;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.sonar.db.user.UserTesting.newUserDto;
+
public class RealmAuthenticatorTest {
@Rule
ArgumentCaptor<UserIdentity> userIdentityArgumentCaptor = ArgumentCaptor.forClass(UserIdentity.class);
ArgumentCaptor<IdentityProvider> identityProviderArgumentCaptor = ArgumentCaptor.forClass(IdentityProvider.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class);
SecurityRealm realm = mock(SecurityRealm.class);
*/
package org.sonar.server.authentication;
-import static com.google.common.collect.Sets.newHashSet;
-import static java.util.Collections.singletonList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.utils.System2;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.user.index.UserIndexer;
+import static com.google.common.collect.Sets.newHashSet;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+
public class UserIdentityAuthenticatorTest {
static String USER_LOGIN = "github-johndoo";
DbSession dbSession = dbTester.getSession();
UserDao userDao = dbClient.userDao();
GroupDao groupDao = dbClient.groupDao();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class);
BasicAuthenticator basicAuthenticator = mock(BasicAuthenticator.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
UserDto user = newUserDto();
verifyZeroInteractions(userSession);
}
- @Test
- public void remove_user_session() throws Exception {
- underTest.removeUserSession();
-
- verify(userSession).remove();
- }
-
private void assertPathIsIgnored(String path) {
when(request.getRequestURI()).thenReturn(path);
@Before
public void setUp() throws Exception {
- threadLocalUserSession.remove();
+ threadLocalUserSession.unload();
dbClient.userDao().insert(dbSession, user);
dbSession.commit();
}
package org.sonar.server.authentication.ws;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.sonar.db.user.UserTesting.newUserDto;
-
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.authentication.BasicAuthenticator;
import org.sonar.server.authentication.JwtHttpHandler;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.test.JsonAssert;
import org.sonarqube.ws.MediaTypes;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.sonar.db.user.UserTesting.newUserDto;
+
public class ValidateActionTest {
StringWriter stringWriter = new StringWriter();
BasicAuthenticator basicAuthenticator = mock(BasicAuthenticator.class);
JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
ValidateAction underTest = new ValidateAction(settings, basicAuthenticator, jwtHttpHandler);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.security.DefaultGroups;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.scanner.protocol.input.ScannerInput.User;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.UnauthorizedException;
public ExpectedException thrown = ExpectedException.none();
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.MessageException;
import static java.lang.Math.abs;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
@Test
public void getWorkCount_returns_1_when_worker_property_is_not_defined() {
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.Logger;
import org.sonar.core.config.PurgeConstants;
import org.sonar.db.DbSession;
private PurgeProfiler profiler = mock(PurgeProfiler.class);
private DefaultPeriodCleaner periodCleaner = mock(DefaultPeriodCleaner.class);
private PurgeListener purgeListener = mock(PurgeListener.class);
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
@Before
public void before() {
import org.junit.rules.ExpectedException;
import org.sonar.api.ce.measure.Component;
import org.sonar.api.ce.measure.MeasureComputer;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.CoreMetrics;
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.TreeRootHolderRule;
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.issue.ComponentIssuesRepositoryRule;
import org.sonar.server.computation.task.projectanalysis.measure.Measure;
import org.sonar.server.computation.task.projectanalysis.measure.MeasureRepositoryRule;
private static final String FILE_1_KEY = "fileKey";
private static final int FILE_2_REF = 12342;
- private static final org.sonar.server.computation.task.projectanalysis.component.Component FILE_1 = builder(org.sonar.server.computation.task.projectanalysis.component.Component.Type.FILE, FILE_1_REF)
- .setKey(FILE_1_KEY)
- .build();
+ private static final org.sonar.server.computation.task.projectanalysis.component.Component FILE_1 = builder(
+ org.sonar.server.computation.task.projectanalysis.component.Component.Type.FILE, FILE_1_REF)
+ .setKey(FILE_1_KEY)
+ .build();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule()
.setRoot(builder(org.sonar.server.computation.task.projectanalysis.component.Component.Type.PROJECT, PROJECT_REF).setKey("project")
.addChildren(
FILE_1,
- builder(org.sonar.server.computation.task.projectanalysis.component.Component.Type.FILE, FILE_2_REF).setKey("fileKey2").build()
- ).build());
+ builder(org.sonar.server.computation.task.projectanalysis.component.Component.Type.FILE, FILE_2_REF).setKey("fileKey2").build())
+ .build());
@Rule
public MetricRepositoryRule metricRepository = new MetricRepositoryRule()
.add(new MetricImpl(3, DOUBLE_METRIC_KEY, "double metric", Metric.MetricType.FLOAT))
.add(new MetricImpl(4, LONG_METRIC_KEY, "long metric", Metric.MetricType.MILLISEC))
.add(new MetricImpl(5, STRING_METRIC_KEY, "string metric", Metric.MetricType.STRING))
- .add(new MetricImpl(6, BOOLEAN_METRIC_KEY, "boolean metric", Metric.MetricType.BOOL))
- ;
+ .add(new MetricImpl(6, BOOLEAN_METRIC_KEY, "boolean metric", Metric.MetricType.BOOL));
@Rule
public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository);
@Test
public void get_string_settings() throws Exception {
- org.sonar.api.config.Settings serverSettings = new org.sonar.api.config.Settings();
+ org.sonar.api.config.Settings serverSettings = new MapSettings();
serverSettings.setProperty("prop", "value");
when(settingsRepository.getSettings(FILE_1)).thenReturn(serverSettings);
@Test
public void get_string_array_settings() throws Exception {
- org.sonar.api.config.Settings serverSettings = new org.sonar.api.config.Settings();
+ org.sonar.api.config.Settings serverSettings = new MapSettings();
serverSettings.setProperty("prop", "1,3.4,8,50");
when(settingsRepository.getSettings(FILE_1)).thenReturn(serverSettings);
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
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.PropertiesDao;
import org.sonar.db.property.PropertyDto;
-import org.sonar.server.setting.ProjectSettingsFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.PROJECT;
DbSession session;
- Settings globalSettings;
+ MapSettings globalSettings;
SettingsRepository underTest;
@Before
public void createDao() {
- globalSettings = new Settings();
- PropertiesDao propertiesDao = new PropertiesDao(dbTester.myBatis());
+ globalSettings = new MapSettings();
session = dbClient.openSession(false);
- underTest = new SettingsRepositoryImpl(new ProjectSettingsFactory(globalSettings, propertiesDao));
+ underTest = new SettingsRepositoryImpl(new ProjectSettingsFactory(globalSettings, dbClient));
}
@After
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.duplications.block.Block;
static final String OTHER_FILE_KEY = "OTHER_FILE_KEY";
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
IntegrateCrossProjectDuplications underTest = new IntegrateCrossProjectDuplications(settings, duplicationRepository);
package org.sonar.server.computation.task.projectanalysis.issue;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.i18n.I18n;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
@org.junit.Rule
public RuleRepositoryRule ruleRepository = new RuleRepositoryRule().add(rule);
- DebtCalculator underTest = new DebtCalculator(ruleRepository, new Durations(new Settings(), mock(I18n.class)));
+ DebtCalculator underTest = new DebtCalculator(ruleRepository, new Durations(new MapSettings(), mock(I18n.class)));
@Test
public void no_debt_if_function_is_not_defined() {
import org.mockito.Mockito;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
+import org.sonar.api.config.MapSettings;
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.TreeRootHolderRule;
import org.sonar.server.user.index.UserDoc;
import org.sonar.server.user.index.UserIndex;
TreeRootHolderRule rootHolder = mock(TreeRootHolderRule.class, Mockito.RETURNS_DEEP_STUBS);
UserIndex userIndex = mock(UserIndex.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
SettingsRepository settingsRepository = mock(SettingsRepository.class);
DefaultAssignee underTest = new DefaultAssignee(rootHolder, userIndex, settingsRepository);
import java.util.Collections;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.server.es.EsTester;
public class ScmAccountToUserLoaderTest {
@org.junit.Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
@org.junit.Rule
public LogTester logTester = new LogTester();
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.issue.DefaultIssue;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
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.TreeRootHolderRule;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void accept_everything_when_no_filter_properties() throws Exception {
- IssueFilter underTest = newIssueFilter(new Settings());
+ IssueFilter underTest = newIssueFilter(new MapSettings());
assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isTrue();
assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isTrue();
}
private static Settings newSettings(List<String> exclusionsProperties, List<String> inclusionsProperties) {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
if (!exclusionsProperties.isEmpty()) {
addProperties(exclusionsProperties, "ignore", settings);
}
import org.junit.rules.ExpectedException;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.MessageException;
@Before
public void setUp() {
- settings = new Settings();
+ settings = new MapSettings();
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.security.DefaultGroups;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.permission.PermissionRepository;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.GroupRoleDto;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.Component;
import org.sonar.server.computation.task.projectanalysis.component.MutableDbIdsRepositoryRule;
import org.sonar.server.computation.task.projectanalysis.component.ReportComponent;
+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 org.sonar.server.es.EsTester;
private static final long SOME_DATE = 1000L;
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
DbClient dbClient = dbTester.getDbClient();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
IssueAuthorizationIndexer issueAuthorizationIndexer;
import org.elasticsearch.search.SearchHit;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.Component;
import org.sonar.server.computation.task.projectanalysis.component.ReportComponent;
+import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.step.ComputationStep;
import org.sonar.server.es.EsTester;
import org.sonar.server.test.db.TestTesting;
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester esTester = new EsTester(new TestIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new TestIndexDefinition(new MapSettings()));
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.LogTester;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.server.computation.task.projectanalysis.component.Component;
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;
import org.sonar.server.computation.task.projectanalysis.period.PeriodsHolderImpl;
PeriodsHolderImpl periodsHolder = new PeriodsHolderImpl();
DbClient dbClient = dbTester.getDbClient();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
SettingsRepository settingsRepository = mock(SettingsRepository.class);
LoadPeriodsStep underTest;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.purge.IdUuidPair;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
+import org.sonar.server.computation.dbcleaner.ProjectCleaner;
import org.sonar.server.computation.task.projectanalysis.component.Component;
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.dbcleaner.ProjectCleaner;
import org.sonar.server.computation.task.step.ComputationStep;
import org.sonar.server.util.WrapInSingleElementArray;
private void verify_call_purge_method_of_the_purge_task(Component project) {
treeRootHolder.setRoot(project);
- when(settingsRepository.getSettings(project)).thenReturn(new Settings());
+ when(settingsRepository.getSettings(project)).thenReturn(new MapSettings());
dbIdsRepository.setComponentId(project, PROJECT_ID);
underTest.execute();
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
-import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.computation.task.projectanalysis.component.Component;
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;
import org.sonar.server.computation.task.projectanalysis.qualitygate.MutableQualityGateHolderRule;
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 Settings());
+ when(settingsRepository.getSettings(root)).thenReturn(new MapSettings());
underTest.execute();
.andMessage(format("Unsupported value (%s) in property sonar.qualitygate", "10 sds")));
treeRootHolder.setRoot(PROJECT_ALONE);
- when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new Settings().setProperty("sonar.qualitygate", "10 sds"));
+ when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", "10 sds"));
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 Settings().setProperty("sonar.qualitygate", 10));
+ when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", 10));
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 Settings().setProperty("sonar.qualitygate", 10));
+ when(settingsRepository.getSettings(PROJECT_ALONE)).thenReturn(new MapSettings().setProperty("sonar.qualitygate", 10));
when(qualityGateService.findById(10)).thenReturn(Optional.of(qualityGate));
underTest.execute();
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.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.permission.GlobalPermissions;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
- DbClient dbClient = db.getDbClient();
- PropertyDbTester propertyDb = new PropertyDbTester(db);
- org.sonar.api.config.Settings settings = new org.sonar.api.config.Settings();
+ private DbClient dbClient = db.getDbClient();
+ private PropertyDbTester propertyDb = new PropertyDbTester(db);
+ private Settings settings = new MapSettings();
- WsActionTester ws = new WsActionTester(new UpdateConfigurationAction(dbClient, userSession, settings));
+ private WsActionTester ws = new WsActionTester(new UpdateConfigurationAction(dbClient, userSession, settings));
@Test
public void update_email_settings() throws Exception {
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.ProcessProperties;
@Rule
public LogTester logTester = new LogTester();
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
private EsClientProvider underTest = new EsClientProvider();
private String localhost;
import org.elasticsearch.node.NodeBuilder;
import org.elasticsearch.search.SearchHit;
import org.junit.rules.ExternalResource;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.core.platform.ComponentContainer;
import static com.google.common.base.Preconditions.checkState;
if (!indexDefinitions.isEmpty()) {
container = new ComponentContainer();
- container.addSingleton(new Settings());
+ container.addSingleton(new MapSettings());
container.addSingletons(indexDefinitions);
container.addSingleton(client);
container.addSingleton(IndexDefinitions.class);
*/
package org.sonar.server.es;
+import java.io.IOException;
+import java.util.Map;
+import javax.annotation.CheckForNull;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.junit.Rule;
import org.junit.Test;
-
-import javax.annotation.CheckForNull;
-
-import java.io.IOException;
-import java.util.Map;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
public void create_index() throws Exception {
assertThat(mappings()).isEmpty();
- IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new Settings());
+ IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new MapSettings());
registry.start();
IndexCreator creator = new IndexCreator(es.client(), registry);
creator.start();
assertThat(mappings()).isEmpty();
// v1
- IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new Settings());
+ IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinition()}, new MapSettings());
registry.start();
IndexCreator creator = new IndexCreator(es.client(), registry);
creator.start();
assertThat(hashV1).isNotEmpty();
// v2
- registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinitionV2()}, new Settings());
+ registry = new IndexDefinitions(new IndexDefinition[] {new FakeIndexDefinitionV2()}, new MapSettings());
registry.start();
creator = new IndexCreator(es.client(), registry);
creator.start();
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;
+import org.sonar.api.config.MapSettings;
import org.sonar.process.ProcessProperties;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void default_shards_and_replicas() {
NewIndex index = new NewIndex("issues");
- index.configureShards(new org.sonar.api.config.Settings());
+ index.configureShards(new MapSettings());
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_SHARDS)).isEqualTo(String.valueOf(NewIndex.DEFAULT_NUMBER_OF_SHARDS));
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS)).isEqualTo("0");
}
@Test
public void five_shards_and_one_replica_by_default_on_cluster() {
NewIndex index = new NewIndex("issues");
- org.sonar.api.config.Settings settings = new org.sonar.api.config.Settings();
+ MapSettings settings = new MapSettings();
settings.setProperty(ProcessProperties.CLUSTER_ENABLED, "true");
index.configureShards(settings);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_SHARDS)).isEqualTo(String.valueOf(NewIndex.DEFAULT_NUMBER_OF_SHARDS));
@Test
public void customize_number_of_shards() {
NewIndex index = new NewIndex("issues");
- org.sonar.api.config.Settings settings = new org.sonar.api.config.Settings();
+ MapSettings settings = new MapSettings();
settings.setProperty("sonar.search.issues.shards", "3");
index.configureShards(settings);
assertThat(index.getSettings().get(IndexMetaData.SETTING_NUMBER_OF_SHARDS)).isEqualTo("3");
@Test
public void customize_number_of_shards_and_replicas() {
NewIndex index = new NewIndex("issues");
- org.sonar.api.config.Settings settings = new org.sonar.api.config.Settings();
+ MapSettings settings = new MapSettings();
settings.setProperty("sonar.search.issues.shards", "3");
settings.setProperty("sonar.search.issues.replicas", "1");
index.configureShards(settings);
import org.elasticsearch.search.SearchHit;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
@Test
public void index_nothing() {
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
public class IssueIndexDebtTest {
@Rule
- public EsTester tester = new EsTester(new IssueIndexDefinition(new Settings()), new ViewIndexDefinition(new Settings()));
+ public EsTester tester = new EsTester(new IssueIndexDefinition(new MapSettings()), new ViewIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
package org.sonar.server.issue.index;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.NewIndex;
@Test
public void define() {
- IssueIndexDefinition def = new IssueIndexDefinition(new Settings());
+ IssueIndexDefinition def = new IssueIndexDefinition(new MapSettings());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.issue.Issue;
import org.sonar.api.resources.Scopes;
import org.sonar.api.rule.RuleKey;
public class IssueIndexTest {
@Rule
- public EsTester tester = new EsTester(new IssueIndexDefinition(new Settings()), new ViewIndexDefinition(new Settings()));
+ public EsTester tester = new EsTester(new IssueIndexDefinition(new MapSettings()), new ViewIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
import org.elasticsearch.search.SearchHit;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
private static final String A_PROJECT_UUID = "P1";
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.api.utils.System2;
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
DbClient dbClient = db.getDbClient();
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.Metric;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
private static final String DEFAULT_PROJECT_KEY = "project-key";
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Rule
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
WsTester ws;
DbClient dbClient = db.getDbClient();
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.api.utils.System2;
import org.sonar.core.permission.GlobalPermissions;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
DbClient dbClient = db.getDbClient();
DbSession dbSession = db.getSession();
System2 system = mock(System2.class);
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.notifications.NotificationChannel;
import org.sonar.db.DbClient;
when(qualityGateChange.getType()).thenReturn("qgate-changes");
when(manager.getFromQueue()).thenReturn(notification).thenReturn(null);
- Settings settings = new Settings().setProperty("sonar.notifications.delay", 1L);
+ Settings settings = new MapSettings().setProperty("sonar.notifications.delay", 1L);
service = new NotificationService(settings, manager,
dbClient,
@Test
public void getDispatchers_empty() {
- Settings settings = new Settings().setProperty("sonar.notifications.delay", 1L);
+ Settings settings = new MapSettings().setProperty("sonar.notifications.delay", 1L);
service = new NotificationService(settings, manager, dbClient);
assertThat(service.getDispatchers()).hasSize(0);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.permission.GroupWithPermissionDto;
import org.sonar.db.permission.OldPermissionQuery;
import org.sonar.db.permission.PermissionRepository;
-import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.UserWithPermissionDto;
+import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.GroupRoleDto;
import org.sonar.db.user.UserDto;
dbClient = db.getDbClient();
dbSession = db.getSession();
- PermissionRepository repository = new PermissionRepository(dbClient, new Settings());
+ PermissionRepository repository = new PermissionRepository(dbClient, new MapSettings());
ComponentFinder componentFinder = new ComponentFinder(dbClient);
PermissionService permissionService = new PermissionService(dbClient, repository, issueAuthorizationIndexer, userSession, componentFinder);
PermissionDependenciesFinder permissionDependenciesFinder = new PermissionDependenciesFinder(dbClient, componentFinder, new UserGroupFinder(dbClient), resourceTypes);
package org.sonar.server.permission.ws.template;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.sonar.db.component.ComponentTesting.newDeveloper;
-import static org.sonar.db.component.ComponentTesting.newProjectDto;
-import static org.sonar.db.component.ComponentTesting.newView;
-import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
-import static org.sonar.db.user.GroupMembershipQuery.IN;
-import static org.sonar.db.user.GroupTesting.newGroupDto;
-import static org.sonar.db.user.UserTesting.newUserDto;
-import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
-import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
-import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
-
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.permission.GroupWithPermissionDto;
import org.sonar.db.permission.OldPermissionQuery;
import org.sonar.db.permission.PermissionRepository;
-import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.UserWithPermissionDto;
+import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.GroupDbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.GroupRoleDto;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.sonar.db.component.ComponentTesting.newDeveloper;
+import static org.sonar.db.component.ComponentTesting.newProjectDto;
+import static org.sonar.db.component.ComponentTesting.newView;
+import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
+import static org.sonar.db.user.GroupMembershipQuery.IN;
+import static org.sonar.db.user.GroupTesting.newGroupDto;
+import static org.sonar.db.user.UserTesting.newUserDto;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
+
public class BulkApplyTemplateActionTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().login("login").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
@Before
public void setUp() {
- PermissionRepository repository = new PermissionRepository(dbClient, new Settings());
+ PermissionRepository repository = new PermissionRepository(dbClient, new MapSettings());
ComponentFinder componentFinder = new ComponentFinder(dbClient);
PermissionService permissionService = new PermissionService(dbClient, repository, issueAuthorizationIndexer, userSession, componentFinder);
PermissionDependenciesFinder permissionDependenciesFinder = new PermissionDependenciesFinder(dbClient, componentFinder, new UserGroupFinder(dbClient), resourceTypes);
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
public class DefaultPermissionTemplateFinderTest {
- ResourceTypes resourceTypes = mock(ResourceTypes.class);
- Settings settings = new Settings();
-
- DefaultPermissionTemplateFinder underTest;
+ private ResourceTypes resourceTypes = mock(ResourceTypes.class);
+ private Settings settings = new MapSettings();
+ private DefaultPermissionTemplateFinder underTest;
@Before
public void setUp() {
underTest = new DefaultPermissionTemplateFinder(settings, resourceTypes);
+ when(resourceTypes.getRoots()).thenReturn(rootResourceTypes());
+ }
+
+ @Test
+ public void get_default_template_uuids_in_settings() {
settings
.setProperty(DEFAULT_TEMPLATE_PROPERTY, "default-template-uuid")
.setProperty(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT), "default-project-template-uuid")
.setProperty(defaultRootQualifierTemplateProperty("DEV"), "default-dev-template-uuid")
.setProperty(defaultRootQualifierTemplateProperty(Qualifiers.VIEW), "default-view-template-uuid");
- when(resourceTypes.getRoots()).thenReturn(rootResourceTypes());
- }
- @Test
- public void get_default_template_uuids_in_settings() {
Set<String> result = underTest.getDefaultTemplateUuids();
assertThat(result).containsOnly("default-project-template-uuid", "default-view-template-uuid", "default-dev-template-uuid");
@Test
public void get_default_template_uuid_if_no_property() {
- settings
- .clear()
- .setProperty(DEFAULT_TEMPLATE_PROPERTY, "default-template-uuid");
+ settings.setProperty(DEFAULT_TEMPLATE_PROPERTY, "default-template-uuid");
underTest = new DefaultPermissionTemplateFinder(settings, resourceTypes);
Set<String> result = underTest.getDefaultTemplateUuids();
@Test
public void get_default_project_template_uuid_if_no_property_for_views() {
settings
- .clear()
.setProperty(DEFAULT_TEMPLATE_PROPERTY, "default-template-uuid")
.setProperty(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT), "default-project-template-uuid")
.setProperty(defaultRootQualifierTemplateProperty("DEV"), "default-dev-template-uuid");
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ResourceTypesRule;
-import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
+import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.UnauthorizedException;
public void setUp() {
i18n.setProjectPermissions();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(defaultRootQualifierTemplateProperty(Qualifiers.PROJECT), UUID_EXAMPLE_01);
settings.setProperty(defaultRootQualifierTemplateProperty(Qualifiers.VIEW), UUID_EXAMPLE_02);
settings.setProperty(defaultRootQualifierTemplateProperty("DEV"), UUID_EXAMPLE_03);
package org.sonar.server.permission.ws.template;
import java.util.List;
-import java.util.Properties;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.PropertyDefinitions;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.server.i18n.I18nRule;
import org.sonar.server.permission.ws.PermissionDependenciesFinder;
import org.sonar.server.platform.PersistentSettings;
-import org.sonar.server.platform.ServerSettingsImpl;
+import org.sonar.server.platform.SettingsChangeNotifier;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usergroups.ws.UserGroupFinder;
import org.sonar.server.ws.TestRequest;
@Before
public void setUp() {
DbClient dbClient = db.getDbClient();
- persistentSettings = new PersistentSettings(dbClient, new ServerSettingsImpl(new PropertyDefinitions(), new Properties()));
+ persistentSettings = new PersistentSettings(new MapSettings(), dbClient, new SettingsChangeNotifier());
persistentSettings.saveProperty(DEFAULT_TEMPLATE_PROPERTY, "any-template-uuid");
persistentSettings.saveProperty(defaultRootQualifierTemplateProperty(PROJECT), "any-template-uuid");
persistentSettings.saveProperty(defaultRootQualifierTemplateProperty(VIEW), "any-view-template-uuid");
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleTesting;
@Rule
public EsTester esTester = new EsTester(
- new RuleIndexDefinition(new Settings()),
- new IssueIndexDefinition(new Settings()),
- new ViewIndexDefinition(new Settings())
+ new RuleIndexDefinition(new MapSettings()),
+ new IssueIndexDefinition(new MapSettings()),
+ new ViewIndexDefinition(new MapSettings())
);
@Rule
*/
package org.sonar.server.platform;
-import com.google.common.collect.ImmutableMap;
-import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.PropertyDefinitions;
+import org.sonar.api.config.MapSettings;
+import org.sonar.api.config.Settings;
import org.sonar.api.utils.System2;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.property.PropertiesDao;
-import org.sonar.db.property.PropertyDto;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
public class PersistentSettingsTest {
-
@Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- DbClient dbClient = db.getDbClient();
- DbSession dbSession = db.getSession();
-
- private PropertiesDao dao = dbClient.propertiesDao();
- private ServerSettings settings = new ServerSettingsImpl(
- new PropertyDefinitions(),
- new Properties());
-
- @Test
- public void load_database_properties_at_startup() {
- newGlobalProperty("in_db", "bar");
-
- PersistentSettings persistentSettings = new PersistentSettings(dbClient, settings);
- persistentSettings.start();
-
- assertThat(settings.getString("in_db")).isEqualTo("bar");
- }
-
- @Test
- public void saveProperty() {
- PersistentSettings persistentSettings = new PersistentSettings(dbClient, settings);
- persistentSettings.saveProperty("foo", "bar");
-
- // kept in memory cache and persisted in db
- assertThat(settings.getString("foo")).isEqualTo("bar");
- verifyGlobalPropertyExists("foo", "bar");
- }
-
- @Test
- public void deleteProperty() {
- newGlobalProperty("foo", "bar_in_db");
- settings.setProperty("foo", "bar");
- assertThat(settings.hasKey("foo")).isTrue();
-
- PersistentSettings persistentSettings = new PersistentSettings(dbClient, settings);
- persistentSettings.deleteProperty("foo");
-
- assertThat(settings.hasKey("foo")).isFalse();
- verifyGlobalPropertyDoesNotExist("foo");
- }
+ public DbTester dbTester = DbTester.create(System2.INSTANCE);
+ private Settings delegate = new MapSettings();
+ private SettingsChangeNotifier changeNotifier = mock(SettingsChangeNotifier.class);
+ private PersistentSettings underTest = new PersistentSettings(delegate, dbTester.getDbClient(), changeNotifier);
@Test
- public void deleteProperties() {
- newGlobalProperty("in_db1", "foo");
- newGlobalProperty("in_db2", "bar");
- settings.setProperty("foo", "bar");
- assertThat(settings.hasKey("foo")).isTrue();
+ public void insert_property_into_database_and_notify_extensions() {
+ assertThat(underTest.getString("foo")).isNull();
- PersistentSettings persistentSettings = new PersistentSettings(dbClient, settings);
- persistentSettings.deleteProperties();
+ underTest.saveProperty("foo", "bar");
- assertThat(settings.getProperties()).isEmpty();
- assertThat(dao.selectGlobalProperties()).isEmpty();
+ assertThat(underTest.getString("foo")).isEqualTo("bar");
+ assertThat(dbTester.getDbClient().propertiesDao().selectGlobalProperty("foo").getValue()).isEqualTo("bar");
+ verify(changeNotifier).onGlobalPropertyChange("foo", "bar");
}
@Test
- public void shortcuts_on_settings() {
- settings.setProperty("foo", "bar");
- assertThat(settings.hasKey("foo")).isTrue();
+ public void delete_property_from_database_and_notify_extensions() {
+ underTest.saveProperty("foo", "bar");
+ underTest.saveProperty("foo", null);
- PersistentSettings persistentSettings = new PersistentSettings(dbClient, settings);
-
- assertThat(persistentSettings.getProperties()).isEqualTo(settings.getProperties());
- assertThat(persistentSettings.getString("foo")).isEqualTo("bar");
- assertThat(persistentSettings.getSettings()).isEqualTo(settings);
+ assertThat(underTest.getString("foo")).isNull();
+ assertThat(dbTester.getDbClient().propertiesDao().selectGlobalProperty("foo")).isNull();
+ verify(changeNotifier).onGlobalPropertyChange("foo", null);
}
@Test
- public void saveProperties() {
- PersistentSettings persistentSettings = new PersistentSettings(dbClient, settings);
- ImmutableMap<String, String> props = ImmutableMap.of("foo", "bar");
- persistentSettings.saveProperties(props);
-
- assertThat(settings.getString("foo")).isEqualTo("bar");
- verifyGlobalPropertyExists("foo", "bar");
+ public void getSettings_returns_delegate() {
+ assertThat(underTest.getSettings()).isSameAs(delegate);
}
-
- private PropertyDto newGlobalProperty(String key, String value) {
- PropertyDto propertyDto = new PropertyDto().setKey(key).setValue(value);
- dao.insertProperty(dbSession, propertyDto);
- dbSession.commit();
- return propertyDto;
- }
-
- private void verifyGlobalPropertyExists(String key, String value){
- PropertyDto propertyDto = dao.selectGlobalProperty(dbSession, key);
- assertThat(propertyDto).isNotNull();
- assertThat(propertyDto.getValue()).isEqualTo(value);
- assertThat(propertyDto.getUserId()).isNull();
- assertThat(propertyDto.getResourceId()).isNull();
- }
-
- private void verifyGlobalPropertyDoesNotExist(String key){
- assertThat(dao.selectGlobalProperty(dbSession, key)).isNull();
- }
-
}
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
private static final String AN_IP = "1.2.3.4";
public static final String AN_ORGANISATION = "corp";
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
ServerIdGenerator idGenerator = mock(ServerIdGenerator.class);
ServerIdLoader underTest = new ServerIdLoader(settings, idGenerator);
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.Version;
import static org.assertj.core.api.Assertions.assertThat;
public class ServerImplTest {
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
private StartupMetadata state = mock(StartupMetadata.class);
private ServerFileSystem fs = mock(ServerFileSystem.class);
private UrlSettings urlSettings = mock(UrlSettings.class);
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.LogbackHelper;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
ServerLogging underTest = new ServerLogging(settings);
@Rule
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.platform;
-
-import com.google.common.collect.ImmutableMap;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.config.PropertyDefinitions;
-
-import java.util.Map;
-import java.util.Properties;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class ServerSettingsTest {
-
- Properties properties;
-
- ServerSettingsImpl settings;
-
- @Before
- public void before() {
- properties = new Properties();
- properties.put("hello", "world");
- properties.put("in_file", "true");
- properties.put("ServerSettingsTestEnv", "in_file");
- settings = new ServerSettingsImpl(new PropertyDefinitions(), properties);
- }
-
- @Test
- public void load_properties_file() {
- assertThat(settings.getString("hello")).isEqualTo("world");
- }
-
- @Test
- public void activate_database_settings() {
- Map<String, String> databaseProperties = ImmutableMap.of("in_db", "true");
- settings.activateDatabaseSettings(databaseProperties);
-
- assertThat(settings.getString("in_db")).isEqualTo("true");
- }
-
- @Test
- public void file_settings_override_db_settings() {
- assertThat(settings.getString("in_file")).isEqualTo("true");
-
- Map<String, String> databaseProperties = ImmutableMap.of("in_file", "false");
- settings.activateDatabaseSettings(databaseProperties);
-
- assertThat(settings.getString("in_file")).isEqualTo("true");
- }
-
-}
*/
package org.sonar.server.platform;
-import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
- private PersistentSettings persistentSettings = new PersistentSettings(dbTester.getDbClient(), new ServerSettingsImpl(new PropertyDefinitions(), new Properties()));
private StartupMetadata metadata = new StartupMetadata("an_id", 123_456_789L);
- private StartupMetadataPersister underTest = new StartupMetadataPersister(metadata, persistentSettings);
+ private StartupMetadataPersister underTest = new StartupMetadataPersister(metadata, dbTester.getDbClient());
@Test
public void persist_metadata_at_startup() {
*/
package org.sonar.server.platform;
-import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
-import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
-
public class StartupMetadataProviderTest {
private static final long A_DATE = 1_500_000_000_000L;
}
private void testLoadingFromDatabase(SonarRuntime runtime, boolean isStartupLeader) {
- PersistentSettings persistentSettings = new PersistentSettings(dbTester.getDbClient(), new ServerSettingsImpl(new PropertyDefinitions(), new Properties()));
- new StartupMetadataPersister(new StartupMetadata(AN_ID, A_DATE), persistentSettings).start();
+ new StartupMetadataPersister(new StartupMetadata(AN_ID, A_DATE), dbTester.getDbClient()).start();
cluster.setStartupLeader(isStartupLeader);
StartupMetadata metadata = underTest.provide(uuidFactory, system, runtime, cluster, dbTester.getDbClient());
import org.junit.rules.ExpectedException;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.core.config.CorePropertyDefinitions;
import static org.assertj.core.api.Assertions.assertThat;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new Settings(new PropertyDefinitions(CorePropertyDefinitions.all()));
+ private Settings settings = new MapSettings(new PropertyDefinitions(CorePropertyDefinitions.all()));
@Test
public void use_default_context_path() {
import org.junit.rules.ExpectedException;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
@Rule
public ExpectedException expectedException = ExpectedException.none();
- private Settings settings = new Settings(new PropertyDefinitions(ClusterProperties.definitions()));
+ private Settings settings = new MapSettings(new PropertyDefinitions(ClusterProperties.definitions()));
@Test
public void cluster_is_disabled_by_default() {
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.database.DatabaseProperties;
-import org.sonar.server.platform.db.EmbeddedDatabase;
-import org.sonar.server.platform.db.EmbeddedDatabaseFactory;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
public class EmbeddedDatabaseFactoryTest {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
@Test
public void should_start_and_stop_tcp_h2_database() {
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.Timeout;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.process.NetworkUtils;
-import org.sonar.server.platform.db.EmbeddedDatabase;
import static junit.framework.Assert.fail;
import static org.sonar.api.database.DatabaseProperties.PROP_EMBEDDED_PORT;
@Test
public void start_fails_with_IAE_if_property_Data_Path_is_not_set() {
- EmbeddedDatabase underTest = new EmbeddedDatabase(new Settings());
+ EmbeddedDatabase underTest = new EmbeddedDatabase(new MapSettings());
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Missing property " + PATH_DATA);
@Test
public void start_fails_with_IAE_if_property_Data_Path_is_empty() {
- EmbeddedDatabase underTest = new EmbeddedDatabase(new Settings()
+ EmbeddedDatabase underTest = new EmbeddedDatabase(new MapSettings()
.setProperty(PATH_DATA, ""));
expectedException.expect(IllegalArgumentException.class);
@Test
public void start_fails_with_IAE_if_JDBC_URL_settings_is_not_set() throws IOException {
- EmbeddedDatabase underTest = new EmbeddedDatabase(new Settings()
+ EmbeddedDatabase underTest = new EmbeddedDatabase(new MapSettings()
.setProperty(PATH_DATA, temporaryFolder.newFolder().getAbsolutePath()));
expectedException.expect(IllegalArgumentException.class);
@Test
public void start_fails_with_IAE_if_embedded_port_settings_is_not_set() throws IOException {
- EmbeddedDatabase underTest = new EmbeddedDatabase(new Settings()
+ EmbeddedDatabase underTest = new EmbeddedDatabase(new MapSettings()
.setProperty(PATH_DATA, temporaryFolder.newFolder().getAbsolutePath())
.setProperty(PROP_URL, "jdbc url"));
@Test
public void start_ignores_URL_to_create_database_and_uses_default_username_and_password_when_then_are_not_set() throws IOException {
int port = NetworkUtils.freePort();
- underTest = new EmbeddedDatabase(new Settings()
+ underTest = new EmbeddedDatabase(new MapSettings()
.setProperty(PATH_DATA, temporaryFolder.newFolder().getAbsolutePath())
.setProperty(PROP_URL, "jdbc url")
.setProperty(PROP_EMBEDDED_PORT, "" + port));
@Test
public void start_creates_db_with_specified_user_and_password() throws IOException {
int port = NetworkUtils.freePort();
- underTest = new EmbeddedDatabase(new Settings()
+ underTest = new EmbeddedDatabase(new MapSettings()
.setProperty(PATH_DATA, temporaryFolder.newFolder().getAbsolutePath())
.setProperty(PROP_URL, "jdbc url")
.setProperty(PROP_EMBEDDED_PORT, "" + port)
@Test
public void start_supports_in_memory_H2_JDBC_URL() throws IOException {
int port = NetworkUtils.freePort();
- underTest = new EmbeddedDatabase(new Settings()
+ underTest = new EmbeddedDatabase(new MapSettings()
.setProperty(PATH_DATA, temporaryFolder.newFolder().getAbsolutePath())
.setProperty(PROP_URL, "jdbc:h2:mem:sonar")
.setProperty(PROP_EMBEDDED_PORT, "" + port)
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.NewIndex;
import org.sonar.server.issue.index.IssueIndexDefinition;
public class EsMonitorTest {
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()));
EsMonitor underTest = new EsMonitor(esTester.client());
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
private static final String PASSWORD_PROPERTY = "sonar.password";
PropertyDefinitions defs = new PropertyDefinitions(PropertyDefinition.builder(PASSWORD_PROPERTY).type(PropertyType.PASSWORD).build());
- Settings settings = new Settings(defs);
+ Settings settings = new MapSettings(defs);
SettingsMonitor underTest = new SettingsMonitor(settings);
@Test
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.platform.Server;
import org.sonar.api.security.SecurityRealm;
import org.sonar.api.utils.log.LoggerLevel;
@Rule
public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
Server server = mock(Server.class);
ServerIdLoader serverIdLoader = mock(ServerIdLoader.class, RETURNS_DEEP_STUBS);
ServerLogging serverLogging = mock(ServerLogging.class);
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.web.UserRole;
@Rule
public LogTester logTester = new LogTester();
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
private Platform platform = mock(Platform.class);
private ProcessCommandWrapper processCommandWrapper = mock(ProcessCommandWrapper.class);
private RestartFlagHolder restartFlagHolder = mock(RestartFlagHolder.class);
import java.nio.charset.StandardCharsets;
import org.junit.Before;
import org.junit.Test;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
import org.sonar.api.utils.SonarException;
import org.sonar.api.utils.UriReader;
public class UpdateCenterClientTest {
- static final String BASE_URL = "http://update.sonarsource.org";
- UriReader reader;
- Settings settings;
-
- UpdateCenterClient underTest;
+ private static final String BASE_URL = "http://update.sonarsource.org";
+ private UriReader reader = mock(UriReader.class);
+ private Settings settings = new MapSettings();
+ private UpdateCenterClient underTest;
@Before
public void startServer() throws Exception {
reader = mock(UriReader.class);
- settings = new Settings()
- .setProperty(UpdateCenterClient.URL_PROPERTY, BASE_URL)
- .setProperty(UpdateCenterClient.ACTIVATION_PROPERTY, true);
+ settings.setProperty(UpdateCenterClient.URL_PROPERTY, BASE_URL);
+ settings.setProperty(UpdateCenterClient.ACTIVATION_PROPERTY, true);
underTest = new UpdateCenterClient(reader, settings);
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = new EsTester(new IssueIndexDefinition(new Settings()),
- new TestIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new IssueIndexDefinition(new MapSettings()),
+ new TestIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
@Rule
public EsTester es = new EsTester(
- new IssueIndexDefinition(new Settings()),
- new TestIndexDefinition(new Settings()));
+ new IssueIndexDefinition(new MapSettings()),
+ new TestIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
-import org.sonar.api.config.Settings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
PropertiesDao propertiesDao = mock(PropertiesDao.class);
ComponentDao componentDao = mock(ComponentDao.class);
MetricFinder metricFinder = mock(MetricFinder.class);
- Settings settings = new Settings();
QualityGates underTest;
@Before
public void initialize() {
- settings.clear();
-
when(dbClient.openSession(false)).thenReturn(dbSession);
when(dbClient.qualityGateDao()).thenReturn(dao);
when(dbClient.gateConditionDao()).thenReturn(conditionDao);
when(componentDao.selectOrFailById(eq(dbSession), anyLong())).thenReturn(newProjectDto(PROJECT_UUID).setId(1L).setKey(PROJECT_KEY));
- underTest = new QualityGates(dbClient, metricFinder, userSessionRule, settings);
+ underTest = new QualityGates(dbClient, metricFinder, userSessionRule);
userSessionRule.set(authorizedProfileAdminUserSession);
}
}
@Test
- public void should_select_default_qgate_and_update_settings() {
+ public void should_select_default_qgate() {
long defaultId = QUALITY_GATE_ID;
String defaultName = "Default Name";
when(dao.selectById(defaultId)).thenReturn(new QualityGateDto().setId(defaultId).setName(defaultName));
assertThat(propertyCaptor.getValue().getKey()).isEqualTo("sonar.qualitygate");
assertThat(propertyCaptor.getValue().getValue()).isEqualTo("42");
- assertThat(settings.getLong("sonar.qualitygate")).isEqualTo(42);
- }
-
- @Test
- public void should_unset_default_qgate_and_unset_in_settings() {
- settings.setProperty("sonar.qualitygate", 42l);
-
- underTest.setDefault(null);
-
- verify(propertiesDao).deleteGlobalProperty("sonar.qualitygate");
- assertThat(settings.hasKey("sonar.qualitygate")).isFalse();
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.measures.MetricFinder;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
DbSession dbSession = db.getSession();
ComponentDbTester componentDb = new ComponentDbTester(db);
- QualityGates qualityGates = new QualityGates(dbClient, mock(MetricFinder.class), userSession, mock(Settings.class));
+ QualityGates qualityGates = new QualityGates(dbClient, mock(MetricFinder.class), userSession);
WsActionTester ws;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
import org.sonar.api.measures.MetricFinder;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
private WsActionTester ws = new WsActionTester(
new GetByProjectAction(userSession, dbClient, new ComponentFinder(dbClient),
- new QualityGates(dbClient, mock(MetricFinder.class), mock(UserSession.class), mock(Settings.class))));
+ new QualityGates(dbClient, mock(MetricFinder.class), mock(UserSession.class))));
@Test
public void json_example() {
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.rule.RuleTesting;
private static final String QUALITY_PROFILE_KEY2 = "qp2";
@Rule
- public EsTester tester = new EsTester(new RuleIndexDefinition(new Settings()));
+ public EsTester tester = new EsTester(new RuleIndexDefinition(new MapSettings()));
ActiveRuleIndex index;
ActiveRuleIndexer activeRuleIndexer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.utils.System2;
static final String QUALITY_PROFILE_KEY2 = "qp2";
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.DateUtils;
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester esTester = new EsTester(new ActivityIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new ActivityIndexDefinition(new MapSettings()));
private DbClient db = dbTester.getDbClient();
private DbSession dbSession = dbTester.getSession();
import java.util.List;
import org.junit.Before;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
public DbTester dbTester = DbTester.create(system);
@org.junit.Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
RuleActivator ruleActivator = mock(RuleActivator.class);
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.process.ProcessProperties;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.IndexDefinition;
public class RuleIndexDefinitionTest {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
RuleIndexDefinition underTest = new RuleIndexDefinition(settings);
@Rule
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
static final String QUALITY_PROFILE_KEY2 = "qp2";
@Rule
- public EsTester tester = new EsTester(new RuleIndexDefinition(new Settings()));
+ public EsTester tester = new EsTester(new RuleIndexDefinition(new MapSettings()));
RuleIndex index;
RuleIndexer ruleIndexer;
import com.google.common.collect.Iterators;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
public class RuleIndexerTest {
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.Rule;
+import org.junit.Test;
+import org.sonar.api.utils.System2;
+import org.sonar.db.DbTester;
+import org.sonar.db.property.PropertyDto;
+import org.sonar.server.setting.DatabaseSettingLoader;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.data.MapEntry.entry;
+
+public class DatabaseSettingLoaderTest {
+
+ private static final String A_KEY = "a_key";
+
+ @Rule
+ public DbTester dbTester = DbTester.create(System2.INSTANCE);
+
+ private DatabaseSettingLoader underTest = new DatabaseSettingLoader(dbTester.getDbClient());
+
+ @Test
+ public void test_load() {
+ insertPropertyIntoDb(A_KEY, "foo");
+
+ assertThat(underTest.load(A_KEY)).isEqualTo("foo");
+ assertThat(underTest.load("missing")).isNull();
+ }
+
+ @Test
+ public void null_value_in_db_is_considered_as_empty_string() {
+ insertPropertyIntoDb(A_KEY, null);
+ assertThat(underTest.load(A_KEY)).isEqualTo("");
+ }
+
+ @Test
+ public void test_empty_value_in_db() {
+ insertPropertyIntoDb(A_KEY, "");
+ assertThat(underTest.load(A_KEY)).isEqualTo("");
+ }
+
+ @Test
+ public void test_loadAll_with_no_properties() {
+ ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
+ underTest.loadAll(map);
+ assertThat(map.build().isEmpty()).isTrue();
+ }
+
+ @Test
+ public void test_loadAll() {
+ insertPropertyIntoDb("foo", "1");
+ insertPropertyIntoDb("bar", "2");
+ ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
+ underTest.loadAll(map);
+ assertThat(map.build()).containsOnly(entry("foo", "1"), entry("bar", "2"));
+ }
+
+ private void insertPropertyIntoDb(String key, String value) {
+ dbTester.getDbClient().propertiesDao().insertProperty(new PropertyDto().setKey(key).setValue(value));
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import org.junit.After;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.sonar.server.setting.DatabaseSettingLoader;
+import org.sonar.server.setting.DatabaseSettingsEnabler;
+import org.sonar.server.setting.ThreadLocalSettings;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+public class DatabaseSettingsEnablerTest {
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ private ThreadLocalSettings settings = mock(ThreadLocalSettings.class);
+ private DatabaseSettingLoader loader = mock(DatabaseSettingLoader.class);
+ private DatabaseSettingsEnabler underTest = new DatabaseSettingsEnabler(settings, loader);
+
+ @After
+ public void tearDown() {
+ underTest.stop();
+ }
+
+ @Test
+ public void change_loader_at_startup() {
+ underTest.start();
+
+ verify(settings).setSettingLoader(loader);
+ }
+}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.Test;
+import org.sonar.server.setting.NopSettingLoader;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class NopSettingLoaderTest {
+
+ private NopSettingLoader underTest = new NopSettingLoader();
+
+ @Test
+ public void do_nothing() {
+ assertThat(underTest.load("foo")).isNull();
+
+ ImmutableMap.Builder<String,String> map = ImmutableMap.builder();
+ underTest.loadAll(map);
+ assertThat(map.build()).isEmpty();
+ }
+}
package org.sonar.server.setting;
import org.junit.Test;
+import org.mockito.Mockito;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
-import org.sonar.db.property.PropertiesDao;
+import org.sonar.ce.settings.ProjectSettingsFactory;
+import org.sonar.db.DbClient;
import org.sonar.db.property.PropertyDto;
import static com.google.common.collect.Lists.newArrayList;
static final String PROJECT_KEY = "PROJECT_KEY";
- Settings settings = new Settings();
- PropertiesDao dao = mock(PropertiesDao.class);
+ Settings settings = new MapSettings();
+ DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS);
- ProjectSettingsFactory underTest = new ProjectSettingsFactory(settings, dao);
+ ProjectSettingsFactory underTest = new ProjectSettingsFactory(settings, dbClient);
@Test
public void return_global_settings() {
@Test
public void return_project_settings() {
- when(dao.selectProjectProperties(PROJECT_KEY)).thenReturn(newArrayList(
+ 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"))
@Test
public void project_settings_override_global_settings() {
settings.setProperty("key", "value");
- when(dao.selectProjectProperties(PROJECT_KEY)).thenReturn(newArrayList(
+ when(dbClient.propertiesDao().selectProjectProperties(PROJECT_KEY)).thenReturn(newArrayList(
new PropertyDto().setKey("key").setValue("value2"))
);
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.setting;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.File;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.CountDownLatch;
+import javax.annotation.Nullable;
+import org.junit.After;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.sonar.api.config.PropertyDefinitions;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.data.MapEntry.entry;
+import static org.mockito.Mockito.mock;
+
+public class ThreadLocalSettingsTest {
+
+ private static final String A_KEY = "a_key";
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ private MapSettingLoader dbSettingLoader = new MapSettingLoader();
+
+ @Rule
+ public TemporaryFolder temp = new TemporaryFolder();
+
+ private ThreadLocalSettings underTest = null;
+
+ @After
+ public void tearDown() {
+ if (underTest != null) {
+ underTest.unload();
+ }
+ }
+
+ @Test
+ public void can_not_add_property_if_no_cache() {
+ underTest = create(Collections.emptyMap());
+
+ underTest.set("foo", "wiz");
+
+ assertThat(underTest.get("foo")).isNotPresent();
+ }
+
+ @Test
+ public void can_not_remove_system_property_if_no_cache() {
+ underTest = create(ImmutableMap.of("foo", "bar"));
+
+ underTest.remove("foo");
+
+ assertThat(underTest.get("foo").get()).isEqualTo("bar");
+ }
+
+ @Test
+ public void add_property_to_cache() {
+ underTest = create(Collections.emptyMap());
+
+ underTest.load();
+ underTest.set("foo", "bar");
+ assertThat(underTest.get("foo").get()).isEqualTo("bar");
+ underTest.unload();
+
+ // no more cache
+ assertThat(underTest.get("foo")).isNotPresent();
+ }
+
+ @Test
+ public void remove_property_from_cache() {
+ underTest = create(Collections.emptyMap());
+
+ underTest.load();
+ underTest.set("foo", "bar");
+ assertThat(underTest.get("foo").get()).isEqualTo("bar");
+ underTest.remove("foo");
+ assertThat(underTest.get("foo")).isNotPresent();
+ underTest.unload();
+
+ // no more cache
+ assertThat(underTest.get("foo")).isNotPresent();
+ }
+
+ @Test
+ public void load_encryption_secret_key_from_system_properties() throws Exception {
+ File secretKey = temp.newFile();
+
+ underTest = create(ImmutableMap.of("foo", "bar", "sonar.secretKeyPath", secretKey.getAbsolutePath()));
+
+ assertThat(underTest.getEncryption().hasSecretKey()).isTrue();
+ }
+
+ @Test
+ public void encryption_secret_key_is_undefined_by_default() {
+ underTest = create(ImmutableMap.of("foo", "bar"));
+
+ assertThat(underTest.getEncryption().hasSecretKey()).isFalse();
+ }
+
+ private ThreadLocalSettings create(Map<String, String> systemProps) {
+ Properties p = new Properties();
+ p.putAll(systemProps);
+ return new ThreadLocalSettings(new PropertyDefinitions(), p, dbSettingLoader);
+ }
+
+ @Test
+ public void load_system_properties() {
+ underTest = create(ImmutableMap.of("foo", "1", "bar", "2"));
+
+ assertThat(underTest.get("foo").get()).isEqualTo("1");
+ assertThat(underTest.get("missing")).isNotPresent();
+ assertThat(underTest.getProperties()).containsOnly(entry("foo", "1"), entry("bar", "2"));
+ }
+
+ @Test
+ public void database_properties_are_not_cached_by_default() {
+ insertPropertyIntoDb("foo", "from db");
+ underTest = create(Collections.emptyMap());
+
+ assertThat(underTest.get("foo").get()).isEqualTo("from db");
+
+ deletePropertyFromDb("foo");
+ // no cache, change is visible immediately
+ assertThat(underTest.get("foo")).isNotPresent();
+ }
+
+ @Test
+ public void system_settings_have_precedence_over_database() {
+ insertPropertyIntoDb("foo", "from db");
+ underTest = create(ImmutableMap.of("foo", "from system"));
+
+ assertThat(underTest.get("foo").get()).isEqualTo("from system");
+ }
+
+ @Test
+ public void getProperties_are_all_properties_with_value() {
+ insertPropertyIntoDb("db", "from db");
+ insertPropertyIntoDb("empty", "");
+ underTest = create(ImmutableMap.of("system", "from system"));
+
+ assertThat(underTest.getProperties()).containsOnly(entry("system", "from system"), entry("db", "from db"), entry("empty", ""));
+ }
+
+ @Test
+ public void load_creates_a_thread_specific_cache() throws InterruptedException {
+ insertPropertyIntoDb(A_KEY, "v1");
+
+ underTest = create(Collections.emptyMap());
+ underTest.load();
+
+ assertThat(underTest.get(A_KEY).get()).isEqualTo("v1");
+
+ deletePropertyFromDb(A_KEY);
+ // the main thread still has "v1" in cache, but not new thread
+ assertThat(underTest.get(A_KEY).get()).isEqualTo("v1");
+ verifyValueInNewThread(underTest, null);
+
+ insertPropertyIntoDb(A_KEY, "v2");
+ // the main thread still has the old value "v1" in cache, but new thread loads "v2"
+ assertThat(underTest.get(A_KEY).get()).isEqualTo("v1");
+ verifyValueInNewThread(underTest, "v2");
+
+ underTest.unload();
+ }
+
+ @Test
+ public void load_throws_ISE_if_load_called_twice_without_unload_in_between() {
+ underTest = create(Collections.emptyMap());
+ underTest.load();
+
+ expectedException.expect(IllegalStateException.class);
+ expectedException.expectMessage("load called twice for thread '" + Thread.currentThread().getName()
+ + "' or state wasn't cleared last time it was used");
+
+ underTest.load();
+ }
+
+ @Test
+ public void keep_in_thread_cache_the_fact_that_a_property_is_not_in_db() {
+ underTest = create(Collections.emptyMap());
+ underTest.load();
+ assertThat(underTest.get(A_KEY)).isNotPresent();
+
+ insertPropertyIntoDb(A_KEY, "bar");
+ // do not execute new SQL request, cache contains the information of missing property
+ assertThat(underTest.get(A_KEY)).isNotPresent();
+
+ underTest.unload();
+ }
+
+ @Test
+ public void change_setting_loader() {
+ underTest = new ThreadLocalSettings(new PropertyDefinitions(), new Properties());
+
+ assertThat(underTest.getSettingLoader()).isNotNull();
+
+ SettingLoader newLoader = mock(SettingLoader.class);
+ underTest.setSettingLoader(newLoader);
+ assertThat(underTest.getSettingLoader()).isSameAs(newLoader);
+ }
+
+ @Test
+ public void cache_db_calls_if_property_is_not_persisted() {
+ underTest = create(Collections.emptyMap());
+ underTest.load();
+ assertThat(underTest.get(A_KEY)).isNotPresent();
+ assertThat(underTest.get(A_KEY)).isNotPresent();
+ underTest.unload();
+ }
+
+ private void insertPropertyIntoDb(String key, @Nullable String value) {
+ dbSettingLoader.put(key, value);
+ }
+
+ private void deletePropertyFromDb(String key) {
+ dbSettingLoader.remove(key);
+ }
+
+ private void verifyValueInNewThread(ThreadLocalSettings settings, @Nullable String expectedValue) throws InterruptedException {
+ CacheCaptorThread captor = new CacheCaptorThread();
+ captor.verifyValue(settings, expectedValue);
+ }
+
+ private class CacheCaptorThread extends Thread {
+ private final CountDownLatch latch = new CountDownLatch(1);
+ private ThreadLocalSettings settings;
+ private String value;
+
+ void verifyValue(ThreadLocalSettings settings, @Nullable String expectedValue) throws InterruptedException {
+ this.settings = settings;
+ this.start();
+ this.latch.await(5, SECONDS);
+ assertThat(value).isEqualTo(expectedValue);
+ }
+
+ @Override
+ public void run() {
+ try {
+ settings.load();
+ value = settings.get(A_KEY).orElse(null);
+ latch.countDown();
+ } finally {
+ settings.unload();
+ }
+ }
+ }
+
+ private static class MapSettingLoader implements SettingLoader {
+ private final Map<String, String> map = new HashMap<>();
+
+ public MapSettingLoader put(String key, String value) {
+ map.put(key, value);
+ return this;
+ }
+
+ public MapSettingLoader remove(String key) {
+ map.remove(key);
+ return this;
+ }
+
+ @Override
+ public String load(String key) {
+ return map.get(key);
+ }
+
+ @Override
+ public void loadAll(ImmutableMap.Builder<String, String> appendTo) {
+ appendTo.putAll(map);
+ }
+ }
+}
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.LogTester;
public DbTester tester = DbTester.create(system2);
@Rule
- public EsTester esTester = new EsTester(new RuleIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new RuleIndexDefinition(new MapSettings()));
@Rule
public LogTester logTester = new LogTester();
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
public class TestIndexTest {
@Rule
- public EsTester es = new EsTester(new TestIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings()));
TestIndex underTest = new TestIndex(es.client());
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.protobuf.DbFileSources;
public class TestIndexerTest {
@Rule
- public EsTester es = new EsTester(new TestIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings()));
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
public class ListActionTest {
@Rule
- public EsTester es = new EsTester(new TestIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new TestIndexDefinition(new MapSettings()));
@Rule
public ExpectedException expectedException = ExpectedException.none();
protected void after() {
this.currentUserSession = null;
if (serverTester != null) {
- serverTester.get(ThreadLocalUserSession.class).remove();
+ serverTester.get(ThreadLocalUserSession.class).unload();
}
}
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypeTree;
import org.sonar.api.resources.ResourceTypes;
@Test
public void empty_call() throws Exception {
- wsTester = new WsTester(new NavigationWs(new GlobalNavigationAction(activeDashboardDao, new Views(userSessionRule), new Settings(), new ResourceTypes(), userSessionRule)));
+ wsTester = new WsTester(new NavigationWs(new GlobalNavigationAction(activeDashboardDao, new Views(userSessionRule), new MapSettings(), new ResourceTypes(), userSessionRule)));
wsTester.newGetRequest("api/navigation", "global").execute().assertJson(getClass(), "empty.json");
}
.addRelations("PAL", "LAP")
.build()
});
- wsTester = new WsTester(new NavigationWs(new GlobalNavigationAction(activeDashboardDao, new Views(userSessionRule), new Settings(), resourceTypes, userSessionRule)));
+ wsTester = new WsTester(new NavigationWs(new GlobalNavigationAction(activeDashboardDao, new Views(userSessionRule), new MapSettings(), resourceTypes, userSessionRule)));
wsTester.newGetRequest("api/navigation", "global").execute().assertJson(getClass(), "with_qualifiers.json");
}
@Test
public void only_logo() throws Exception {
wsTester = new WsTester(new NavigationWs(new GlobalNavigationAction(activeDashboardDao, new Views(userSessionRule),
- new Settings()
+ new MapSettings()
.setProperty("sonar.lf.logoUrl", "http://some-server.tld/logo.png")
.setProperty("sonar.lf.logoWidthPx", "123"),
new ResourceTypes(), userSessionRule)));
session.commit();
- Settings settings = new Settings()
+ Settings settings = new MapSettings()
.setProperty("sonar.lf.logoUrl", "http://some-server.tld/logo.png")
.setProperty("sonar.lf.logoWidthPx", "123");
wsTester = new WsTester(new NavigationWs(new GlobalNavigationAction(activeDashboardDao, createViews(), settings, new ResourceTypes(), userSessionRule)));
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.i18n.I18n;
import org.sonar.api.web.NavigationSection;
import org.sonar.api.web.Page;
@Before
public void before() {
- settings = new Settings();
+ settings = new MapSettings();
i18n = mock(I18n.class);
when(i18n.message(any(Locale.class), anyString(), anyString())).thenAnswer(new Answer<String>() {
@Override
import org.junit.Test;
import org.sonar.api.CoreProperties;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.config.Settings;
import org.sonar.api.security.LoginPasswordAuthenticator;
import org.sonar.api.security.SecurityRealm;
public class SecurityRealmFactoryTest {
- Settings settings = new Settings();
+ private Settings 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, new SecurityRealm[] {realm});
factory.start();
assertThat(factory.getRealm()).isSameAs(realm);
assertThat(factory.hasExternalAuthentication()).isTrue();
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, 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},
- new LoginPasswordAuthenticator[]{authenticator});
+ SecurityRealmFactory factory = new SecurityRealmFactory(settings, new SecurityRealm[] {realm},
+ new LoginPasswordAuthenticator[] {authenticator});
assertThat(factory.getRealm()).isSameAs(realm);
}
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, 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, new SecurityRealm[] {realm}).start();
fail();
} catch (SonarException e) {
assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
*/
package org.sonar.server.user;
-import static org.assertj.core.api.Assertions.assertThat;
-
import java.util.Locale;
import org.junit.After;
import org.junit.Before;
import org.sonar.server.tester.AnonymousMockUserSession;
import org.sonar.server.tester.MockUserSession;
+import static org.assertj.core.api.Assertions.assertThat;
+
public class ThreadLocalUserSessionTest {
ThreadLocalUserSession threadLocalUserSession = new ThreadLocalUserSession();
@Before
public void setUp() {
// for test isolation
- threadLocalUserSession.remove();
+ threadLocalUserSession.unload();
}
@After
public void tearDown() {
// clean up for next test
- threadLocalUserSession.remove();
+ threadLocalUserSession.unload();
}
@Test
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
-import org.sonar.core.platform.ComponentContainer;
+import org.mockito.Mockito;
import org.sonar.server.authentication.UserSessionInitializer;
import org.sonar.server.platform.Platform;
+import org.sonar.server.setting.ThreadLocalSettings;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
public class UserSessionFilterTest {
private UserSessionInitializer userSessionInitializer = mock(UserSessionInitializer.class);
- private Platform platform = mock(Platform.class);
- private ComponentContainer componentContainer = mock(ComponentContainer.class);
+ private Platform platform = mock(Platform.class, Mockito.RETURNS_DEEP_STUBS);
private HttpServletRequest request = mock(HttpServletRequest.class);
private HttpServletResponse response = mock(HttpServletResponse.class);
private FilterChain chain = mock(FilterChain.class);
-
+ private ThreadLocalSettings settings = mock(ThreadLocalSettings.class);
private UserSessionFilter underTest = new UserSessionFilter(platform);
@Before
public void setUp() {
- when(platform.getContainer()).thenReturn(componentContainer);
+ when(platform.getContainer().getComponentByType(ThreadLocalSettings.class)).thenReturn(settings);
}
@Test
public void cleanup_user_session_after_request_handling() throws IOException, ServletException {
- when(componentContainer.getComponentByType(UserSessionInitializer.class)).thenReturn(userSessionInitializer);
+ when(platform.getContainer().getComponentByType(UserSessionInitializer.class)).thenReturn(userSessionInitializer);
when(userSessionInitializer.initUserSession(request, response)).thenReturn(true);
underTest.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
verify(userSessionInitializer).initUserSession(request, response);
- verify(userSessionInitializer).removeUserSession();
}
@Test
public void stop_when_user_session_return_false() throws Exception {
- when(componentContainer.getComponentByType(UserSessionInitializer.class)).thenReturn(userSessionInitializer);
+ when(platform.getContainer().getComponentByType(UserSessionInitializer.class)).thenReturn(userSessionInitializer);
when(userSessionInitializer.initUserSession(request, response)).thenReturn(false);
underTest.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
verify(userSessionInitializer).initUserSession(request, response);
- verify(userSessionInitializer).removeUserSession();
}
@Test
public void does_nothing_when_not_initialized() throws Exception {
+ when(platform.getContainer().getComponentByType(UserSessionInitializer.class)).thenReturn(null);
+
underTest.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
*/
package org.sonar.server.user;
-import static com.google.common.collect.Lists.newArrayList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.data.MapEntry.entry;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.sonar.api.CoreProperties.CORE_DEFAULT_GROUP;
-import static org.sonar.db.user.UserTesting.newDisabledUser;
-import static org.sonar.db.user.UserTesting.newUserDto;
-
import com.google.common.base.Strings;
import java.util.List;
import org.elasticsearch.search.SearchHit;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.platform.NewUserHandler;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.server.user.index.UserIndexer;
import org.sonar.server.util.Validation;
+import static com.google.common.collect.Lists.newArrayList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.data.MapEntry.entry;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.sonar.api.CoreProperties.CORE_DEFAULT_GROUP;
+import static org.sonar.db.user.UserTesting.newDisabledUser;
+import static org.sonar.db.user.UserTesting.newUserDto;
+
public class UserUpdaterTest {
static final long NOW = 1418215735482L;
static final String DEFAULT_LOGIN = "marius";
@Rule
- public EsTester es = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester es = new EsTester(new UserIndexDefinition(new MapSettings()));
System2 system2 = mock(System2.class);
ArgumentCaptor<NewUserHandler.Context> newUserHandler = ArgumentCaptor.forClass(NewUserHandler.Context.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
UserDao userDao = dbClient.userDao();
GroupDao groupDao = dbClient.groupDao();
GroupMembershipFinder groupMembershipFinder = new GroupMembershipFinder(userDao, dbClient.groupMembershipDao());
package org.sonar.server.user.index;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.NewIndex;
@Test
public void define() {
- UserIndexDefinition def = new UserIndexDefinition(new Settings());
+ UserIndexDefinition def = new UserIndexDefinition(new MapSettings());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
private static final long DATE_2 = 1_500_000_000_001L;
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
private UserIndex index;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
@Test
public void index_nothing() {
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.permission.GlobalPermissions;
public class ChangePasswordActionTest {
- static final Settings settings = new Settings().setProperty("sonar.defaultGroup", "sonar-users");
+ static final Settings settings = new MapSettings().setProperty("sonar.defaultGroup", "sonar-users");
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.i18n.I18n;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
public class CreateActionTest {
- private static final Settings settings = new Settings().setProperty("sonar.defaultGroup", "sonar-users");
+ private static final Settings settings = new MapSettings().setProperty("sonar.defaultGroup", "sonar-users");
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.permission.GlobalPermissions;
public class DeactivateActionTest {
- static final Settings settings = new Settings();
+ static final Settings settings = new MapSettings();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
import com.google.common.collect.Lists;
import java.util.List;
-import org.junit.Before;
-import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.core.permission.GlobalPermissions;
public class SearchActionTest {
@Rule
- public EsTester esTester = new EsTester(new UserIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new UserIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.permission.GlobalPermissions;
public class UpdateActionTest {
- static final Settings settings = new Settings().setProperty("sonar.defaultGroup", "sonar-users");
+ static final Settings settings = new MapSettings().setProperty("sonar.defaultGroup", "sonar-users");
System2 system2 = new System2();
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.permission.GlobalPermissions;
permissionTemplateDao = dbClient.permissionTemplateDao();
dbSession = db.getSession();
- Settings settings = new Settings().setProperty(CoreProperties.CORE_DEFAULT_GROUP, CoreProperties.CORE_DEFAULT_GROUP_DEFAULT_VALUE);
+ Settings settings = new MapSettings().setProperty(CoreProperties.CORE_DEFAULT_GROUP, CoreProperties.CORE_DEFAULT_GROUP_DEFAULT_VALUE);
GroupDto defaultGroup = groupDao.insert(dbSession, new GroupDto().setName(CoreProperties.CORE_DEFAULT_GROUP_DEFAULT_VALUE));
defaultGroupId = defaultGroup.getId();
dbSession.commit();
package org.sonar.server.view.index;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.NewIndex;
@Test
public void define() {
- ViewIndexDefinition def = new ViewIndexDefinition(new Settings());
+ ViewIndexDefinition def = new ViewIndexDefinition(new MapSettings());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.server.es.EsTester;
import static com.google.common.collect.Lists.newArrayList;
public class ViewIndexTest {
@Rule
- public EsTester esTester = new EsTester(new ViewIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new ViewIndexDefinition(new MapSettings()));
ViewIndex index = new ViewIndex(esTester.client());
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester esTester = new EsTester(new IssueIndexDefinition(new Settings()), new ViewIndexDefinition(new Settings()));
+ public EsTester esTester = new EsTester(new IssueIndexDefinition(new MapSettings()), new ViewIndexDefinition(new MapSettings()));
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.i18n.I18n;
import static org.mockito.Matchers.anyString;
static int PERIOD_INDEX = 1;
@Rule
public ExpectedException thrown = ExpectedException.none();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
I18n i18n = mock(I18n.class);
Periods periods = new Periods(settings, i18n);
import org.simpleframework.http.core.Container;
import org.simpleframework.transport.connect.SocketConnection;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.SonarException;
public void describeTo(Description arg0) {
}
});
- DefaultHttpDownloader downloader = new DefaultHttpDownloader(new Settings(), 10, 50000);
+ DefaultHttpDownloader downloader = new DefaultHttpDownloader(new MapSettings(), 10, 50000);
downloader.openStream(new URI(url));
}
@Test
public void downloadBytes() throws URISyntaxException {
- byte[] bytes = new DefaultHttpDownloader(new Settings()).readBytes(new URI(baseUrl));
+ byte[] bytes = new DefaultHttpDownloader(new MapSettings()).readBytes(new URI(baseUrl));
assertThat(bytes.length).isGreaterThan(10);
}
@Test
public void readString() throws URISyntaxException {
- String text = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl), StandardCharsets.UTF_8);
+ String text = new DefaultHttpDownloader(new MapSettings()).readString(new URI(baseUrl), StandardCharsets.UTF_8);
assertThat(text.length()).isGreaterThan(10);
}
@Test
public void readGzipString() throws URISyntaxException {
- String text = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl + "/gzip/"), StandardCharsets.UTF_8);
+ String text = new DefaultHttpDownloader(new MapSettings()).readString(new URI(baseUrl + "/gzip/"), StandardCharsets.UTF_8);
assertThat(text).isEqualTo("GZIP response");
}
@Test
public void readStringWithDefaultTimeout() throws URISyntaxException {
- String text = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl + "/timeout/"), StandardCharsets.UTF_8);
+ String text = new DefaultHttpDownloader(new MapSettings()).readString(new URI(baseUrl + "/timeout/"), StandardCharsets.UTF_8);
assertThat(text.length()).isGreaterThan(10);
}
public void describeTo(Description arg0) {
}
});
- new DefaultHttpDownloader(new Settings(), 50).readString(new URI(baseUrl + "/timeout/"), StandardCharsets.UTF_8);
+ new DefaultHttpDownloader(new MapSettings(), 50).readString(new URI(baseUrl + "/timeout/"), StandardCharsets.UTF_8);
}
@Test
File toDir = temporaryFolder.newFolder();
File toFile = new File(toDir, "downloadToFile.txt");
- new DefaultHttpDownloader(new Settings()).download(new URI(baseUrl), toFile);
+ new DefaultHttpDownloader(new MapSettings()).download(new URI(baseUrl), toFile);
assertThat(toFile).exists();
assertThat(toFile.length()).isGreaterThan(10l);
}
try {
int port = new InetSocketAddress("localhost", 0).getPort();
- new DefaultHttpDownloader(new Settings()).download(new URI("http://localhost:" + port), toFile);
+ new DefaultHttpDownloader(new MapSettings()).download(new URI("http://localhost:" + port), toFile);
} catch (SonarException e) {
assertThat(toFile).doesNotExist();
}
Server server = mock(Server.class);
when(server.getVersion()).thenReturn("2.2");
- InputStream stream = new DefaultHttpDownloader(server, new Settings()).openStream(new URI(baseUrl));
+ InputStream stream = new DefaultHttpDownloader(server, new MapSettings()).openStream(new URI(baseUrl));
Properties props = new Properties();
props.load(stream);
stream.close();
@Test
public void followRedirect() throws URISyntaxException {
- String content = new DefaultHttpDownloader(new Settings()).readString(new URI(baseUrl + "/redirect/"), StandardCharsets.UTF_8);
+ String content = new DefaultHttpDownloader(new MapSettings()).readString(new URI(baseUrl + "/redirect/"), StandardCharsets.UTF_8);
assertThat(content).contains("agent");
}
@Test
public void supported_schemes() {
- assertThat(new DefaultHttpDownloader(new Settings()).getSupportedSchemes()).contains("http");
+ assertThat(new DefaultHttpDownloader(new MapSettings()).getSupportedSchemes()).contains("http");
}
@Test
public void uri_description() throws URISyntaxException {
- String description = new DefaultHttpDownloader(new Settings()).description(new URI("http://sonarsource.org"));
+ String description = new DefaultHttpDownloader(new MapSettings()).description(new URI("http://sonarsource.org"));
assertThat(description).matches("http://sonarsource.org \\(.*\\)");
}
@Test
public void configure_http_and_https_proxies() {
DefaultHttpDownloader.SystemFacade system = mock(DefaultHttpDownloader.SystemFacade.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("http.proxyHost", "1.2.3.4");
settings.setProperty("http.proxyPort", "80");
settings.setProperty("https.proxyHost", "5.6.7.8");
@Test
public void https_defaults_are_http_properties() {
DefaultHttpDownloader.SystemFacade system = mock(DefaultHttpDownloader.SystemFacade.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("http.proxyHost", "1.2.3.4");
settings.setProperty("http.proxyPort", "80");
@Test
public void configure_http_proxy_credentials() {
DefaultHttpDownloader.SystemFacade system = mock(DefaultHttpDownloader.SystemFacade.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("https.proxyHost", "1.2.3.4");
settings.setProperty("http.proxyUser", "the_login");
settings.setProperty("http.proxyPassword", "the_passwd");
@Test
public void no_http_proxy_settings_by_default() {
DefaultHttpDownloader.SystemFacade system = mock(DefaultHttpDownloader.SystemFacade.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
new DefaultHttpDownloader.BaseHttpDownloader(system, settings, null);
verify(system, never()).setProperty(eq("http.proxyHost"), anyString());
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.db.dialect.PostgreSql;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void shouldLoadDefaultValues() {
- DefaultDatabase db = new DefaultDatabase(new Settings());
+ DefaultDatabase db = new DefaultDatabase(new MapSettings());
db.initSettings();
Properties props = db.getProperties();
@Test
public void shouldCompleteProperties() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
DefaultDatabase db = new DefaultDatabase(settings) {
@Override
@Test
public void shouldStart() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "jdbc:h2:mem:sonar");
settings.setProperty("sonar.jdbc.driverClassName", "org.h2.Driver");
settings.setProperty("sonar.jdbc.username", "sonar");
@Test
public void shouldGuessDialectFromUrl() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "jdbc:postgresql://localhost/sonar");
DefaultDatabase database = new DefaultDatabase(settings);
@Test
public void shouldGuessDefaultDriver() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "jdbc:postgresql://localhost/sonar");
DefaultDatabase database = new DefaultDatabase(settings);
*/
package org.sonar.db;
-import com.google.common.collect.Maps;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
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.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.db.dialect.H2;
private TestDb(@Nullable String schemaPath) {
if (db == null) {
- Settings settings = new Settings().setProperties(Maps.fromProperties(System.getProperties()));
+ Settings settings = new MapSettings().addProperties(System.getProperties());
if (settings.hasKey("orchestrator.configUrl")) {
loadOrchestratorSettings(settings);
}
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
DbClient dbClient = dbTester.getDbClient();
DbSession session = dbTester.getSession();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
PermissionRepository underTest = new PermissionRepository(dbTester.getDbClient(), settings);
@Before
import java.util.Date;
import org.junit.Test;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
@Test
public void do_not_delete_directory_by_default() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(PurgeConstants.PROPERTY_CLEAN_DIRECTORY, false);
settings.setProperty(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES, 5);
Date now = new Date();
@Test
public void delete_directory_if_in_settings() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(PurgeConstants.PROPERTY_CLEAN_DIRECTORY, true);
PurgeConfiguration underTest = PurgeConfiguration.newDefaultPurgeConfiguration(settings, new IdUuidPair(42L, "any-uuid"), Collections.emptyList());
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.internal.ApiVersion;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.measures.Metric;
private boolean cancelled;
private SensorContextTester(Path moduleBaseDir) {
- this.settings = new Settings();
+ this.settings = new MapSettings();
this.fs = new DefaultFileSystem(moduleBaseDir);
this.activeRules = new ActiveRulesBuilder().build();
this.sensorStorage = new InMemorySensorStorage();
public Encryption(@Nullable String pathToSecretKey) {
aesCipher = new AesCipher(pathToSecretKey);
ciphers = ImmutableMap.of(
- BASE64_ALGORITHM, new Base64Cipher(),
- AES_ALGORITHM, aesCipher);
+ BASE64_ALGORITHM, new Base64Cipher(),
+ AES_ALGORITHM, aesCipher);
}
public void setPathToSecretKey(@Nullable String pathToSecretKey) {
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.api.config;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * In-memory map-based implementation of {@link Settings}. It must be used
+ * <b>only for unit tests</b>. This is not the implementation
+ * deployed at runtime, so non-test code must never cast
+ * {@link Settings} to {@link MapSettings}.
+ *
+ * @since 6.1
+ */
+public class MapSettings extends Settings {
+
+ private final Map<String, String> props = new HashMap<>();
+
+ public MapSettings() {
+ super(new PropertyDefinitions(), new Encryption(null));
+ }
+
+ public MapSettings(PropertyDefinitions definitions) {
+ super(definitions, new Encryption(null));
+ }
+
+ @Override
+ protected Optional<String> get(String key) {
+ return Optional.ofNullable(props.get(key));
+ }
+
+ @Override
+ protected void set(String key, String value) {
+ props.put(key, value);
+ }
+
+ @Override
+ protected void remove(String key) {
+ props.remove(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return ImmutableMap.copyOf(props);
+ }
+
+ public MapSettings clear() {
+ props.clear();
+ return this;
+ }
+}
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Properties;
+import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.ArrayUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.DateUtils;
+import static java.util.Objects.requireNonNull;
+import static org.apache.commons.lang.StringUtils.trim;
+
/**
+ *
* Project settings on batch side, or global settings on server side. This component does not access to database, so
* property changed via setter methods are not persisted.
* <br>
* defaultValue = "A default value",
* name = "My property"),
* })
- * public class MyPlugin extends SonarPlugin {
+ * class MyPlugin extends SonarPlugin {
* </code>
* </pre>
* then you can use:
* <li>If you are using the {@link PropertyDefinition#builder(String)} way like:
* <pre>
* <code>
- * public class MyPlugin extends SonarPlugin {
- * public List getExtensions() {
+ * class MyPlugin extends SonarPlugin {
+ * List getExtensions() {
* return Arrays.asList(
* PropertyDefinition.builder("sonar.myProp").name("My property").defaultValue("A default value").build()
* );
* </pre>
* </li>
* </ul>
- *
+ *
+ * History - this class is abstract since 6.1.
* @since 2.12
*/
@ScannerSide
@ServerSide
@ComputeEngineSide
-public class Settings {
+public abstract class Settings {
- protected Map<String, String> properties;
- protected PropertyDefinitions definitions;
- private Encryption encryption;
+ private final PropertyDefinitions definitions;
+ private final Encryption encryption;
- public Settings() {
- this(new PropertyDefinitions());
+ protected Settings(PropertyDefinitions definitions, Encryption encryption) {
+ this.definitions = requireNonNull(definitions);
+ this.encryption = requireNonNull(encryption);
}
- public Settings(PropertyDefinitions definitions) {
- this.properties = Maps.newHashMap();
- this.definitions = definitions;
- this.encryption = new Encryption(null);
+ protected abstract Optional<String> get(String key);
+
+ protected abstract void set(String key, String value);
+
+ protected abstract void remove(String key);
+
+ /**
+ * Immutable map of the properties that have non-default values.
+ * The default values defined by {@link PropertyDefinitions} are ignored,
+ * so the returned values are not the effective values. Basically only
+ * the non-empty results of {@link #getRawString(String)} are returned.
+ * <p>
+ * Values are not decrypted if they are encrypted with a secret key.
+ * </p>
+ */
+ public abstract Map<String, String> getProperties();
+
+ // FIXME scope to be replaced by "protected" as soon as not used by JRubyFacade
+ public Encryption getEncryption() {
+ return encryption;
}
/**
- * Clone settings. Actions are not propagated to cloned settings.
+ * The value that overrides the default value. It
+ * may be encrypted with a secret key. Use {@link #getString(String)} to get
+ * the effective and decrypted value.
*
- * @since 3.1
+ * @since 6.1
*/
- public Settings(Settings other) {
- this.properties = Maps.newHashMap(other.getProperties());
- this.definitions = other.getDefinitions();
- this.encryption = other.getEncryption();
+ public Optional<String> getRawString(String key) {
+ return get(definitions.validKey(requireNonNull(key)));
}
- public Encryption getEncryption() {
- return encryption;
+ /**
+ * All the property definitions declared by core and plugins.
+ */
+ public PropertyDefinitions getDefinitions() {
+ return definitions;
}
- @CheckForNull
- public String getDefaultValue(String key) {
- return definitions.getDefaultValue(key);
+ /**
+ * The definition related to the specified property. It may
+ * be empty.
+ *
+ * @since 6.1
+ */
+ public Optional<PropertyDefinition> getDefinition(String key) {
+ return Optional.ofNullable(definitions.get(key));
}
+ /**
+ * @return {@code true} if the property has a non-default value, else {@code false}.
+ */
public boolean hasKey(String key) {
- return properties.containsKey(key);
+ return getRawString(key).isPresent();
+ }
+
+ @CheckForNull
+ public String getDefaultValue(String key) {
+ return definitions.getDefaultValue(key);
}
public boolean hasDefaultValue(String key) {
return StringUtils.isNotEmpty(getDefaultValue(key));
}
+ /**
+ * The effective value of the specified property. Can return
+ * {@code null} if the property is not set and has no
+ * defined default value.
+ * <p>
+ * If the property is encrypted with a secret key,
+ * then the returned value is decrypted.
+ * </p>
+ *
+ * @throws IllegalStateException if value is encrypted but fails to be decrypted.
+ */
@CheckForNull
public String getString(String key) {
- String value = getClearString(key);
- if (value != null && encryption.isEncrypted(value)) {
+ String effectiveKey = definitions.validKey(key);
+ Optional<String> value = getRawString(effectiveKey);
+ if (!value.isPresent()) {
+ // default values cannot be encrypted, so return value as-is.
+ return getDefaultValue(effectiveKey);
+ }
+ if (encryption.isEncrypted(value.get())) {
try {
- value = encryption.decrypt(value);
+ return encryption.decrypt(value.get());
} catch (Exception e) {
- throw new IllegalStateException("Fail to decrypt the property " + key + ". Please check your secret key.", e);
+ throw new IllegalStateException("Fail to decrypt the property " + effectiveKey + ". Please check your secret key.", e);
}
}
- return value;
+ return value.get();
}
/**
- * Does not decrypt value.
+ * Effective value as boolean. It is {@code false} if {@link #getString(String)}
+ * does not return {@code "true"}, even if it's not a boolean representation.
+ * @return {@code true} if the effective value is {@code "true"}, else {@code false}.
*/
- @CheckForNull
- protected String getClearString(String key) {
- doOnGetProperties(key);
- String validKey = definitions.validKey(key);
- String value = properties.get(validKey);
- if (value == null) {
- value = getDefaultValue(validKey);
- }
- return value;
- }
-
public boolean getBoolean(String key) {
String value = getString(key);
return StringUtils.isNotEmpty(value) && Boolean.parseBoolean(value);
}
/**
+ * Effective value as int.
* @return the value as int. If the property does not exist and has no default value, then 0 is returned.
*/
public int getInt(String key) {
* </ul>
*/
public String[] getStringArray(String key) {
- PropertyDefinition property = getDefinitions().get(key);
- if ((null != property) && (property.multiValues())) {
+ Optional<PropertyDefinition> def = getDefinition(key);
+ if ((def.isPresent()) && (def.get().multiValues())) {
String value = getString(key);
if (value == null) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
/**
- * Value is splitted and trimmed.
+ * Value is split and trimmed.
*/
public String[] getStringArrayBySeparator(String key, String separator) {
String value = getString(key);
String[] strings = StringUtils.splitByWholeSeparator(value, separator);
String[] result = new String[strings.length];
for (int index = 0; index < strings.length; index++) {
- result[index] = StringUtils.trim(strings[index]);
+ result[index] = trim(strings[index]);
}
return result;
}
return ArrayUtils.EMPTY_STRING_ARRAY;
}
- public List<String> getKeysStartingWith(String prefix) {
- List<String> result = new ArrayList<>();
- for (String key : properties.keySet()) {
- if (StringUtils.startsWith(key, prefix)) {
- result.add(key);
- }
- }
- return result;
- }
-
- public Settings appendProperty(String key, String value) {
- String newValue = properties.get(definitions.validKey(key));
- if (StringUtils.isEmpty(newValue)) {
- newValue = StringUtils.trim(value);
+ public Settings appendProperty(String key, @Nullable String value) {
+ Optional<String> existingValue = getRawString(definitions.validKey(key));
+ String newValue;
+ if (!existingValue.isPresent()) {
+ newValue = trim(value);
} else {
- newValue += "," + StringUtils.trim(value);
+ newValue = existingValue.get() + "," + trim(value);
}
return setProperty(key, newValue);
}
public Settings setProperty(String key, @Nullable String[] values) {
- PropertyDefinition property = getDefinitions().get(key);
- if ((null == property) || (!property.multiValues())) {
+ Optional<PropertyDefinition> def = getDefinition(key);
+ if (!def.isPresent() || (!def.get().multiValues())) {
throw new IllegalStateException("Fail to set multiple values on a single value property " + key);
}
}
String escapedValue = Joiner.on(',').join(escaped);
- text = StringUtils.trim(escapedValue);
+ text = trim(escapedValue);
}
return setProperty(key, text);
}
public Settings setProperty(String key, @Nullable String value) {
String validKey = definitions.validKey(key);
if (value == null) {
- properties.remove(validKey);
- doOnRemoveProperty(validKey);
+ removeProperty(validKey);
+
} else {
- properties.put(validKey, StringUtils.trim(value));
- doOnSetProperty(validKey, value);
+ set(validKey, trim(value));
}
return this;
}
return this;
}
- public Settings setProperties(Map<String, String> props) {
- clear();
- return addProperties(props);
- }
-
public Settings setProperty(String key, @Nullable Date date, boolean includeTime) {
if (date == null) {
return removeProperty(key);
}
public Settings removeProperty(String key) {
- return setProperty(key, (String) null);
- }
-
- public Settings clear() {
- properties.clear();
- doOnClearProperties();
+ remove(key);
return this;
}
- /**
- *
- * @return immutable copy of properties. Encrypted values are kept and not decrypted.
- */
- public Map<String, String> getProperties() {
- return ImmutableMap.copyOf(properties);
- }
-
- public PropertyDefinitions getDefinitions() {
- return definitions;
- }
-
- /**
- * Create empty settings. Definition of available properties is loaded from the given annotated class.
- * This method is usually used by unit tests.
- */
- public static Settings createForComponent(Object component) {
- return new Settings(new PropertyDefinitions(component));
- }
-
- protected void doOnSetProperty(String key, @Nullable String value) {
- // can be overridden
- }
-
- protected void doOnRemoveProperty(String key) {
- // can be overridden
- }
-
- protected void doOnClearProperties() {
- // can be overridden
+ public List<String> getKeysStartingWith(String prefix) {
+ return getProperties().keySet().stream()
+ .filter(key -> StringUtils.startsWith(key, prefix))
+ .collect(Collectors.toList());
}
- protected void doOnGetProperties(String key) {
- // can be overridden
- }
}
*/
package org.sonar.api.batch.bootstrap;
+import java.io.File;
import org.junit.Test;
import org.sonar.api.batch.bootstrap.internal.ProjectBuilderContext;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
-
-import java.io.File;
-
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.hasItem;
public class ProjectBuilderTest {
// this reactor is created and provided by Sonar
final ProjectReactor projectReactor = new ProjectReactor(ProjectDefinition.create());
- ProjectBuilder builder = new ProjectBuilderSample(new Settings());
+ ProjectBuilder builder = new ProjectBuilderSample(new MapSettings());
builder.build(new ProjectBuilderContext(projectReactor));
assertThat(projectReactor.getProjects().size(), is(2));
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
@Test
public void save_no_tokens() {
SensorStorage sensorStorage = mock(SensorStorage.class);
- DefaultCpdTokens tokens = new DefaultCpdTokens(new Settings(), sensorStorage)
+ DefaultCpdTokens tokens = new DefaultCpdTokens(new MapSettings(), sensorStorage)
.onFile(INPUT_FILE);
tokens.save();
@Test
public void save_one_token() {
SensorStorage sensorStorage = mock(SensorStorage.class);
- DefaultCpdTokens tokens = new DefaultCpdTokens(new Settings(), sensorStorage)
+ DefaultCpdTokens tokens = new DefaultCpdTokens(new MapSettings(), sensorStorage)
.onFile(INPUT_FILE)
.addToken(INPUT_FILE.newRange(1, 2, 1, 5), "foo");
@Test
public void handle_exclusions_by_pattern() {
SensorStorage sensorStorage = mock(SensorStorage.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("sonar.cpd.exclusions", "src/Foo.java,another");
DefaultCpdTokens tokens = new DefaultCpdTokens(settings, sensorStorage)
.onFile(INPUT_FILE)
@Test
public void save_many_tokens() {
SensorStorage sensorStorage = mock(SensorStorage.class);
- DefaultCpdTokens tokens = new DefaultCpdTokens(new Settings(), sensorStorage)
+ DefaultCpdTokens tokens = new DefaultCpdTokens(new MapSettings(), sensorStorage)
.onFile(INPUT_FILE)
.addToken(INPUT_FILE.newRange(1, 2, 1, 5), "foo")
.addToken(INPUT_FILE.newRange(1, 6, 1, 10), "bar")
@Test
public void basic_validation() {
SensorStorage sensorStorage = mock(SensorStorage.class);
- DefaultCpdTokens tokens = new DefaultCpdTokens(new Settings(), sensorStorage);
+ DefaultCpdTokens tokens = new DefaultCpdTokens(new MapSettings(), sensorStorage);
try {
tokens.save();
fail("Expected exception");
@Test
public void validate_tokens_order() {
SensorStorage sensorStorage = mock(SensorStorage.class);
- DefaultCpdTokens tokens = new DefaultCpdTokens(new Settings(), sensorStorage)
+ DefaultCpdTokens tokens = new DefaultCpdTokens(new MapSettings(), sensorStorage)
.onFile(INPUT_FILE)
.addToken(INPUT_FILE.newRange(1, 6, 1, 10), "bar");
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.SonarException;
@Test
public void testSettings() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("foo", "bar");
tester.setSettings(settings);
assertThat(tester.settings().getString("foo")).isEqualTo("bar");
*/
package org.sonar.api.config;
-import org.junit.Before;
import org.junit.Test;
import org.sonar.api.CoreProperties;
-import org.sonar.api.config.EmailSettings;
-import org.sonar.api.config.Settings;
import static org.assertj.core.api.Assertions.assertThat;
public class EmailSettingsTest {
- EmailSettings emailSettings;
- @Before
- public void setUp() {
- emailSettings = new EmailSettings(new Settings());
- }
+ private EmailSettings underTest = new EmailSettings(new MapSettings());
@Test
public void should_return_default_values() {
- assertThat(emailSettings.getSmtpHost()).isEqualTo("");
- assertThat(emailSettings.getSmtpPort()).isEqualTo(25);
- assertThat(emailSettings.getSmtpUsername()).isEmpty();
- assertThat(emailSettings.getSmtpPassword()).isEmpty();
- assertThat(emailSettings.getSecureConnection()).isEmpty();
- assertThat(emailSettings.getFrom()).isEqualTo("noreply@nowhere");
- assertThat(emailSettings.getPrefix()).isEqualTo("[SONARQUBE]");
- assertThat(emailSettings.getServerBaseURL()).isEqualTo(CoreProperties.SERVER_BASE_URL_DEFAULT_VALUE);
+ assertThat(underTest.getSmtpHost()).isEqualTo("");
+ assertThat(underTest.getSmtpPort()).isEqualTo(25);
+ assertThat(underTest.getSmtpUsername()).isEmpty();
+ assertThat(underTest.getSmtpPassword()).isEmpty();
+ assertThat(underTest.getSecureConnection()).isEmpty();
+ assertThat(underTest.getFrom()).isEqualTo("noreply@nowhere");
+ assertThat(underTest.getPrefix()).isEqualTo("[SONARQUBE]");
+ assertThat(underTest.getServerBaseURL()).isEqualTo(CoreProperties.SERVER_BASE_URL_DEFAULT_VALUE);
}
}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2016 SonarSource SA
+ * mailto:contact 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.api.config;
+
+import java.util.Date;
+import org.assertj.core.data.Offset;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.sonar.api.Properties;
+import org.sonar.api.Property;
+import org.sonar.api.PropertyType;
+import org.sonar.api.utils.DateUtils;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class MapSettingsTest {
+
+ private PropertyDefinitions definitions;
+
+ @Properties({
+ @Property(key = "hello", name = "Hello", defaultValue = "world"),
+ @Property(key = "date", name = "Date", defaultValue = "2010-05-18"),
+ @Property(key = "datetime", name = "DateTime", defaultValue = "2010-05-18T15:50:45+0100"),
+ @Property(key = "boolean", name = "Boolean", defaultValue = "true"),
+ @Property(key = "falseboolean", name = "False Boolean", defaultValue = "false"),
+ @Property(key = "integer", name = "Integer", defaultValue = "12345"),
+ @Property(key = "array", name = "Array", defaultValue = "one,two,three"),
+ @Property(key = "multi_values", name = "Array", defaultValue = "1,2,3", multiValues = true),
+ @Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET, propertySetKey = "jira"),
+ @Property(key = "newKey", name = "New key", deprecatedKey = "oldKey"),
+ @Property(key = "newKeyWithDefaultValue", name = "New key with default value", deprecatedKey = "oldKeyWithDefaultValue", defaultValue = "default_value"),
+ @Property(key = "new_multi_values", name = "New multi values", defaultValue = "1,2,3", multiValues = true, deprecatedKey = "old_multi_values")
+ })
+ private static class Init {
+ }
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Before
+ public void init_definitions() {
+ definitions = new PropertyDefinitions();
+ definitions.addComponent(Init.class);
+ }
+
+ @Test
+ public void default_values_should_be_loaded_from_definitions() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getDefaultValue("hello")).isEqualTo("world");
+ }
+
+ @Test
+ public void set_property_int() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", 123);
+ assertThat(settings.getInt("foo")).isEqualTo(123);
+ assertThat(settings.getString("foo")).isEqualTo("123");
+ assertThat(settings.getBoolean("foo")).isFalse();
+ }
+
+ @Test
+ public void default_number_values_are_zero() {
+ Settings settings = new MapSettings();
+ assertThat(settings.getInt("foo")).isEqualTo(0);
+ assertThat(settings.getLong("foo")).isEqualTo(0L);
+ }
+
+ @Test
+ public void getInt_value_must_be_valid() {
+ thrown.expect(NumberFormatException.class);
+
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "not a number");
+ settings.getInt("foo");
+ }
+
+ @Test
+ public void all_values_should_be_trimmed_set_property() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", " FOO ");
+ assertThat(settings.getString("foo")).isEqualTo("FOO");
+ }
+
+ @Test
+ public void test_get_default_value() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getDefaultValue("unknown")).isNull();
+ }
+
+ @Test
+ public void test_get_string() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("hello", "Russia");
+ assertThat(settings.getString("hello")).isEqualTo("Russia");
+ }
+
+ @Test
+ public void setProperty_date() {
+ Settings settings = new MapSettings();
+ Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100");
+ settings.setProperty("aDate", date);
+ settings.setProperty("aDateTime", date, true);
+
+ assertThat(settings.getString("aDate")).isEqualTo("2010-05-18");
+ assertThat(settings.getString("aDateTime")).startsWith("2010-05-18T");
+ }
+
+ @Test
+ public void test_get_date() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getDate("unknown")).isNull();
+ assertThat(settings.getDate("date").getDate()).isEqualTo(18);
+ assertThat(settings.getDate("date").getMonth()).isEqualTo(4);
+ }
+
+ @Test
+ public void test_get_date_not_found() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getDate("unknown")).isNull();
+ }
+
+ @Test
+ public void test_get_datetime() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getDateTime("unknown")).isNull();
+ assertThat(settings.getDateTime("datetime").getDate()).isEqualTo(18);
+ assertThat(settings.getDateTime("datetime").getMonth()).isEqualTo(4);
+ assertThat(settings.getDateTime("datetime").getMinutes()).isEqualTo(50);
+ }
+
+ @Test
+ public void test_get_double() {
+ Settings settings = new MapSettings();
+ settings.setProperty("from_double", 3.14159);
+ settings.setProperty("from_string", "3.14159");
+ assertThat(settings.getDouble("from_double")).isEqualTo(3.14159, Offset.offset(0.00001));
+ assertThat(settings.getDouble("from_string")).isEqualTo(3.14159, Offset.offset(0.00001));
+ assertThat(settings.getDouble("unknown")).isNull();
+ }
+
+ @Test
+ public void test_get_float() {
+ Settings settings = new MapSettings();
+ settings.setProperty("from_float", 3.14159f);
+ settings.setProperty("from_string", "3.14159");
+ assertThat(settings.getDouble("from_float")).isEqualTo(3.14159f, Offset.offset(0.00001));
+ assertThat(settings.getDouble("from_string")).isEqualTo(3.14159f, Offset.offset(0.00001));
+ assertThat(settings.getDouble("unknown")).isNull();
+ }
+
+ @Test
+ public void test_get_bad_float() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "bar");
+
+ thrown.expect(IllegalStateException.class);
+ thrown.expectMessage("The property 'foo' is not a float value");
+ settings.getFloat("foo");
+ }
+
+ @Test
+ public void test_get_bad_double() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "bar");
+
+ thrown.expect(IllegalStateException.class);
+ thrown.expectMessage("The property 'foo' is not a double value");
+ settings.getDouble("foo");
+ }
+
+ @Test
+ public void testSetNullFloat() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", (Float) null);
+ assertThat(settings.getFloat("foo")).isNull();
+ }
+
+ @Test
+ public void testSetNullDouble() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", (Double) null);
+ assertThat(settings.getDouble("foo")).isNull();
+ }
+
+ @Test
+ public void getStringArray() {
+ Settings settings = new MapSettings(definitions);
+ String[] array = settings.getStringArray("array");
+ assertThat(array).isEqualTo(new String[] {"one", "two", "three"});
+ }
+
+ @Test
+ public void setStringArray() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("multi_values", new String[] {"A", "B"});
+ String[] array = settings.getStringArray("multi_values");
+ assertThat(array).isEqualTo(new String[] {"A", "B"});
+ }
+
+ @Test
+ public void setStringArrayTrimValues() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("multi_values", new String[] {" A ", " B "});
+ String[] array = settings.getStringArray("multi_values");
+ assertThat(array).isEqualTo(new String[] {"A", "B"});
+ }
+
+ @Test
+ public void setStringArrayEscapeCommas() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("multi_values", new String[] {"A,B", "C,D"});
+ String[] array = settings.getStringArray("multi_values");
+ assertThat(array).isEqualTo(new String[] {"A,B", "C,D"});
+ }
+
+ @Test
+ public void setStringArrayWithEmptyValues() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("multi_values", new String[] {"A,B", "", "C,D"});
+ String[] array = settings.getStringArray("multi_values");
+ assertThat(array).isEqualTo(new String[] {"A,B", "", "C,D"});
+ }
+
+ @Test
+ public void setStringArrayWithNullValues() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("multi_values", new String[] {"A,B", null, "C,D"});
+ String[] array = settings.getStringArray("multi_values");
+ assertThat(array).isEqualTo(new String[] {"A,B", "", "C,D"});
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void shouldFailToSetArrayValueOnSingleValueProperty() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("array", new String[] {"A", "B", "C"});
+ }
+
+ @Test
+ public void getStringArray_no_value() {
+ Settings settings = new MapSettings();
+ String[] array = settings.getStringArray("array");
+ assertThat(array).isEmpty();
+ }
+
+ @Test
+ public void shouldTrimArray() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", " one, two, three ");
+ String[] array = settings.getStringArray("foo");
+ assertThat(array).isEqualTo(new String[] {"one", "two", "three"});
+ }
+
+ @Test
+ public void shouldKeepEmptyValuesWhenSplitting() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", " one, , two");
+ String[] array = settings.getStringArray("foo");
+ assertThat(array).isEqualTo(new String[] {"one", "", "two"});
+ }
+
+ @Test
+ public void testDefaultValueOfGetString() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getString("hello")).isEqualTo("world");
+ }
+
+ @Test
+ public void set_property_boolean() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", true);
+ settings.setProperty("bar", false);
+ assertThat(settings.getBoolean("foo")).isTrue();
+ assertThat(settings.getBoolean("bar")).isFalse();
+ assertThat(settings.getString("foo")).isEqualTo("true");
+ assertThat(settings.getString("bar")).isEqualTo("false");
+ }
+
+ @Test
+ public void ignore_case_of_boolean_values() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "true");
+ settings.setProperty("bar", "TRUE");
+ // labels in UI
+ settings.setProperty("baz", "True");
+
+ assertThat(settings.getBoolean("foo")).isTrue();
+ assertThat(settings.getBoolean("bar")).isTrue();
+ assertThat(settings.getBoolean("baz")).isTrue();
+ }
+
+ @Test
+ public void get_boolean() {
+ Settings settings = new MapSettings(definitions);
+ assertThat(settings.getBoolean("boolean")).isTrue();
+ assertThat(settings.getBoolean("falseboolean")).isFalse();
+ assertThat(settings.getBoolean("unknown")).isFalse();
+ assertThat(settings.getBoolean("hello")).isFalse();
+ }
+
+ @Test
+ public void shouldCreateByIntrospectingComponent() {
+ Settings settings = new MapSettings();
+ settings.getDefinitions().addComponent(MyComponent.class);
+
+ // property definition has been loaded, ie for default value
+ assertThat(settings.getDefaultValue("foo")).isEqualTo("bar");
+ }
+
+ @Property(key = "foo", name = "Foo", defaultValue = "bar")
+ public static class MyComponent {
+
+ }
+
+ @Test
+ public void getStringLines_no_value() {
+ assertThat(new MapSettings().getStringLines("foo")).hasSize(0);
+ }
+
+ @Test
+ public void getStringLines_single_line() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "the line");
+ assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"the line"});
+ }
+
+ @Test
+ public void getStringLines_linux() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "one\ntwo");
+ assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
+
+ settings.setProperty("foo", "one\ntwo\n");
+ assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
+ }
+
+ @Test
+ public void getStringLines_windows() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "one\r\ntwo");
+ assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
+
+ settings.setProperty("foo", "one\r\ntwo\r\n");
+ assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
+ }
+
+ @Test
+ public void getStringLines_mix() {
+ Settings settings = new MapSettings();
+ settings.setProperty("foo", "one\r\ntwo\nthree");
+ assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two", "three"});
+ }
+
+ @Test
+ public void getKeysStartingWith() {
+ Settings settings = new MapSettings();
+ settings.setProperty("sonar.jdbc.url", "foo");
+ settings.setProperty("sonar.jdbc.username", "bar");
+ settings.setProperty("sonar.security", "admin");
+
+ assertThat(settings.getKeysStartingWith("sonar")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username", "sonar.security");
+ assertThat(settings.getKeysStartingWith("sonar.jdbc")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username");
+ assertThat(settings.getKeysStartingWith("other")).hasSize(0);
+ }
+
+ @Test
+ public void should_fallback_deprecated_key_to_default_value_of_new_key() {
+ Settings settings = new MapSettings(definitions);
+
+ assertThat(settings.getString("newKeyWithDefaultValue")).isEqualTo("default_value");
+ assertThat(settings.getString("oldKeyWithDefaultValue")).isEqualTo("default_value");
+ }
+
+ @Test
+ public void should_fallback_deprecated_key_to_new_key() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("newKey", "value of newKey");
+
+ assertThat(settings.getString("newKey")).isEqualTo("value of newKey");
+ assertThat(settings.getString("oldKey")).isEqualTo("value of newKey");
+ }
+
+ @Test
+ public void should_load_value_of_deprecated_key() {
+ // it's used for example when deprecated settings are set through command-line
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("oldKey", "value of oldKey");
+
+ assertThat(settings.getString("newKey")).isEqualTo("value of oldKey");
+ assertThat(settings.getString("oldKey")).isEqualTo("value of oldKey");
+ }
+
+ @Test
+ public void should_load_values_of_deprecated_key() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("oldKey", "a,b");
+
+ assertThat(settings.getStringArray("newKey")).containsOnly("a", "b");
+ assertThat(settings.getStringArray("oldKey")).containsOnly("a", "b");
+ }
+
+ @Test
+ public void should_support_deprecated_props_with_multi_values() {
+ Settings settings = new MapSettings(definitions);
+ settings.setProperty("new_multi_values", new String[] {" A ", " B "});
+ assertThat(settings.getStringArray("new_multi_values")).isEqualTo(new String[] {"A", "B"});
+ assertThat(settings.getStringArray("old_multi_values")).isEqualTo(new String[] {"A", "B"});
+ }
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact 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.api.config;
-
-import com.google.common.collect.ImmutableMap;
-import org.assertj.core.data.Offset;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.Properties;
-import org.sonar.api.Property;
-import org.sonar.api.PropertyType;
-import org.sonar.api.utils.DateUtils;
-
-import java.util.Date;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class SettingsTest {
-
- private PropertyDefinitions definitions;
-
- @Properties({
- @Property(key = "hello", name = "Hello", defaultValue = "world"),
- @Property(key = "date", name = "Date", defaultValue = "2010-05-18"),
- @Property(key = "datetime", name = "DateTime", defaultValue = "2010-05-18T15:50:45+0100"),
- @Property(key = "boolean", name = "Boolean", defaultValue = "true"),
- @Property(key = "falseboolean", name = "False Boolean", defaultValue = "false"),
- @Property(key = "integer", name = "Integer", defaultValue = "12345"),
- @Property(key = "array", name = "Array", defaultValue = "one,two,three"),
- @Property(key = "multi_values", name = "Array", defaultValue = "1,2,3", multiValues = true),
- @Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET, propertySetKey = "jira"),
- @Property(key = "newKey", name = "New key", deprecatedKey = "oldKey"),
- @Property(key = "newKeyWithDefaultValue", name = "New key with default value", deprecatedKey = "oldKeyWithDefaultValue", defaultValue = "default_value"),
- @Property(key = "new_multi_values", name = "New multi values", defaultValue = "1,2,3", multiValues = true, deprecatedKey = "old_multi_values")
- })
- static class Init {
- }
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void init_definitions() {
- definitions = new PropertyDefinitions();
- definitions.addComponent(Init.class);
- }
-
- @Test
- public void default_values_should_be_loaded_from_definitions() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getDefaultValue("hello")).isEqualTo("world");
- }
-
- @Test
- public void set_property_int() {
- Settings settings = new Settings();
- settings.setProperty("foo", 123);
- assertThat(settings.getInt("foo")).isEqualTo(123);
- assertThat(settings.getString("foo")).isEqualTo("123");
- assertThat(settings.getBoolean("foo")).isFalse();
- }
-
- @Test
- public void default_number_values_are_zero() {
- Settings settings = new Settings();
- assertThat(settings.getInt("foo")).isEqualTo(0);
- assertThat(settings.getLong("foo")).isEqualTo(0L);
- }
-
- @Test
- public void getInt_value_must_be_valid() {
- thrown.expect(NumberFormatException.class);
-
- Settings settings = new Settings();
- settings.setProperty("foo", "not a number");
- settings.getInt("foo");
- }
-
- @Test
- public void all_values_should_be_trimmed_set_property() {
- Settings settings = new Settings();
- settings.setProperty("foo", " FOO ");
- assertThat(settings.getString("foo")).isEqualTo("FOO");
- }
-
- @Test
- public void all_values_should_be_trimmed_set_properties() {
- Settings settings = new Settings();
- settings.setProperties(ImmutableMap.of("foo", " FOO "));
- assertThat(settings.getString("foo")).isEqualTo("FOO");
- }
-
- @Test
- public void test_get_default_value() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getDefaultValue("unknown")).isNull();
- }
-
- @Test
- public void test_get_string() {
- Settings settings = new Settings(definitions);
- settings.setProperty("hello", "Russia");
- assertThat(settings.getString("hello")).isEqualTo("Russia");
- }
-
- @Test
- public void setProperty_date() {
- Settings settings = new Settings();
- Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100");
- settings.setProperty("aDate", date);
- settings.setProperty("aDateTime", date, true);
-
- assertThat(settings.getString("aDate")).isEqualTo("2010-05-18");
- assertThat(settings.getString("aDateTime")).startsWith("2010-05-18T");
- }
-
- @Test
- public void test_get_date() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getDate("unknown")).isNull();
- assertThat(settings.getDate("date").getDate()).isEqualTo(18);
- assertThat(settings.getDate("date").getMonth()).isEqualTo(4);
- }
-
- @Test
- public void test_get_date_not_found() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getDate("unknown")).isNull();
- }
-
- @Test
- public void test_get_datetime() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getDateTime("unknown")).isNull();
- assertThat(settings.getDateTime("datetime").getDate()).isEqualTo(18);
- assertThat(settings.getDateTime("datetime").getMonth()).isEqualTo(4);
- assertThat(settings.getDateTime("datetime").getMinutes()).isEqualTo(50);
- }
-
- @Test
- public void test_get_double() {
- Settings settings = new Settings();
- settings.setProperty("from_double", 3.14159);
- settings.setProperty("from_string", "3.14159");
- assertThat(settings.getDouble("from_double")).isEqualTo(3.14159, Offset.offset(0.00001));
- assertThat(settings.getDouble("from_string")).isEqualTo(3.14159, Offset.offset(0.00001));
- assertThat(settings.getDouble("unknown")).isNull();
- }
-
- @Test
- public void test_get_float() {
- Settings settings = new Settings();
- settings.setProperty("from_float", 3.14159f);
- settings.setProperty("from_string", "3.14159");
- assertThat(settings.getDouble("from_float")).isEqualTo(3.14159f, Offset.offset(0.00001));
- assertThat(settings.getDouble("from_string")).isEqualTo(3.14159f, Offset.offset(0.00001));
- assertThat(settings.getDouble("unknown")).isNull();
- }
-
- @Test
- public void test_get_bad_float() {
- Settings settings = new Settings();
- settings.setProperty("foo", "bar");
-
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("The property 'foo' is not a float value");
- settings.getFloat("foo");
- }
-
- @Test
- public void test_get_bad_double() {
- Settings settings = new Settings();
- settings.setProperty("foo", "bar");
-
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("The property 'foo' is not a double value");
- settings.getDouble("foo");
- }
-
- @Test
- public void testSetNullFloat() {
- Settings settings = new Settings();
- settings.setProperty("foo", (Float) null);
- assertThat(settings.getFloat("foo")).isNull();
- }
-
- @Test
- public void testSetNullDouble() {
- Settings settings = new Settings();
- settings.setProperty("foo", (Double) null);
- assertThat(settings.getDouble("foo")).isNull();
- }
-
- @Test
- public void getStringArray() {
- Settings settings = new Settings(definitions);
- String[] array = settings.getStringArray("array");
- assertThat(array).isEqualTo(new String[] {"one", "two", "three"});
- }
-
- @Test
- public void setStringArray() {
- Settings settings = new Settings(definitions);
- settings.setProperty("multi_values", new String[] {"A", "B"});
- String[] array = settings.getStringArray("multi_values");
- assertThat(array).isEqualTo(new String[] {"A", "B"});
- }
-
- @Test
- public void setStringArrayTrimValues() {
- Settings settings = new Settings(definitions);
- settings.setProperty("multi_values", new String[] {" A ", " B "});
- String[] array = settings.getStringArray("multi_values");
- assertThat(array).isEqualTo(new String[] {"A", "B"});
- }
-
- @Test
- public void setStringArrayEscapeCommas() {
- Settings settings = new Settings(definitions);
- settings.setProperty("multi_values", new String[] {"A,B", "C,D"});
- String[] array = settings.getStringArray("multi_values");
- assertThat(array).isEqualTo(new String[] {"A,B", "C,D"});
- }
-
- @Test
- public void setStringArrayWithEmptyValues() {
- Settings settings = new Settings(definitions);
- settings.setProperty("multi_values", new String[] {"A,B", "", "C,D"});
- String[] array = settings.getStringArray("multi_values");
- assertThat(array).isEqualTo(new String[] {"A,B", "", "C,D"});
- }
-
- @Test
- public void setStringArrayWithNullValues() {
- Settings settings = new Settings(definitions);
- settings.setProperty("multi_values", new String[] {"A,B", null, "C,D"});
- String[] array = settings.getStringArray("multi_values");
- assertThat(array).isEqualTo(new String[] {"A,B", "", "C,D"});
- }
-
- @Test(expected = IllegalStateException.class)
- public void shouldFailToSetArrayValueOnSingleValueProperty() {
- Settings settings = new Settings(definitions);
- settings.setProperty("array", new String[] {"A", "B", "C"});
- }
-
- @Test
- public void getStringArray_no_value() {
- Settings settings = new Settings();
- String[] array = settings.getStringArray("array");
- assertThat(array).isEmpty();
- }
-
- @Test
- public void shouldTrimArray() {
- Settings settings = new Settings();
- settings.setProperty("foo", " one, two, three ");
- String[] array = settings.getStringArray("foo");
- assertThat(array).isEqualTo(new String[] {"one", "two", "three"});
- }
-
- @Test
- public void shouldKeepEmptyValuesWhenSplitting() {
- Settings settings = new Settings();
- settings.setProperty("foo", " one, , two");
- String[] array = settings.getStringArray("foo");
- assertThat(array).isEqualTo(new String[] {"one", "", "two"});
- }
-
- @Test
- public void testDefaultValueOfGetString() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getString("hello")).isEqualTo("world");
- }
-
- @Test
- public void set_property_boolean() {
- Settings settings = new Settings();
- settings.setProperty("foo", true);
- settings.setProperty("bar", false);
- assertThat(settings.getBoolean("foo")).isTrue();
- assertThat(settings.getBoolean("bar")).isFalse();
- assertThat(settings.getString("foo")).isEqualTo("true");
- assertThat(settings.getString("bar")).isEqualTo("false");
- }
-
- @Test
- public void ignore_case_of_boolean_values() {
- Settings settings = new Settings();
- settings.setProperty("foo", "true");
- settings.setProperty("bar", "TRUE");
- // labels in UI
- settings.setProperty("baz", "True");
-
- assertThat(settings.getBoolean("foo")).isTrue();
- assertThat(settings.getBoolean("bar")).isTrue();
- assertThat(settings.getBoolean("baz")).isTrue();
- }
-
- @Test
- public void get_boolean() {
- Settings settings = new Settings(definitions);
- assertThat(settings.getBoolean("boolean")).isTrue();
- assertThat(settings.getBoolean("falseboolean")).isFalse();
- assertThat(settings.getBoolean("unknown")).isFalse();
- assertThat(settings.getBoolean("hello")).isFalse();
- }
-
- @Test
- public void shouldCreateByIntrospectingComponent() {
- Settings settings = Settings.createForComponent(MyComponent.class);
-
- // property definition has been loaded, ie for default value
- assertThat(settings.getDefaultValue("foo")).isEqualTo("bar");
- }
-
- @Property(key = "foo", name = "Foo", defaultValue = "bar")
- public static class MyComponent {
-
- }
-
- @Test
- public void cloneSettings() {
- Settings target = new Settings(definitions).setProperty("foo", "bar");
- Settings settings = new Settings(target);
-
- assertThat(settings.getString("foo")).isEqualTo("bar");
- assertThat(settings.getDefinitions()).isSameAs(definitions);
-
- // do not propagate changes
- settings.setProperty("foo", "changed");
- settings.setProperty("new", "value");
-
- assertThat(settings.getString("foo")).isEqualTo("changed");
- assertThat(settings.getString("new")).isEqualTo("value");
- assertThat(target.getString("foo")).isEqualTo("bar");
- assertThat(target.getString("new")).isNull();
- }
-
- @Test
- public void getStringLines_no_value() {
- assertThat(new Settings().getStringLines("foo")).hasSize(0);
- }
-
- @Test
- public void getStringLines_single_line() {
- Settings settings = new Settings();
- settings.setProperty("foo", "the line");
- assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"the line"});
- }
-
- @Test
- public void getStringLines_linux() {
- Settings settings = new Settings();
- settings.setProperty("foo", "one\ntwo");
- assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
-
- settings.setProperty("foo", "one\ntwo\n");
- assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
- }
-
- @Test
- public void getStringLines_windows() {
- Settings settings = new Settings();
- settings.setProperty("foo", "one\r\ntwo");
- assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
-
- settings.setProperty("foo", "one\r\ntwo\r\n");
- assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two"});
- }
-
- @Test
- public void getStringLines_mix() {
- Settings settings = new Settings();
- settings.setProperty("foo", "one\r\ntwo\nthree");
- assertThat(settings.getStringLines("foo")).isEqualTo(new String[] {"one", "two", "three"});
- }
-
- @Test
- public void getKeysStartingWith() {
- Settings settings = new Settings();
- settings.setProperty("sonar.jdbc.url", "foo");
- settings.setProperty("sonar.jdbc.username", "bar");
- settings.setProperty("sonar.security", "admin");
-
- assertThat(settings.getKeysStartingWith("sonar")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username", "sonar.security");
- assertThat(settings.getKeysStartingWith("sonar.jdbc")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username");
- assertThat(settings.getKeysStartingWith("other")).hasSize(0);
- }
-
- @Test
- public void should_fallback_deprecated_key_to_default_value_of_new_key() {
- Settings settings = new Settings(definitions);
-
- assertThat(settings.getString("newKeyWithDefaultValue")).isEqualTo("default_value");
- assertThat(settings.getString("oldKeyWithDefaultValue")).isEqualTo("default_value");
- }
-
- @Test
- public void should_fallback_deprecated_key_to_new_key() {
- Settings settings = new Settings(definitions);
- settings.setProperty("newKey", "value of newKey");
-
- assertThat(settings.getString("newKey")).isEqualTo("value of newKey");
- assertThat(settings.getString("oldKey")).isEqualTo("value of newKey");
- }
-
- @Test
- public void should_load_value_of_deprecated_key() {
- // it's used for example when deprecated settings are set through command-line
- Settings settings = new Settings(definitions);
- settings.setProperty("oldKey", "value of oldKey");
-
- assertThat(settings.getString("newKey")).isEqualTo("value of oldKey");
- assertThat(settings.getString("oldKey")).isEqualTo("value of oldKey");
- }
-
- @Test
- public void should_load_values_of_deprecated_key() {
- Settings settings = new Settings(definitions);
- settings.setProperty("oldKey", "a,b");
-
- assertThat(settings.getStringArray("newKey")).containsOnly("a", "b");
- assertThat(settings.getStringArray("oldKey")).containsOnly("a", "b");
- }
-
- @Test
- public void should_support_deprecated_props_with_multi_values() {
- Settings settings = new Settings(definitions);
- settings.setProperty("new_multi_values", new String[] {" A ", " B "});
- assertThat(settings.getStringArray("new_multi_values")).isEqualTo(new String[] {"A", "B"});
- assertThat(settings.getStringArray("old_multi_values")).isEqualTo(new String[] {"A", "B"});
- }
-}
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
public class FileExclusionsTest {
@Test
public void ignore_inclusion_of_world() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*");
settings.setProperty(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*");
assertThat(new FileExclusions(settings).sourceInclusions()).isEmpty();
@Test
public void load_inclusions() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*Foo.java");
settings.setProperty(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*FooTest.java");
FileExclusions moduleExclusions = new FileExclusions(settings);
@Test
public void load_exclusions() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "**/*Foo.java");
settings.setProperty(CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY, "**/*FooTest.java");
FileExclusions moduleExclusions = new FileExclusions(settings);
import org.mockito.runners.MockitoJUnitRunner;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.i18n.I18n;
import java.util.Locale;
@Before
public void setUp() {
- settings = new Settings();
+ settings = new MapSettings();
settings.setProperty(CoreProperties.HOURS_IN_DAY, HOURS_IN_DAY);
durations = new Durations(settings, i18n);
}
package org.sonar.scanner.bootstrap;
import com.google.common.collect.ImmutableMap;
+import java.util.HashMap;
import java.util.Map;
+import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.CoreProperties;
+import org.sonar.api.config.Encryption;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
import org.sonar.api.utils.MessageException;
private final GlobalProperties bootstrapProps;
private final GlobalRepositories globalReferentials;
private final GlobalMode mode;
+ private final Map<String, String> properties = new HashMap<>();
public GlobalSettings(GlobalProperties bootstrapProps, PropertyDefinitions propertyDefinitions,
GlobalRepositories globalReferentials, GlobalMode mode) {
- super(propertyDefinitions);
+ super(propertyDefinitions, new Encryption(null));
this.mode = mode;
getEncryption().setPathToSecretKey(bootstrapProps.property(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
this.bootstrapProps = bootstrapProps;
}
@Override
- protected void doOnGetProperties(String key) {
+ protected Optional<String> get(String key) {
if (mode.isIssues() && key.endsWith(".secured") && !key.contains(".license")) {
throw MessageException.of("Access to the secured property '" + key
+ "' is not possible in issues mode. The SonarQube plugin which requires this property must be deactivated in issues mode.");
}
+ return Optional.ofNullable(properties.get(key));
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ @Override
+ protected void set(String key, String value) {
+ properties.put(key, value);
+ }
+
+ @Override
+ protected void remove(String key) {
+ properties.remove(key);
}
}
package org.sonar.scanner.scan;
import com.google.common.collect.Lists;
+import java.util.HashMap;
import java.util.List;
-import org.sonar.api.CoreProperties;
+import java.util.Map;
+import java.util.Optional;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.config.Settings;
import org.sonar.api.utils.MessageException;
private final ProjectRepositories projectRepos;
private final DefaultAnalysisMode analysisMode;
+ private final Map<String, String> properties = new HashMap<>();
public ModuleSettings(GlobalSettings batchSettings, ProjectDefinition moduleDefinition, ProjectRepositories projectSettingsRepo,
DefaultAnalysisMode analysisMode, AnalysisContextReportPublisher contextReportPublisher) {
- super(batchSettings.getDefinitions());
+ super(batchSettings.getDefinitions(), batchSettings.getEncryption());
this.projectRepos = projectSettingsRepo;
this.analysisMode = analysisMode;
- getEncryption().setPathToSecretKey(batchSettings.getString(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
init(moduleDefinition, batchSettings);
contextReportPublisher.dumpModuleSettings(moduleDefinition);
}
@Override
- protected void doOnGetProperties(String key) {
+ protected Optional<String> get(String key) {
if (analysisMode.isIssues() && key.endsWith(".secured") && !key.contains(".license")) {
throw MessageException.of("Access to the secured property '" + key
+ "' is not possible in issues mode. The SonarQube plugin which requires this property must be deactivated in issues mode.");
}
+ return Optional.ofNullable(properties.get(key));
+ }
+
+ @Override
+ protected void set(String key, String value) {
+ properties.put(key, value);
+ }
+
+ @Override
+ protected void remove(String key) {
+ properties.remove(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
}
}
*/
package org.sonar.scanner.scan;
-import org.sonar.api.CoreProperties;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
import org.sonar.api.batch.bootstrap.ProjectReactor;
-import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.analysis.DefaultAnalysisMode;
private final GlobalSettings globalSettings;
private final ProjectRepositories projectRepositories;
private final DefaultAnalysisMode mode;
+ private final Map<String, String> properties = new HashMap<>();
- public ProjectSettings(ProjectReactor reactor, GlobalSettings globalSettings, PropertyDefinitions propertyDefinitions,
- ProjectRepositories projectRepositories, DefaultAnalysisMode mode) {
- super(propertyDefinitions);
+ public ProjectSettings(ProjectReactor reactor, GlobalSettings globalSettings, ProjectRepositories projectRepositories, DefaultAnalysisMode mode) {
+ super(globalSettings.getDefinitions(), globalSettings.getEncryption());
this.mode = mode;
- getEncryption().setPathToSecretKey(globalSettings.getString(CoreProperties.ENCRYPTION_SECRET_KEY_PATH));
this.globalSettings = globalSettings;
this.projectRepositories = projectRepositories;
init(reactor);
}
@Override
- protected void doOnGetProperties(String key) {
+ protected Optional<String> get(String key) {
if (mode.isIssues() && key.endsWith(".secured") && !key.contains(".license")) {
throw MessageException.of("Access to the secured property '" + key
+ "' is not possible in issues mode. The SonarQube plugin which requires this property must be deactivated in issues mode.");
}
+ return Optional.ofNullable(properties.get(key));
+ }
+
+ @Override
+ protected void set(String key, String value) {
+ properties.put(key, value);
+ }
+
+ @Override
+ protected void remove(String key) {
+ properties.remove(key);
+ }
+
+ @Override
+ public Map<String, String> getProperties() {
+ return properties;
}
}
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Project;
import org.sonar.api.utils.System2;
-import org.sonar.scanner.ProjectConfigurator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
when(system2.now()).thenReturn(now);
Project project = new Project("key");
- new ProjectConfigurator(new Settings(), system2).configure(project);
+ new ProjectConfigurator(new MapSettings(), system2).configure(project);
assertThat(now - project.getAnalysisDate().getTime()).isLessThan(1000);
}
@Test
public void analysis_date_could_be_explicitly_set() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2005-01-30");
Project project = new Project("key");
new ProjectConfigurator(settings, system2).configure(project);
@Test
public void analysis_timestamp_could_be_explicitly_set() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2005-01-30T08:45:10+0000");
Project project = new Project("key");
new ProjectConfigurator(settings, system2).configure(project);
@Test(expected = RuntimeException.class)
public void fail_if_analyis_date_is_not_valid() {
- Settings configuration = new Settings();
+ Settings configuration = new MapSettings();
configuration.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2005/30/01");
Project project = new Project("key");
new ProjectConfigurator(configuration, system2).configure(project);
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
-import org.sonar.scanner.bootstrap.BatchPluginPredicate;
-import org.sonar.scanner.bootstrap.GlobalMode;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class BatchPluginPredicateTest {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
GlobalMode mode = mock(GlobalMode.class);
@Test
import java.io.File;
import java.io.IOException;
-
import org.junit.Rule;
-import org.junit.rules.TemporaryFolder;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.home.cache.FileCache;
-import org.sonar.scanner.bootstrap.FileCacheProvider;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void provide() {
FileCacheProvider provider = new FileCacheProvider();
- FileCache cache = provider.provide(new Settings());
+ FileCache cache = provider.provide(new MapSettings());
assertThat(cache).isNotNull();
assertThat(cache.getDir()).isNotNull().exists();
@Test
public void keep_singleton_instance() {
FileCacheProvider provider = new FileCacheProvider();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
FileCache cache1 = provider.provide(settings);
FileCache cache2 = provider.provide(settings);
@Test
public void honor_sonarUserHome() throws IOException {
FileCacheProvider provider = new FileCacheProvider();
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
File f = temp.newFolder();
settings.appendProperty("sonar.userHome", f.getAbsolutePath());
FileCache cache = provider.provide(settings);
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Project;
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.util.CloseableIterator;
import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.ClonePart;
-import org.sonar.scanner.protocol.output.ScannerReport.Duplicate;
-import org.sonar.scanner.protocol.output.ScannerReport.Duplication;
-import org.sonar.scanner.report.ReportPublisher;
-import org.sonar.scanner.cpd.CpdExecutor;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import org.sonar.scanner.index.BatchComponent;
import org.sonar.scanner.index.BatchComponentCache;
+import org.sonar.scanner.protocol.output.ScannerReport.Duplicate;
+import org.sonar.scanner.protocol.output.ScannerReport.Duplication;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
+import org.sonar.scanner.report.ReportPublisher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public void setUp() throws IOException {
File outputDir = temp.newFolder();
- settings = new Settings();
+ settings = new MapSettings();
index = mock(SonarCpdBlockIndex.class);
publisher = mock(ReportPublisher.class);
when(publisher.getWriter()).thenReturn(new ScannerReportWriter(outputDir));
import org.junit.Test;
import org.slf4j.Logger;
import org.sonar.api.config.Settings;
-import org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
@Before
public void init() {
- settings = new Settings();
+ settings = new MapSettings();
engine = new DefaultCpdBlockIndexer(null, null, settings, null);
}
*/
package org.sonar.scanner.cpd.deprecated;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.duplications.block.Block;
-import org.sonar.scanner.cpd.deprecated.JavaCpdBlockIndexer;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import org.sonar.scanner.index.BatchComponentCache;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.eq;
File ioFile = file.file();
FileUtils.copyURLToFile(this.getClass().getResource("ManyStatements.java"), ioFile);
- settings = new Settings();
+ settings = new MapSettings();
engine = new JavaCpdBlockIndexer(fs, settings, index);
}
@Test
public void languageSupported() {
- JavaCpdBlockIndexer engine = new JavaCpdBlockIndexer(mock(FileSystem.class), new Settings(), index);
+ JavaCpdBlockIndexer engine = new JavaCpdBlockIndexer(mock(FileSystem.class), new MapSettings(), index);
assertThat(engine.isLanguageSupported(JAVA)).isTrue();
assertThat(engine.isLanguageSupported("php")).isFalse();
}
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.SonarException;
import org.sonar.core.config.IssueExclusionProperties;
-import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer;
import static org.assertj.core.api.Assertions.assertThat;
@Before
public void init() {
- settings = new Settings(new PropertyDefinitions(IssueExclusionProperties.all()));
+ settings = new MapSettings(new PropertyDefinitions(IssueExclusionProperties.all()));
patternsInitializer = new IssueExclusionPatternInitializer(settings);
}
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.core.config.IssueExclusionProperties;
-import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer;
import static org.assertj.core.api.Assertions.assertThat;
@Before
public void init() {
- settings = new Settings(new PropertyDefinitions(IssueExclusionProperties.all()));
+ settings = new MapSettings(new PropertyDefinitions(IssueExclusionProperties.all()));
patternsInitializer = new IssueInclusionPatternInitializer(settings);
}
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.scanner.bootstrap.BatchWsClient;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void shouldLoadServerProperties() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.SERVER_ID, "123");
settings.setProperty(CoreProperties.SERVER_VERSION, "2.2");
settings.setProperty(CoreProperties.SERVER_STARTTIME, "2010-05-18T17:59:00+0000");
@Test
public void publicRootUrl() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
BatchWsClient client = mock(BatchWsClient.class);
when(client.baseUrl()).thenReturn("http://foo.com/");
DefaultServer metadata = new DefaultServer(settings, client);
@Test(expected = RuntimeException.class)
public void invalid_startup_date_throws_exception() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.SERVER_STARTTIME, "invalid");
BatchWsClient client = mock(BatchWsClient.class);
DefaultServer metadata = new DefaultServer(settings, client);
import org.sonar.api.batch.postjob.issue.PostJobIssue;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.File;
import org.sonar.scanner.index.BatchComponentCache;
import org.sonar.scanner.issue.IssueCache;
import org.sonar.scanner.issue.tracking.TrackedIssue;
-import org.sonar.scanner.postjob.DefaultPostJobContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public void prepare() {
issueCache = mock(IssueCache.class);
resourceCache = new BatchComponentCache();
- settings = new Settings();
+ settings = new MapSettings();
analysisMode = mock(AnalysisMode.class);
context = new DefaultPostJobContext(settings, issueCache, resourceCache, analysisMode);
}
import org.junit.rules.ExpectedException;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
import org.sonar.api.config.Settings;
-import org.sonar.scanner.postjob.PostJobOptimizer;
+import org.sonar.api.config.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
@Before
public void prepare() {
- settings = new Settings();
+ settings = new MapSettings();
optimizer = new PostJobOptimizer(settings);
}
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Project;
import org.sonar.scanner.index.BatchComponentCache;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
-import org.sonar.scanner.report.MetadataPublisher;
import org.sonar.scanner.rule.ModuleQProfiles;
import org.sonar.scanner.rule.QProfile;
import org.sonar.scanner.scan.ImmutableProjectReactor;
org.sonar.api.resources.Resource sampleFile = org.sonar.api.resources.File.create("src/Foo.php").setEffectiveKey("foo:src/Foo.php");
componentCache.add(project, null);
componentCache.add(sampleFile, project);
- settings = new Settings();
+ settings = new MapSettings();
qProfiles = mock(ModuleQProfiles.class);
underTest = new MetadataPublisher(componentCache, new ImmutableProjectReactor(projectDef), settings, qProfiles);
}
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.TempFolder;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.scanner.analysis.DefaultAnalysisMode;
import org.sonar.scanner.bootstrap.BatchWsClient;
-import org.sonar.scanner.report.AnalysisContextReportPublisher;
-import org.sonar.scanner.report.ReportPublisher;
-import org.sonar.scanner.report.ReportPublisherStep;
import org.sonar.scanner.scan.ImmutableProjectReactor;
import static org.apache.commons.io.FileUtils.readFileToString;
public ExpectedException exception = ExpectedException.none();
DefaultAnalysisMode mode = mock(DefaultAnalysisMode.class);
- Settings settings = new Settings(new PropertyDefinitions(CorePropertyDefinitions.all()));
+ Settings settings = new MapSettings(new PropertyDefinitions(CorePropertyDefinitions.all()));
BatchWsClient wsClient = mock(BatchWsClient.class, Mockito.RETURNS_DEEP_STUBS);
Server server = mock(Server.class);
ImmutableProjectReactor reactor = mock(ImmutableProjectReactor.class);
import org.slf4j.Logger;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.utils.MessageException;
-import org.sonar.scanner.rule.ModuleQProfiles;
-import org.sonar.scanner.rule.QProfile;
-import org.sonar.scanner.rule.QProfileVerifier;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
private DefaultFileSystem fs;
private ModuleQProfiles profiles;
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
@Before
public void before() throws Exception {
import org.junit.Test;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.rule.RuleKey;
-import org.sonar.scanner.rule.ModuleQProfiles;
-import org.sonar.scanner.rule.QProfile;
-import org.sonar.scanner.rule.RulesProfileProvider;
-import org.sonar.scanner.rule.RulesProfileWrapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class RulesProfileProviderTest {
ModuleQProfiles qProfiles = mock(ModuleQProfiles.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
RulesProfileProvider provider = new RulesProfileProvider();
@Test
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Languages;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.FakeJava;
@Rule
public ExpectedException thrown = ExpectedException.none();
- private Settings settings = new Settings();
+ private Settings settings = new MapSettings();
private LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(FakeJava.INSTANCE));
private DefaultFileSystem fs;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.analysis.DefaultAnalysisMode;
+import org.sonar.scanner.bootstrap.GlobalMode;
+import org.sonar.scanner.bootstrap.GlobalProperties;
import org.sonar.scanner.bootstrap.GlobalSettings;
+import org.sonar.scanner.protocol.input.GlobalRepositories;
import org.sonar.scanner.report.AnalysisContextReportPublisher;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.ProjectRepositories;
-import org.sonar.scanner.scan.ModuleSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Test
public void test_loading_of_module_settings() {
- GlobalSettings globalSettings = mock(GlobalSettings.class);
- when(globalSettings.getDefinitions()).thenReturn(new PropertyDefinitions());
- when(globalSettings.getProperties()).thenReturn(ImmutableMap.of(
+ GlobalSettings globalSettings = newGlobalSettings(ImmutableMap.of(
"overridding", "batch",
"on-batch", "true"));
assertThat(moduleSettings.getString("overridding")).isEqualTo("module");
assertThat(moduleSettings.getString("on-batch")).isEqualTo("true");
assertThat(moduleSettings.getString("on-module")).isEqualTo("true");
-
}
// SONAR-6386
@Test
public void test_loading_of_parent_module_settings_for_new_module() {
- GlobalSettings globalSettings = mock(GlobalSettings.class);
- when(globalSettings.getDefinitions()).thenReturn(new PropertyDefinitions());
- when(globalSettings.getProperties()).thenReturn(ImmutableMap.of(
+ GlobalSettings globalSettings = newGlobalSettings(ImmutableMap.of(
"overridding", "batch",
"on-batch", "true"));
@Test
public void should_not_fail_when_accessing_secured_properties() {
- GlobalSettings batchSettings = mock(GlobalSettings.class);
- when(batchSettings.getDefinitions()).thenReturn(new PropertyDefinitions());
- when(batchSettings.getProperties()).thenReturn(ImmutableMap.of(
+ GlobalSettings globalSettings = newGlobalSettings(ImmutableMap.of(
"sonar.foo.secured", "bar"));
ProjectRepositories projSettingsRepo = createSettings("struts-core", ImmutableMap.of("sonar.foo.license.secured", "bar2"));
ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
- ModuleSettings moduleSettings = new ModuleSettings(batchSettings, module, projSettingsRepo, mode, mock(AnalysisContextReportPublisher.class));
+ ModuleSettings moduleSettings = new ModuleSettings(globalSettings, module, projSettingsRepo, mode, mock(AnalysisContextReportPublisher.class));
assertThat(moduleSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
assertThat(moduleSettings.getString("sonar.foo.secured")).isEqualTo("bar");
@Test
public void should_fail_when_accessing_secured_properties_in_issues() {
- GlobalSettings batchSettings = mock(GlobalSettings.class);
- when(batchSettings.getDefinitions()).thenReturn(new PropertyDefinitions());
- when(batchSettings.getProperties()).thenReturn(ImmutableMap.of(
+ GlobalSettings globalSettings = newGlobalSettings(ImmutableMap.of(
"sonar.foo.secured", "bar"));
ProjectRepositories projSettingsRepo = createSettings("struts-core", ImmutableMap.of("sonar.foo.license.secured", "bar2"));
ProjectDefinition module = ProjectDefinition.create().setKey("struts-core");
- ModuleSettings moduleSettings = new ModuleSettings(batchSettings, module, projSettingsRepo, mode, mock(AnalysisContextReportPublisher.class));
+ ModuleSettings moduleSettings = new ModuleSettings(globalSettings, module, projSettingsRepo, mode, mock(AnalysisContextReportPublisher.class));
assertThat(moduleSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
"Access to the secured property 'sonar.foo.secured' is not possible in issues mode. The SonarQube plugin which requires this property must be deactivated in issues mode.");
moduleSettings.getString("sonar.foo.secured");
}
+
+ private GlobalSettings newGlobalSettings(Map<String, String> props) {
+ GlobalProperties globalProps = new GlobalProperties(props);
+ return new GlobalSettings(globalProps, new PropertyDefinitions(),
+ new GlobalRepositories(), new GlobalMode(globalProps));
+ }
}
*/
package org.sonar.scanner.scan;
-import static org.mockito.Mockito.when;
-
-import org.sonar.api.utils.MessageException;
-import org.sonar.scanner.analysis.DefaultAnalysisMode;
-import org.sonar.scanner.scan.ProjectReactorValidator;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
+import org.sonar.api.utils.MessageException;
+import org.sonar.scanner.analysis.DefaultAnalysisMode;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
public class ProjectReactorValidatorTest {
@Before
public void prepare() {
mode = mock(DefaultAnalysisMode.class);
- settings = new Settings();
+ settings = new MapSettings();
validator = new ProjectReactorValidator(settings, mode);
}
import org.sonar.scanner.protocol.input.GlobalRepositories;
import org.sonar.scanner.repository.FileData;
import org.sonar.scanner.repository.ProjectRepositories;
-import org.sonar.scanner.scan.ProjectSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
project.setProperty("project.prop", "project");
projectRef = new ProjectRepositories(emptySettings, emptyFileData, null);
- ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, new PropertyDefinitions(), projectRef, mode);
+ ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, projectRef, mode);
assertThat(batchSettings.getString("project.prop")).isEqualTo("project");
}
settings.put("struts", "sonar.java.coveragePlugin", "jacoco");
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, new PropertyDefinitions(), projectRef, mode);
+ ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, projectRef, mode);
assertThat(batchSettings.getString("sonar.java.coveragePlugin")).isEqualTo("jacoco");
}
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, new PropertyDefinitions(), projectRef, mode);
+ ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, projectRef, mode);
assertThat(batchSettings.getString("sonar.java.coveragePlugin")).isEqualTo("jacoco");
}
settings.put("struts", "sonar.foo.license.secured", "bar2");
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, new PropertyDefinitions(), projectRef, mode);
+ ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, projectRef, mode);
assertThat(batchSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
assertThat(batchSettings.getString("sonar.foo.secured")).isEqualTo("bar");
when(mode.isIssues()).thenReturn(true);
projectRef = new ProjectRepositories(settings, emptyFileData, null);
- ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, new PropertyDefinitions(), projectRef, mode);
+ ProjectSettings batchSettings = new ProjectSettings(new ProjectReactor(project), bootstrapProps, projectRef, mode);
assertThat(batchSettings.getString("sonar.foo.license.secured")).isEqualTo("bar2");
thrown.expect(MessageException.class);
*/
package org.sonar.scanner.scan.filesystem;
+import java.io.File;
+import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.scan.filesystem.FileExclusions;
-import org.sonar.scanner.scan.filesystem.ExclusionFilters;
-import java.io.File;
-import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void no_inclusions_nor_exclusions() throws IOException {
- ExclusionFilters filter = new ExclusionFilters(new FileExclusions(new Settings()));
+ ExclusionFilters filter = new ExclusionFilters(new FileExclusions(new MapSettings()));
filter.prepare();
java.io.File file = temp.newFile();
@Test
public void match_inclusion() throws IOException {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*Dao.java");
ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings));
filter.prepare();
@Test
public void match_at_least_one_inclusion() throws IOException {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*Dao.java,**/*Dto.java");
ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings));
@Test
public void match_exclusions() throws IOException {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "src/main/java/**/*");
settings.setProperty(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY, "src/test/java/**/*");
settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "**/*Dao.java");
File baseDir = temp.newFile();
File excludedFile = new File(baseDir, "src/main/java/org/bar/Bar.java");
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "src/main/java/**/*");
settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "file:" + excludedFile.getCanonicalPath());
ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings));
@Test
public void trim_pattern() {
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, " **/*Dao.java ");
ExclusionFilters filter = new ExclusionFilters(new FileExclusions(settings));
import org.mockito.Mockito;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.FileMetadata;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.scan.filesystem.PathResolver;
-import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem;
-import org.sonar.scanner.scan.filesystem.InputFileBuilder;
-import org.sonar.scanner.scan.filesystem.InputFileBuilderFactory;
-import org.sonar.scanner.scan.filesystem.LanguageDetectionFactory;
-import org.sonar.scanner.scan.filesystem.StatusDetectionFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
DefaultModuleFileSystem fs = mock(DefaultModuleFileSystem.class);
InputFileBuilderFactory factory = new InputFileBuilderFactory(ProjectDefinition.create().setKey("struts"), pathResolver, langDetectionFactory,
- statusDetectionFactory, new Settings(), new FileMetadata());
+ statusDetectionFactory, new MapSettings(), new FileMetadata());
InputFileBuilder builder = factory.create(fs);
assertThat(builder.langDetection()).isNotNull();
*/
package org.sonar.scanner.scan.filesystem;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.PathUtils;
-import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem;
-import org.sonar.scanner.scan.filesystem.InputFileBuilder;
-import org.sonar.scanner.scan.filesystem.LanguageDetection;
-import org.sonar.scanner.scan.filesystem.StatusDetection;
-import java.io.File;
-import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
.thenReturn(InputFile.Status.ADDED);
InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
- langDetection, statusDetection, fs, new Settings(), new FileMetadata());
+ langDetection, statusDetection, fs, new MapSettings(), new FileMetadata());
DefaultInputFile inputFile = builder.create(srcFile);
builder.completeAndComputeMetadata(inputFile, InputFile.Type.MAIN);
when(fs.baseDir()).thenReturn(basedir);
InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
- langDetection, statusDetection, fs, new Settings(), new FileMetadata());
+ langDetection, statusDetection, fs, new MapSettings(), new FileMetadata());
DefaultInputFile inputFile = builder.create(srcFile);
assertThat(inputFile).isNull();
when(langDetection.language(any(InputFile.class))).thenReturn(null);
InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
- langDetection, statusDetection, fs, new Settings(), new FileMetadata());
+ langDetection, statusDetection, fs, new MapSettings(), new FileMetadata());
DefaultInputFile inputFile = builder.create(srcFile);
inputFile = builder.completeAndComputeMetadata(inputFile, InputFile.Type.MAIN);
package org.sonar.scanner.scan.filesystem;
import org.junit.Test;
-import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Languages;
import org.sonar.scanner.FakeJava;
import org.sonar.scanner.repository.language.DefaultLanguagesRepository;
import org.sonar.scanner.repository.language.LanguagesRepository;
-import org.sonar.scanner.scan.filesystem.LanguageDetection;
-import org.sonar.scanner.scan.filesystem.LanguageDetectionFactory;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void testCreate() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(FakeJava.INSTANCE));
- LanguageDetectionFactory factory = new LanguageDetectionFactory(new Settings(), languages);
+ LanguageDetectionFactory factory = new LanguageDetectionFactory(new MapSettings(), languages);
LanguageDetection languageDetection = factory.create();
assertThat(languageDetection).isNotNull();
assertThat(languageDetection.patternsByLanguage()).hasSize(1);
*/
package org.sonar.scanner.scan.filesystem;
+import java.io.File;
+import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.utils.MessageException;
import org.sonar.scanner.repository.language.DefaultLanguagesRepository;
import org.sonar.scanner.repository.language.LanguagesRepository;
-import org.sonar.scanner.scan.filesystem.LanguageDetection;
-import java.io.File;
-import java.io.IOException;
import static junit.framework.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void search_by_file_extension() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java", "jav"), new MockLanguage("cobol", "cbl", "cob")));
- LanguageDetection detection = new LanguageDetection(new Settings(), languages);
+ LanguageDetection detection = new LanguageDetection(new MapSettings(), languages);
assertThat(detection.language(newInputFile("Foo.java"))).isEqualTo("java");
assertThat(detection.language(newInputFile("src/Foo.java"))).isEqualTo("java");
@Test
public void should_not_fail_if_no_language() throws Exception {
- LanguageDetection detection = spy(new LanguageDetection(new Settings(), new DefaultLanguagesRepository(new Languages())));
+ LanguageDetection detection = spy(new LanguageDetection(new MapSettings(), new DefaultLanguagesRepository(new Languages())));
assertThat(detection.language(newInputFile("Foo.java"))).isNull();
}
public void plugin_can_declare_a_file_extension_twice_for_case_sensitivity() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("abap", "abap", "ABAP")));
- LanguageDetection detection = new LanguageDetection(new Settings(), languages);
+ LanguageDetection detection = new LanguageDetection(new MapSettings(), languages);
assertThat(detection.language(newInputFile("abc.abap"))).isEqualTo("abap");
}
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java"), new MockLanguage("abap")));
// No side-effect on non-ABAP projects
- LanguageDetection detection = new LanguageDetection(new Settings(), languages);
+ LanguageDetection detection = new LanguageDetection(new MapSettings(), languages);
assertThat(detection.language(newInputFile("abc"))).isNull();
assertThat(detection.language(newInputFile("abc.abap"))).isNull();
assertThat(detection.language(newInputFile("abc.java"))).isEqualTo("java");
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_LANGUAGE_PROPERTY, "abap");
detection = new LanguageDetection(settings, languages);
assertThat(detection.language(newInputFile("abc"))).isEqualTo("abap");
public void force_language_using_deprecated_property() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java"), new MockLanguage("php", "php")));
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_LANGUAGE_PROPERTY, "java");
LanguageDetection detection = new LanguageDetection(settings, languages);
assertThat(detection.language(newInputFile("abc"))).isNull();
thrown.expectMessage("No language is installed with key 'unknown'. Please update property 'sonar.language'");
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java"), new MockLanguage("php", "php")));
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty(CoreProperties.PROJECT_LANGUAGE_PROPERTY, "unknown");
new LanguageDetection(settings, languages);
}
@Test
public void fail_if_conflicting_language_suffix() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
- LanguageDetection detection = new LanguageDetection(new Settings(), languages);
+ LanguageDetection detection = new LanguageDetection(new MapSettings(), languages);
try {
detection.language(newInputFile("abc.xhtml"));
fail();
public void solve_conflict_using_filepattern() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("sonar.lang.patterns.xml", "xml/**");
settings.setProperty("sonar.lang.patterns.web", "web/**");
LanguageDetection detection = new LanguageDetection(settings, languages);
@Test
public void fail_if_conflicting_filepattern() throws Exception {
LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("abap", "abap"), new MockLanguage("cobol", "cobol")));
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
settings.setProperty("sonar.lang.patterns.abap", "*.abap,*.txt");
settings.setProperty("sonar.lang.patterns.cobol", "*.cobol,*.txt");
*/
package org.sonar.scanner.scan.report;
+import java.util.Arrays;
+import java.util.Collections;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.Severity;
import org.sonar.api.utils.log.LogTester;
import org.sonar.scanner.issue.IssueCache;
import org.sonar.scanner.issue.tracking.TrackedIssue;
import org.sonar.scanner.scan.filesystem.InputPathCache;
-import org.sonar.scanner.scan.report.ConsoleReport;
-import java.util.Arrays;
-import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Before
public void prepare() {
- settings = new Settings();
+ settings = new MapSettings();
issueCache = mock(IssueCache.class);
inputPathCache = mock(InputPathCache.class);
report = new ConsoleReport(settings, issueCache, inputPathCache);
import org.sonar.api.batch.rule.Rules;
import org.sonar.api.batch.rule.internal.RulesBuilder;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.issue.Issue;
import org.sonar.api.platform.Server;
import org.sonar.api.resources.Project;
import org.sonar.scanner.protocol.input.ScannerInput;
import org.sonar.scanner.repository.user.UserRepositoryLoader;
import org.sonar.scanner.scan.filesystem.InputPathCache;
-import org.sonar.scanner.scan.report.JSONReport;
import static net.javacrumbs.jsonunit.assertj.JsonAssert.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
DefaultFileSystem fs;
Server server = mock(Server.class);
Rules rules = mock(Rules.class);
- Settings settings = new Settings();
+ Settings settings = new MapSettings();
IssueCache issueCache = mock(IssueCache.class);
private UserRepositoryLoader userRepository;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.Version;
MetricFinder metricFinder = mock(MetricFinder.class);
when(metricFinder.<Integer>findByKey(CoreMetrics.NCLOC_KEY)).thenReturn(CoreMetrics.NCLOC);
when(metricFinder.<String>findByKey(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION);
- settings = new Settings();
+ settings = new MapSettings();
sensorStorage = mock(SensorStorage.class);
analysisMode = mock(AnalysisMode.class);
runtime = SonarRuntimeImpl.forSonarQube(Version.parse("5.5"), SonarQubeSide.SCANNER);
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
import org.sonar.api.resources.File;
MetricFinder metricFinder = mock(MetricFinder.class);
when(metricFinder.<Integer>findByKey(CoreMetrics.NCLOC_KEY)).thenReturn(CoreMetrics.NCLOC);
when(metricFinder.<String>findByKey(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION);
- settings = new Settings();
+ settings = new MapSettings();
moduleIssues = mock(ModuleIssues.class);
project = new Project("myProject");
measureCache = mock(MeasureCache.class);
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.rule.RuleKey;
-import org.sonar.scanner.sensor.SensorOptimizer;
import static org.assertj.core.api.Assertions.assertThat;
@Before
public void prepare() throws Exception {
fs = new DefaultFileSystem(temp.newFolder().toPath());
- settings = new Settings();
+ settings = new MapSettings();
optimizer = new SensorOptimizer(fs, new ActiveRulesBuilder().build(), settings);
}
*/
package org.sonar.scanner.sensor.coverage;
-import org.junit.rules.TemporaryFolder;
-
-import org.sonar.api.batch.fs.internal.DefaultFileSystem;
-import org.sonar.api.batch.fs.internal.DefaultInputFile;
import com.google.common.collect.ImmutableMap;
+import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.sonar.api.batch.fs.internal.DefaultFileSystem;
+import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.Settings;
+import org.sonar.api.config.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
import org.sonar.api.resources.File;
import org.sonar.api.resources.Resource;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.core.config.ExclusionProperties;
-import org.sonar.scanner.sensor.coverage.CoverageExclusions;
-import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Before
public void createFilter() {
- settings = new Settings(new PropertyDefinitions(ExclusionProperties.all()));
+ settings = new MapSettings(new PropertyDefinitions(ExclusionProperties.all()));
fs = new DefaultFileSystem(temp.getRoot());
filter = new CoverageExclusions(settings, fs);
}
import org.sonar.api.source.Symbolizable;
import org.sonar.scanner.index.BatchComponent;
import org.sonar.scanner.sensor.DefaultSensorStorage;
-import org.sonar.scanner.source.SymbolizableBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;