Java Code Examples for org.sonar.api.config.Configuration

The following examples show how to use org.sonar.api.config.Configuration. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testGetBranchName() {
    AnalysisDetails.BranchDetails branchDetails = mock(AnalysisDetails.BranchDetails.class);
    doReturn("branchName").when(branchDetails).getBranchName();

    AnalysisDetails.MeasuresHolder measuresHolder = mock(AnalysisDetails.MeasuresHolder.class);
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    QualityGate qualityGate = mock(QualityGate.class);
    Analysis analysis = mock(Analysis.class);
    Project project = mock(Project.class);
    Configuration configuration = mock(Configuration.class);
    ScannerContext scannerContext = mock(ScannerContext.class);

    AnalysisDetails testCase =
            new AnalysisDetails(branchDetails, postAnalysisIssueVisitor, qualityGate, measuresHolder, analysis,
                                project, configuration, null, scannerContext);

    assertEquals("branchName", testCase.getBranchName());
}
 
Example 2
@Test
public void testGetCommitSha() {
    AnalysisDetails.BranchDetails branchDetails = mock(AnalysisDetails.BranchDetails.class);
    doReturn("commitId").when(branchDetails).getCommitId();

    AnalysisDetails.MeasuresHolder measuresHolder = mock(AnalysisDetails.MeasuresHolder.class);
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    QualityGate qualityGate = mock(QualityGate.class);
    Analysis analysis = mock(Analysis.class);
    Project project = mock(Project.class);
    ScannerContext scannerContext = mock(ScannerContext.class);
    Configuration configuration = mock(Configuration.class);

    AnalysisDetails testCase =
            new AnalysisDetails(branchDetails, postAnalysisIssueVisitor, qualityGate, measuresHolder, analysis,
                                project, configuration, null, scannerContext);

    assertEquals("commitId", testCase.getCommitSha());
}
 
Example 3
@Test
public void testGetQualityGateStatus() {
    AnalysisDetails.BranchDetails branchDetails = mock(AnalysisDetails.BranchDetails.class);
    AnalysisDetails.MeasuresHolder measuresHolder = mock(AnalysisDetails.MeasuresHolder.class);
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    QualityGate qualityGate = mock(QualityGate.class);
    doReturn(QualityGate.Status.ERROR).when(qualityGate).getStatus();
    Analysis analysis = mock(Analysis.class);
    Project project = mock(Project.class);
    ScannerContext scannerContext = mock(ScannerContext.class);
    Configuration configuration = mock(Configuration.class);

    AnalysisDetails testCase =
            new AnalysisDetails(branchDetails, postAnalysisIssueVisitor, qualityGate, measuresHolder, analysis,
                                project, configuration, null, scannerContext);

    assertEquals(QualityGate.Status.ERROR, testCase.getQualityGateStatus());
}
 
Example 4
@Test
public void testGetAnalysisDate() {
    AnalysisDetails.BranchDetails branchDetails = mock(AnalysisDetails.BranchDetails.class);
    AnalysisDetails.MeasuresHolder measuresHolder = mock(AnalysisDetails.MeasuresHolder.class);
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    QualityGate qualityGate = mock(QualityGate.class);
    Analysis analysis = mock(Analysis.class);
    doReturn(new Date()).when(analysis).getDate();
    Project project = mock(Project.class);
    ScannerContext scannerContext = mock(ScannerContext.class);
    Configuration configuration = mock(Configuration.class);

    AnalysisDetails testCase =
            new AnalysisDetails(branchDetails, postAnalysisIssueVisitor, qualityGate, measuresHolder, analysis,
                                project, configuration, null, scannerContext);

    assertEquals(analysis.getDate(), testCase.getAnalysisDate());
}
 
Example 5
@Test
public void testGetAnalysisId() {
    AnalysisDetails.BranchDetails branchDetails = mock(AnalysisDetails.BranchDetails.class);
    AnalysisDetails.MeasuresHolder measuresHolder = mock(AnalysisDetails.MeasuresHolder.class);
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    QualityGate qualityGate = mock(QualityGate.class);
    Analysis analysis = mock(Analysis.class);
    doReturn("Analysis ID").when(analysis).getAnalysisUuid();
    Project project = mock(Project.class);
    ScannerContext scannerContext = mock(ScannerContext.class);
    Configuration configuration = mock(Configuration.class);

    AnalysisDetails testCase =
            new AnalysisDetails(branchDetails, postAnalysisIssueVisitor, qualityGate, measuresHolder, analysis,
                                project, configuration, null, scannerContext);

    assertEquals("Analysis ID", testCase.getAnalysisId());
}
 
Example 6
@Test
public void testGetAnalysisProjectKey() {
    AnalysisDetails.BranchDetails branchDetails = mock(AnalysisDetails.BranchDetails.class);
    AnalysisDetails.MeasuresHolder measuresHolder = mock(AnalysisDetails.MeasuresHolder.class);
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    QualityGate qualityGate = mock(QualityGate.class);
    Analysis analysis = mock(Analysis.class);
    Project project = mock(Project.class);
    doReturn("Project Key").when(project).getKey();
    ScannerContext scannerContext = mock(ScannerContext.class);
    Configuration configuration = mock(Configuration.class);

    AnalysisDetails testCase =
            new AnalysisDetails(branchDetails, postAnalysisIssueVisitor, qualityGate, measuresHolder, analysis,
                                project, configuration, null, scannerContext);

    assertEquals("Project Key", testCase.getAnalysisProjectKey());
}
 
Example 7
@Test
public void testDefineInvokedOnSuccessLoad() throws ClassNotFoundException {
    Plugin.Context context = spy(mock(Plugin.Context.class));
    Configuration configuration = mock(Configuration.class);
    when(context.getBootConfiguration()).thenReturn(configuration);
    when(configuration.get(any())).thenReturn(Optional.empty());
    SonarRuntime sonarRuntime = mock(SonarRuntime.class);
    when(context.getRuntime()).thenReturn(sonarRuntime);
    when(sonarRuntime.getSonarQubeSide()).thenReturn(SonarQubeSide.SCANNER);

    ClassLoader classLoader = mock(ClassLoader.class);
    when(classLoader.loadClass(any())).thenReturn((Class) MockPlugin.class);

    ElevatedClassLoaderFactory elevatedClassLoaderFactory = mock(ElevatedClassLoaderFactory.class);
    when(elevatedClassLoaderFactory.createClassLoader(any())).thenReturn(classLoader);

    ElevatedClassLoaderFactoryProvider elevatedClassLoaderFactoryProvider =
            mock(ElevatedClassLoaderFactoryProvider.class);
    when(elevatedClassLoaderFactoryProvider.createFactory(any())).thenReturn(elevatedClassLoaderFactory);

    CommunityBranchPluginBootstrap testCase =
            new CommunityBranchPluginBootstrap(elevatedClassLoaderFactoryProvider);
    testCase.define(context);

    assertEquals(context, MockPlugin.invokedContext);
}
 
Example 8
@Test
public void testDefineNotInvokedForNonScanner() throws ClassNotFoundException {
    Plugin.Context context = spy(mock(Plugin.Context.class));
    Configuration configuration = mock(Configuration.class);
    when(context.getBootConfiguration()).thenReturn(configuration);
    when(configuration.get(any())).thenReturn(Optional.empty());
    SonarRuntime sonarRuntime = mock(SonarRuntime.class);
    when(context.getRuntime()).thenReturn(sonarRuntime);
    when(sonarRuntime.getSonarQubeSide()).thenReturn(SonarQubeSide.SERVER);

    ClassLoader classLoader = mock(ClassLoader.class);
    when(classLoader.loadClass(any())).thenReturn((Class) MockPlugin.class);

    ElevatedClassLoaderFactory elevatedClassLoaderFactory = mock(ElevatedClassLoaderFactory.class);
    when(elevatedClassLoaderFactory.createClassLoader(any())).thenReturn(classLoader);

    ElevatedClassLoaderFactoryProvider elevatedClassLoaderFactoryProvider =
            mock(ElevatedClassLoaderFactoryProvider.class);
    when(elevatedClassLoaderFactoryProvider.createFactory(any())).thenReturn(elevatedClassLoaderFactory);

    CommunityBranchPluginBootstrap testCase =
            new CommunityBranchPluginBootstrap(elevatedClassLoaderFactoryProvider);
    testCase.define(context);

    assertNull(MockPlugin.invokedContext);
}
 
Example 9
@Test
public void qualifiedNameCheckValid() {
  Configuration cfg = mock(Configuration.class);
  Mockito.when(cfg.get(QualifiedNameCheck.QUALIFIED_NAME_KEY)).thenReturn(Optional.of(QualifiedNameCheck.QUALIFIED_NAME_DEFVALUE));
  FlowLanguage.setConfig(cfg);
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  QualifiedNameCheck qnc = new QualifiedNameCheck();
  checks.add(qnc);
  String validPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkQualityNameInvalid/flow.xml";

  SourceFile sfCorrect = FlowAstScanner.scanSingleFile(new File(validPath), checks, metrics);
  Set<CheckMessage> scmCorrect = sfCorrect.getCheckMessages();
  assertEquals(0, scmCorrect.size());  
}
 
Example 10
@Test
public void qualifiedNameCheckInvalid() {
  Configuration cfg = mock(Configuration.class);
  Mockito.when(cfg.get(QualifiedNameCheck.QUALIFIED_NAME_KEY)).thenReturn(Optional.of("test.*"));
  FlowLanguage.setConfig(cfg);
  List<SquidAstVisitor<Grammar>> metrics = new ArrayList<SquidAstVisitor<Grammar>>();
  metrics.add(new SimpleMetricVisitor());
  List<FlowCheck> checks = new ArrayList<FlowCheck>();
  QualifiedNameCheck qnc = new QualifiedNameCheck();
  checks.add(qnc);
  String validPath = "src/test/resources/WmTestPackage/ns/I8cFlowSonarPluginTest"
      + "/pub/checkQualityNameInvalid/flow.xml";

  SourceFile sfCorrect = FlowAstScanner.scanSingleFile(new File(validPath), checks, metrics);
  Set<CheckMessage> scmCorrect = sfCorrect.getCheckMessages();
  assertEquals(1, scmCorrect.size());  
}
 
Example 11
Source Project: sonar-clover   Source File: CloverSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_process_file() throws Exception {
  final String cloverFilePath = "org/sonar/plugins/clover/CloverXmlReportParserTest/clover_2_6_0.xml";
  final File cloverFile = TestUtils.getResource(cloverFilePath);
  final MapSettings settings = new MapSettings();
  settings.setProperty(CloverSensor.REPORT_PATH_PROPERTY, cloverFile.getAbsolutePath());

  final DefaultFileSystem fs = context.fileSystem();
  fs.add(new TestInputFileBuilder("", cloverFile.getAbsolutePath()).build());

  final Configuration configuration = new ConfigurationBridge(settings);
  final CloverSensor sensor = new CloverSensor(configuration, fs, new PathResolver());

  sensor.execute(context);

  assertThat(logTester.logs(LoggerLevel.INFO)).contains("Parsing " + cloverFile.getCanonicalPath());
  assertThat(logTester.logs(LoggerLevel.WARN).stream().anyMatch(s -> s.contains("14 files in Clover report did not match any file in SonarQube Index"))).isEqualTo(true);
}
 
Example 12
AnalysisDetails(BranchDetails branchDetails, PostAnalysisIssueVisitor postAnalysisIssueVisitor,
                QualityGate qualityGate, MeasuresHolder measuresHolder, Analysis analysis, Project project,
                Configuration configuration, String publicRootURL, ScannerContext scannerContext) {
    super();
    this.publicRootURL = publicRootURL;
    this.branchDetails = branchDetails;
    this.measuresHolder = measuresHolder;
    this.postAnalysisIssueVisitor = postAnalysisIssueVisitor;
    this.qualityGate = qualityGate;
    this.analysis = analysis;
    this.project = project;
    this.scannerContext = scannerContext;
    this.configuration = configuration;
}
 
Example 13
public PullRequestPostAnalysisTask(Server server,
                                   List<PullRequestBuildStatusDecorator> pullRequestDecorators,
                                   PostAnalysisIssueVisitor postAnalysisIssueVisitor,
                                   MetricRepository metricRepository, MeasureRepository measureRepository,
                                   TreeRootHolder treeRootHolder, Configuration configuration, DbClient dbClient) {
    super();
    this.server = server;
    this.pullRequestDecorators = pullRequestDecorators;
    this.postAnalysisIssueVisitor = postAnalysisIssueVisitor;
    this.metricRepository = metricRepository;
    this.measureRepository = measureRepository;
    this.treeRootHolder = treeRootHolder;
    this.configuration = configuration;
    this.dbClient = dbClient;
}
 
Example 14
@Test
public void testCorrectPostAnalysisIssueVisitorReturned() {
    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    AnalysisDetails analysisDetails =
            new AnalysisDetails(mock(AnalysisDetails.BranchDetails.class), postAnalysisIssueVisitor,
                                mock(QualityGate.class), mock(AnalysisDetails.MeasuresHolder.class),
                                mock(Analysis.class), mock(Project.class), mock(Configuration.class), null,
                                mock(ScannerContext.class));
    assertSame(postAnalysisIssueVisitor, analysisDetails.getPostAnalysisIssueVisitor());
}
 
Example 15
@Test
public void testGetBaseImageUrlFromConfig() {
    Configuration configuration = mock(Configuration.class);
    doReturn(Optional.of("http://host.name/path")).when(configuration)
            .get(eq(CommunityBranchPlugin.IMAGE_URL_BASE));

    AnalysisDetails analysisDetails =
            new AnalysisDetails(mock(AnalysisDetails.BranchDetails.class), mock(PostAnalysisIssueVisitor.class),
                    mock(QualityGate.class), mock(AnalysisDetails.MeasuresHolder.class),
                    mock(Analysis.class), mock(Project.class), configuration, "http://localhost:9000", mock(ScannerContext.class));

    assertEquals("http://host.name/path", analysisDetails.getBaseImageUrl());
}
 
Example 16
@Test
public void testGetBaseImageUrlFromConfigWithTrailingSlash() {
    Configuration configuration = mock(Configuration.class);
    doReturn(Optional.of("http://host.name/path/")).when(configuration)
            .get(eq(CommunityBranchPlugin.IMAGE_URL_BASE));

    AnalysisDetails analysisDetails =
            new AnalysisDetails(mock(AnalysisDetails.BranchDetails.class), mock(PostAnalysisIssueVisitor.class),
                    mock(QualityGate.class), mock(AnalysisDetails.MeasuresHolder.class),
                    mock(Analysis.class), mock(Project.class), configuration, "http://localhost:9000", mock(ScannerContext.class));

    assertEquals("http://host.name/path", analysisDetails.getBaseImageUrl());
}
 
Example 17
@Test
public void testGetBaseImageUrlFromRootUrl() {
    AnalysisDetails analysisDetails =
            new AnalysisDetails(mock(AnalysisDetails.BranchDetails.class), mock(PostAnalysisIssueVisitor.class),
                    mock(QualityGate.class), mock(AnalysisDetails.MeasuresHolder.class),
                    mock(Analysis.class), mock(Project.class), mock(Configuration.class), "http://localhost:9000", mock(ScannerContext.class));

    assertEquals("http://localhost:9000/static/communityBranchPlugin", analysisDetails.getBaseImageUrl());
}
 
Example 18
@Test
public void testReflectiveTypeMatched() {
    Plugin.Context context = mock(Plugin.Context.class);
    Configuration configuration = mock(Configuration.class);
    when(context.getBootConfiguration()).thenReturn(configuration);

    assertTrue(ProviderType.fromName("REFLECTIVE")
                       .createFactory(context) instanceof ReflectiveElevatedClassLoaderFactory);
}
 
Example 19
@Test
public void testClassReferenceTypeMatched() {
    Plugin.Context context = mock(Plugin.Context.class);
    Configuration configuration = mock(Configuration.class);
    when(context.getBootConfiguration()).thenReturn(configuration);

    assertTrue(ProviderType.fromName("CLASS_REFERENCE")
                       .createFactory(context) instanceof ClassReferenceElevatedClassLoaderFactory);
}
 
Example 20
@Test
public void validFactoryReturnedOnNoPropertiesSet() {
    Plugin.Context context = mock(Plugin.Context.class);
    Configuration configuration = mock(Configuration.class);
    when(context.getBootConfiguration()).thenReturn(configuration);
    when(configuration.get(any())).thenReturn(Optional.empty());

    assertTrue(DefaultElevatedClassLoaderFactoryProvider.getInstance()
                       .createFactory(context) instanceof ClassReferenceElevatedClassLoaderFactory);
}
 
Example 21
public LicenseSettingsService(PersistentSettings persistentSettings, Configuration configuration, LicenseService licenseService)
{
    super();
    this.persistentSettings = persistentSettings;
    this.configuration = configuration;
    this.licenseService = licenseService;

    initSpdxLicences();
}
 
Example 22
Source Project: sonarqube-licensecheck   Source File: LicenseCheckSensor.java    License: Apache License 2.0 5 votes vote down vote up
public LicenseCheckSensor(FileSystem fs, Configuration configuration, ValidateLicenses validateLicenses,
    MavenLicenseService mavenLicenseService, MavenDependencyService mavenDependencyService)
{
    this.fs = fs;
    this.configuration = configuration;
    this.validateLicenses = validateLicenses;
    this.scanners = new Scanner[]{
        new PackageJsonDependencyScanner(
            configuration.getBoolean(LicenseCheckPropertyKeys.NPM_RESOLVE_TRANSITIVE_DEPS).orElse(false)),
        new MavenDependencyScanner(mavenLicenseService, mavenDependencyService)};
}
 
Example 23
public MavenLicenseSettingsService(PersistentSettings persistentSettings, Configuration configuration,
    MavenLicenseService mavenLicenseService)
{
    super();
    this.persistentSettings = persistentSettings;
    this.configuration = configuration;
    this.mavenLicenseService = mavenLicenseService;
    initMavenLicenses();
}
 
Example 24
/**
 * Main Constructor. Parameters are injected.
 * 
 * @param config
 *          Configuration
 * @param checkFactory
 *          Checkfactory
 * @param fileSystem
 *          Filesystem
 * @param pathResolver
 *          Pathresolver
 */
public FlowSquidSensor(Configuration config, CheckFactory checkFactory, FileSystem fileSystem,
    PathResolver pathResolver) {
  logger.debug("** FlowSquidSenser constructor");
  this.fileSystem = fileSystem;
  this.config = config;
  this.pathResolver = pathResolver;
  this.flowChecks = checkFactory.<FlowCheck>create(FlowRulesDefinition.REPO_KEY)
      .addAnnotatedChecks(CheckList.getFlowChecks().toArray()).addAnnotatedChecks(
          config.getBoolean(FlowLanguageProperties.IGNORE_TOPLEVEL_KEY).get() ? null
              : CheckList.getTopLevelChecks().toArray());
  this.nodeChecks = checkFactory.<FlowCheck>create(FlowRulesDefinition.REPO_KEY)
      .addAnnotatedChecks(CheckList.getNodeChecks().toArray());
}
 
Example 25
public CandidateRule[] getChecks(final SensorContext context) {
	final Configuration config = context.config();
	final boolean skipCustomRules = config.getBoolean(Constants.PLUGIN_SKIP_CUSTOM_RULES).orElse(false);
	final String baseDir = context.fileSystem().baseDir().getAbsolutePath();

	final String[] paths = config.getStringArray(Constants.PLUGIN_CUSTOM_RULES_PATH);
	final String rulesPrefix = config.get(Constants.PLUGIN_CUSTOM_RULES_PREFIX).orElse(".customRules");

	final List<SqlRules> rules = new ArrayList<>();

	rules.addAll(provider.getRules(baseDir, rulesPrefix, paths).values());

	if (!skipCustomRules) {
		final SqlRules customRules = pluginChecksProvider.getRules();
		rules.add(customRules);
	}

	for (final SqlRules sqlRules : rules) {
		if (sqlRules.isIsAdhoc()) {
			for (final Rule r : sqlRules.getRule()) {
				context.newAdHocRule().description(r.getDescription()).engineId(sqlRules.getRepoKey())
						.ruleId(r.getKey()).type(RuleType.valueOf(r.getRuleType())).name(r.getName())
						.severity(Severity.valueOf(r.getSeverity())).save();
			}
		}
	}

	final SqlRules[] finalRules = rules.toArray(new SqlRules[0]);

	final CandidateRule[] candidateRules = convert(finalRules);
	LOGGER.info(String.format("Total %s custom rules repositories with total %s checks", rules.size(),
			candidateRules.length));
	return candidateRules;

}
 
Example 26
public static FilePredicate createFilePredicate(Configuration configuration, SensorContext sensorContext) {
    FilePredicates predicates = sensorContext.fileSystem().predicates();

    List<FilePredicate> fileExtensions = getFileExtensionsPredicates(predicates, configuration);
    List<FilePredicate> relativePaths = getPathsPredicate(predicates, configuration);

    return predicates.and(
            predicates.hasType(InputFile.Type.MAIN),
            predicates.or(
                    predicates.hasLanguages(Htl.KEY),
                    predicates.or(fileExtensions)
            ),
            predicates.or(relativePaths)
    );
}
 
Example 27
private static List<FilePredicate> getFileExtensionsPredicates(FilePredicates predicates, Configuration configuration) {
    return Stream.of(configuration.getStringArray(Constants.FILE_EXTENSIONS_PROP_KEY))
            .filter(Objects::nonNull)
            .map(extension -> StringUtils.removeStart(extension, "."))
            .map(predicates::hasExtension)
            .collect(Collectors.toList());
}
 
Example 28
private static List<FilePredicate> getPathsPredicate(FilePredicates predicates, Configuration configuration) {
    return Stream.of(configuration.getStringArray(Constants.HTL_FILES_RELATIVE_PATHS_KEY))
            .filter(StringUtils::isNotEmpty)
            .map(path -> StringUtils.wrapIfMissing(path, "**"))
            .map(predicates::matchesPathPattern)
            .collect(Collectors.toList());
}
 
Example 29
Source Project: AEM-Rules-for-SonarQube   Source File: HtlSensorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    RulesDefinition rulesDefinition = new AemRulesRulesDefinition();
    RulesDefinition.Context context = new RulesDefinition.Context();
    rulesDefinition.define(context);
    RulesDefinition.Repository htlRepository = context.repository(HtlCheckClasses.REPOSITORY_KEY);

    FileLinesContextFactory fileLinesContextFactory = getMockedFileLinesContextFactory();
    Configuration configuration = getMockedConfiguration();
    CheckFactory checkFactory = getCheckFactory(htlRepository);

    sensor = new HtlSensor(fileLinesContextFactory, configuration, checkFactory);
    tester = SensorContextTester.create(TEST_DIR);
}
 
Example 30
Source Project: sonar-esql-plugin   Source File: SymbolModelImpl.java    License: Apache License 2.0 5 votes vote down vote up
public static void build(TreeVisitorContext context,  @Nullable Configuration configuration) {
  Map<Tree, Scope> treeScopeMap = getScopes(context);

  new HoistedSymbolVisitor(treeScopeMap).scanTree(context);
  new SymbolVisitor(treeScopeMap).scanTree(context);
  new TypeVisitor(configuration).scanTree(context);
}