org.sonar.api.config.Configuration类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(164)

本文整理了Java中org.sonar.api.config.Configuration类的一些代码示例,展示了Configuration类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Configuration类的具体详情如下:
包路径:org.sonar.api.config.Configuration
类名称:Configuration

Configuration介绍

[英]Component to get effective configuration. Values of properties depend on the runtime environment:

  • immutable project configuration in scanner.
  • global configuration in web server. It does not allow to get the settings overridden on projects.
  • project configuration in Compute Engine.

Usage

public class MyExtension { 
private final Configuration config; 
public MyExtension(Configuration config) { 
this.config = config; 
} 
public void doSomething() { 
String fooValue = config.get("sonar.foo").orElse(null); 
// .. 
} 
}

Scanner example

Scanner sensor can get the reference on Configuration directly through SensorContext, without injecting the component into constructor.

public class MySensor implements Sensor { 
 @Override 
public void execute(SensorContext context) { 
String fooValue = context.config().get("sonar.foo").orElse(null); 
// .. 
} 
}

For testing, and only for testing, the in-memory implementation MapSettings can be used.

@Test 
public void my_test() { 
MapSettings settings = new MapSettings(); 
settings.setProperty("foo", "bar"); 
MyExtension underTest = new MyExtension(settings.asConfig()); 
// ... 
}

[中]组件以获得有效的配置。属性的值取决于运行时环境:
*扫描仪中不可变的项目配置。
*web服务器中的全局配置。它不允许在项目上覆盖设置。
*计算引擎中的项目配置。
####用法

public class MyExtension { 
private final Configuration config; 
public MyExtension(Configuration config) { 
this.config = config; 
} 
public void doSomething() { 
String fooValue = config.get("sonar.foo").orElse(null); 
// .. 
} 
}

####扫描仪示例
Scanner sensor可以直接通过SensorContext获取配置参考,而无需将组件注入构造函数

public class MySensor implements Sensor { 
 @Override 
public void execute(SensorContext context) { 
String fooValue = context.config().get("sonar.foo").orElse(null); 
// .. 
} 
}

对于测试,并且仅对于测试,可以使用内存中的实现映射设置。

@Test 
public void my_test() { 
MapSettings settings = new MapSettings(); 
settings.setProperty("foo", "bar"); 
MyExtension underTest = new MyExtension(settings.asConfig()); 
// ... 
}

代码示例

代码示例来源:origin: SonarSource/sonarqube

public DebtRatingGrid(Configuration config) {
 try {
  String[] grades = config.getStringArray(RATING_GRID);
  gridValues = new double[4];
  for (int i = 0; i < 4; i++) {
   gridValues[i] = Double.parseDouble(grades[i]);
  }
  this.ratingBounds = buildRatingBounds(gridValues);
 } catch (Exception e) {
  throw new IllegalArgumentException("The rating grid is incorrect. Expected something similar to '"
   + RATING_GRID_DEF_VALUES + "' and got '" + config.get(RATING_GRID).orElse("") + "'", e);
 }
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public void start() {
 this.systemSettingValuesByKey.put(SONAR_UPDATECENTER_ACTIVATE.getKey(), config.get(SONAR_UPDATECENTER_ACTIVATE.getKey()).orElse(null));
 boolean isOnSonarCloud = config.getBoolean(SONARCLOUD_ENABLED.getKey()).orElse(false);
 if (isOnSonarCloud) {
  this.systemSettingValuesByKey.put(SONAR_PRISMIC_ACCESS_TOKEN.getKey(), config.get(SONAR_PRISMIC_ACCESS_TOKEN.getKey()).orElse(null));
  this.systemSettingValuesByKey.put(SONAR_ANALYTICS_TRACKING_ID.getKey(), config.get(SONAR_ANALYTICS_TRACKING_ID.getKey()).orElse(null));
 }
}

代码示例来源:origin: SonarSource/sonarqube

private boolean settingsCondition(DefaultPostJobDescriptor descriptor) {
 if (!descriptor.properties().isEmpty()) {
  for (String propertyKey : descriptor.properties()) {
   if (!settings.hasKey(propertyKey)) {
    return false;
   }
  }
 }
 return true;
}

代码示例来源:origin: SonarSource/sonarqube

private String computeBaseUrl() {
 String host = config.get("sonar.web.host").orElse("");
 int port = config.getInt("sonar.web.port").orElse(0);
 String context = config.get("sonar.web.context").orElse("");
 StringBuilder res = new StringBuilder();
 res.append("http://");
 appendHost(host, res);
 appendPort(port, res);
 appendContext(context, res);
 return res.toString();
}

代码示例来源:origin: SonarSource/sonarqube

private void applySettingsConfiguration(SettingsConfiguration settingsConfiguration) {
 settings.put("index.mapper.dynamic", valueOf(false));
 settings.put("index.refresh_interval", refreshInterval(settingsConfiguration));
 Configuration config = settingsConfiguration.getConfiguration();
 boolean clusterMode = config.getBoolean(CLUSTER_ENABLED.getKey()).orElse(false);
 int shards = config.getInt(format("sonar.search.%s.shards", indexName))
  .orElse(settingsConfiguration.getDefaultNbOfShards());
 int replicas = clusterMode ? config.getInt(SEARCH_REPLICAS.getKey()).orElse(1) : 0;
 settings.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, shards);
 settings.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, replicas);
}

代码示例来源:origin: SonarSource/sonarqube

/**
 * Effective value as boolean. It is {@code empty} if {@link #get(String)} is empty or if it
 * does not return {@code "true"}, even if it's not a boolean representation.
 * @return {@code true} if the effective value is {@code "true"}, {@code false} for any other non empty value. 
 * If the property does not have value nor default value, then {@code empty} is returned.
 */
default Optional<Boolean> getBoolean(String key) {
 return get(key).map(String::trim).map(Boolean::parseBoolean);
}

代码示例来源:origin: SonarSource/sonarqube

public EsClient provide(Configuration config) {
 if (cache == null) {
  Settings.Builder esSettings = Settings.builder();
  // mandatory property defined by bootstrap process
  esSettings.put("cluster.name", config.get(CLUSTER_NAME.getKey()).get());
  boolean clusterEnabled = config.getBoolean(CLUSTER_ENABLED.getKey()).orElse(false);
  boolean searchNode = !clusterEnabled || SEARCH.equals(NodeType.parse(config.get(CLUSTER_NODE_TYPE.getKey()).orElse(null)));
  final TransportClient nativeClient = new MinimalTransportClient(esSettings.build());
  if (clusterEnabled && !searchNode) {
   esSettings.put("client.transport.sniff", true);
   Arrays.stream(config.getStringArray(CLUSTER_SEARCH_HOSTS.getKey()))
    .map(HostAndPort::fromString)
    .forEach(h -> addHostToClient(h, nativeClient));
   LOGGER.info("Connected to remote Elasticsearch: [{}]", displayedAddresses(nativeClient));
  } else {
   HostAndPort host = HostAndPort.fromParts(config.get(SEARCH_HOST.getKey()).get(), config.getInt(SEARCH_PORT.getKey()).get());
   addHostToClient(host, nativeClient);
   LOGGER.info("Connected to local Elasticsearch: [{}]", displayedAddresses(nativeClient));
  }
  cache = new EsClient(nativeClient);
 }
 return cache;
}

代码示例来源:origin: SonarSource/sonarqube

public boolean isCrossProjectDuplicationEnabled() {
 return settings.getBoolean(CoreProperties.CPD_CROSS_PROJECT).orElse(false)
  // No cross project duplication for branches
  && StringUtils.isBlank(branch);
}

代码示例来源:origin: SonarSource/sonarqube

private String[] exclusions(String globalExclusionsProperty, String exclusionsProperty) {
  String[] globalExclusions = config.getStringArray(globalExclusionsProperty);
  String[] exclusions = config.getStringArray(exclusionsProperty);
  return Stream.concat(Arrays.stream(globalExclusions), Arrays.stream(exclusions))
   .map(StringUtils::trim)
   .toArray(String[]::new);
 }
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public void start() {
 if (analysisMode.isIssues()) {
  return;
 }
 if (isDisabled()) {
  LOG.debug(MESSAGE_SCM_STEP_IS_DISABLED_BY_CONFIGURATION);
  return;
 }
 if (settings.hasKey(SCM_PROVIDER_KEY)) {
  settings.get(SCM_PROVIDER_KEY).ifPresent(this::setProviderIfSupported);
 } else {
  autodetection();
  if (this.provider == null) {
   considerOldScmUrl();
  }
  if (this.provider == null) {
   String message = "SCM provider autodetection failed. Please use \"" + SCM_PROVIDER_KEY + "\" to define SCM of " +
    "your project, or disable the SCM Sensor in the project settings.";
   LOG.warn(message);
   analysisWarnings.addUnique(message);
  }
 }
 if (isExclusionDisabled()) {
  LOG.info(MESSAGE_SCM_EXLUSIONS_IS_DISABLED_BY_CONFIGURATION);
 }
}

代码示例来源:origin: SonarSource/sonar-java

@CheckForNull
private static List<File> getReportsDirectoriesFromProperty(Configuration settings, FileSystem fs, PathResolver pathResolver) {
 if(settings.hasKey(SUREFIRE_REPORT_PATHS_PROPERTY)) {
  return Arrays.stream(settings.getStringArray(SUREFIRE_REPORT_PATHS_PROPERTY))
   .map(String::trim)
   .map(path -> getFileFromPath(fs, pathResolver, path))
   .filter(Objects::nonNull)
   .collect(Collectors.toList());
 }
 return null;
}

代码示例来源:origin: SonarSource/sonarqube

/**
  * Not applicable to Java, as the {@link BlockChunker} that it uses does not record start and end units of each block. 
  * Also, it uses statements instead of tokens. 
  */
 int getMinimumTokens(String languageKey) {
  return settings.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100);
 }
}

代码示例来源:origin: SonarSource/sonarqube

/**
 * Can be null when server is waiting for migration
 */
@Override
@CheckForNull
public String getId() {
 return config.get(CoreProperties.SERVER_ID).orElse(null);
}

代码示例来源:origin: SonarSource/sonarqube

public IntegrateCrossProjectDuplications(Configuration config, DuplicationRepository duplicationRepository) {
 this.config = config;
 this.duplicationRepository = duplicationRepository;
 if (config.getBoolean(CoreProperties.CPD_CROSS_PROJECT).orElse(false)) {
  LOGGER.warn("This analysis uses the deprecated cross-project duplication feature.");
 }
}

代码示例来源:origin: SonarSource/sonarqube

private Set<String> loadReportPaths() {
 return Arrays.stream(config.getStringArray(REPORT_PATHS_PROPERTY_KEY)).collect(Collectors.toSet());
}

代码示例来源:origin: SonarSource/sonar-java

@CheckForNull
private static File getReportsDirectoryFromDeprecatedProperty(Configuration settings, FileSystem fs, PathResolver pathResolver) {
 if(settings.hasKey(SUREFIRE_REPORTS_PATH_PROPERTY)) {
  String path = settings.get(SUREFIRE_REPORTS_PATH_PROPERTY).orElse(null);
  if (path != null) {
   return getFileFromPath(fs, pathResolver, path);
  }
 }
 return null;
}

代码示例来源:origin: org.sonarsource.sonarqube/sonar-server

private void applySettingsConfiguration(SettingsConfiguration settingsConfiguration) {
 settings.put("index.mapper.dynamic", valueOf(false));
 settings.put("index.refresh_interval", refreshInterval(settingsConfiguration));
 Configuration config = settingsConfiguration.getConfiguration();
 boolean clusterMode = config.getBoolean(CLUSTER_ENABLED.getKey()).orElse(false);
 int shards = config.getInt(format("sonar.search.%s.shards", indexName))
  .orElse(settingsConfiguration.getDefaultNbOfShards());
 int replicas = clusterMode ? config.getInt(SEARCH_REPLICAS.getKey()).orElse(1) : 0;
 settings.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, shards);
 settings.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, replicas);
}

代码示例来源:origin: SonarSource/sonarqube

private int getMinimumTokens(String languageKey) {
 // The java language is an exception : it doesn't compute tokens but statement, so the settings could not be used.
 if (languageKey.equalsIgnoreCase(JAVA_KEY)) {
  return 0;
 }
 return config.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100);
}

代码示例来源:origin: SonarSource/sonarqube

private static Map<String, LanguageSpecificConfiguration> initLanguageSpecificConfigurationByLanguageKey(Configuration config) {
 ImmutableMap.Builder<String, LanguageSpecificConfiguration> builder = ImmutableMap.builder();
 String[] languageConfigIndexes = config.getStringArray(LANGUAGE_SPECIFIC_PARAMETERS);
 for (String languageConfigIndex : languageConfigIndexes) {
  String languagePropertyKey = LANGUAGE_SPECIFIC_PARAMETERS + "." + languageConfigIndex + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY;
  String languageKey = config.get(languagePropertyKey)
   .orElseThrow(() -> MessageException.of("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " +
    "Contact your administrator to update this configuration in the global administration section of SonarQube."));
  builder.put(languageKey, LanguageSpecificConfiguration.create(config, languageConfigIndex));
 }
 return builder.build();
}

代码示例来源:origin: SonarSource/sonarqube

private static long initDefaultDevelopmentCost(Configuration config) {
 try {
  return Long.parseLong(config.get(DEVELOPMENT_COST).get());
 } catch (NumberFormatException e) {
  throw new IllegalArgumentException("The value of the development cost property '" + DEVELOPMENT_COST
   + "' is incorrect. Expected long but got '" + config.get(DEVELOPMENT_COST).get() + "'", e);
 }
}

相关文章