Search in sources :

Example 26 with AnalyzerMessage

use of org.sonar.java.reporting.AnalyzerMessage in project sonar-java by SonarSource.

the class DefaultJavaFileScannerContext method completeAnalyzerMessageWithFlows.

private static <L> void completeAnalyzerMessageWithFlows(AnalyzerMessage analyzerMessage, Iterable<List<L>> flows, Function<L, AnalyzerMessage.TextSpan> flowItemLocationProdivder, Function<L, String> flowItemMessageProvider) {
    JavaCheck check = analyzerMessage.getCheck();
    InputComponent component = analyzerMessage.getInputComponent();
    for (List<L> flow : flows) {
        List<AnalyzerMessage> sonarqubeFlow = flow.stream().map(l -> new AnalyzerMessage(check, component, flowItemLocationProdivder.apply(l), flowItemMessageProvider.apply(l), 0)).collect(Collectors.toList());
        analyzerMessage.flows.add(sonarqubeFlow);
    }
}
Also used : InputFile(org.sonar.api.batch.fs.InputFile) FluentReporting(org.sonar.java.reporting.FluentReporting) EndOfAnalysis(org.sonar.plugins.java.api.internal.EndOfAnalysis) RegexParseResult(org.sonarsource.analyzer.commons.regex.RegexParseResult) RegexScannerContext(org.sonar.java.regex.RegexScannerContext) ComplexityVisitor(org.sonar.java.ast.visitors.ComplexityVisitor) CompilationUnitTree(org.sonar.plugins.java.api.tree.CompilationUnitTree) Function(java.util.function.Function) FlagSet(org.sonarsource.analyzer.commons.regex.ast.FlagSet) ArrayList(java.util.ArrayList) InternalJavaIssueBuilder(org.sonar.java.reporting.InternalJavaIssueBuilder) RegexSyntaxElement(org.sonarsource.analyzer.commons.regex.ast.RegexSyntaxElement) JavaCheck(org.sonar.plugins.java.api.JavaCheck) SonarComponents(org.sonar.java.SonarComponents) Nullable(javax.annotation.Nullable) LiteralTree(org.sonar.plugins.java.api.tree.LiteralTree) InputComponent(org.sonar.api.batch.fs.InputComponent) AnalyzerMessage(org.sonar.java.reporting.AnalyzerMessage) Tree(org.sonar.plugins.java.api.tree.Tree) Collectors(java.util.stream.Collectors) JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) SourceMap(org.sonar.plugins.java.api.SourceMap) CacheContext(org.sonar.plugins.java.api.caching.CacheContext) RegexCache(org.sonar.java.regex.RegexCache) List(java.util.List) JavaVersion(org.sonar.plugins.java.api.JavaVersion) RegexCheck(org.sonar.java.regex.RegexCheck) Optional(java.util.Optional) Collections(java.util.Collections) InputComponent(org.sonar.api.batch.fs.InputComponent) JavaCheck(org.sonar.plugins.java.api.JavaCheck) AnalyzerMessage(org.sonar.java.reporting.AnalyzerMessage)

Example 27 with AnalyzerMessage

use of org.sonar.java.reporting.AnalyzerMessage in project sonar-java by SonarSource.

the class FilterVerifier method verify.

public static void verify(String filename, JavaIssueFilter filter, JavaCheck... extraJavaChecks) {
    IssueCollector issueCollector = new IssueCollector();
    List<JavaCheck> visitors = new ArrayList<>();
    visitors.add(filter);
    visitors.add(issueCollector);
    // instantiate the rules filtered by the filter
    visitors.addAll(instantiateRules(filter.filteredRules()));
    visitors.addAll(Arrays.asList(extraJavaChecks));
    Collection<File> classpath = FileUtils.listFiles(new File(FilesUtils.DEFAULT_TEST_JARS_DIRECTORY), new String[] { "jar", "zip" }, true);
    List<File> projectClasspath = new ArrayList<>(classpath);
    projectClasspath.add(new File("target/test-classes"));
    InputFile inputFile = TestUtils.inputFile(filename);
    VisitorsBridgeForTests visitorsBridge = new VisitorsBridgeForTests(visitors, projectClasspath, sonarComponents(inputFile), new JavaVersionImpl());
    JavaAstScanner.scanSingleFileForTests(inputFile, visitorsBridge);
    JavaFileScannerContextForTests testJavaFileScannerContext = visitorsBridge.lastCreatedTestContext();
    Map<Integer, Set<String>> issuesByLines = new HashMap<>();
    Set<AnalyzerMessage> issues = testJavaFileScannerContext.getIssues();
    for (AnalyzerMessage analyzerMessage : issues) {
        Integer issueLine = analyzerMessage.getLine();
        String ruleKey = AnnotationUtils.getAnnotation(analyzerMessage.getCheck().getClass(), Rule.class).key();
        FilterableIssue issue = mock(FilterableIssue.class);
        when(issue.ruleKey()).thenReturn(RuleKey.of("java", ruleKey));
        when(issue.componentKey()).thenReturn(inputFile.key());
        when(issue.line()).thenReturn(issueLine);
        if (issueCollector.rejectedIssuesLines.contains(issueLine)) {
            assertThat(filter.accept(issue)).overridingErrorMessage("Line #" + issueLine + " has been marked with 'NoIssue' but issue of rule '" + ruleKey + "' has been accepted!").isFalse();
        } else if (issueCollector.acceptedIssuesLines.contains(issueLine)) {
            // force check on accepted issues
            assertThat(filter.accept(issue)).overridingErrorMessage("Line #" + issueLine + " has been marked with 'WithIssue' but no issue have been raised!").isTrue();
        } else {
            issuesByLines.computeIfAbsent(issueLine, k -> new HashSet<>()).add(ruleKey);
        }
    }
    if (!issuesByLines.isEmpty()) {
        List<Integer> lines = new ArrayList<>(issuesByLines.keySet());
        Collections.sort(lines);
        StringBuilder builder = new StringBuilder();
        for (Integer line : lines) {
            builder.append("\n#" + line + ": " + issuesByLines.get(line).toString());
        }
        Fail.fail("The following lines have not been marked with 'WithIssue' or 'NoIssue' and raised issues:" + builder.toString());
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) JavaCheck(org.sonar.plugins.java.api.JavaCheck) FilterableIssue(org.sonar.api.scan.issue.filter.FilterableIssue) ArrayList(java.util.ArrayList) InputFile(org.sonar.api.batch.fs.InputFile) VisitorsBridgeForTests(org.sonar.java.testing.VisitorsBridgeForTests) JavaVersionImpl(org.sonar.java.model.JavaVersionImpl) JavaFileScannerContextForTests(org.sonar.java.testing.JavaFileScannerContextForTests) AnalyzerMessage(org.sonar.java.reporting.AnalyzerMessage) Rule(org.sonar.check.Rule) InputFile(org.sonar.api.batch.fs.InputFile) File(java.io.File)

Example 28 with AnalyzerMessage

use of org.sonar.java.reporting.AnalyzerMessage in project sonar-java by SonarSource.

the class SonarComponents method reportIssue.

@VisibleForTesting
void reportIssue(AnalyzerMessage analyzerMessage, RuleKey key, InputComponent fileOrProject, @Nullable Double cost) {
    Objects.requireNonNull(context);
    JavaIssue issue = JavaIssue.create(context, key, cost);
    AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation();
    if (textSpan == null) {
        // either an issue at file or project level
        issue.setPrimaryLocationOnComponent(fileOrProject, analyzerMessage.getMessage());
    } else {
        if (!textSpan.onLine()) {
            Preconditions.checkState(!textSpan.isEmpty(), "Issue location should not be empty");
        }
        issue.setPrimaryLocation((InputFile) fileOrProject, analyzerMessage.getMessage(), textSpan.startLine, textSpan.startCharacter, textSpan.endLine, textSpan.endCharacter);
    }
    if (!analyzerMessage.flows.isEmpty()) {
        issue.addFlow((InputFile) analyzerMessage.getInputComponent(), analyzerMessage.flows);
    }
    issue.save();
}
Also used : AnalyzerMessage(org.sonar.java.reporting.AnalyzerMessage) JavaIssue(org.sonar.java.reporting.JavaIssue) VisibleForTesting(org.sonar.java.annotations.VisibleForTesting)

Example 29 with AnalyzerMessage

use of org.sonar.java.reporting.AnalyzerMessage in project sonar-java by SonarSource.

the class InternalCheckVerifier method validateLocation.

private static void validateLocation(AnalyzerMessage analyzerMessage, Map<Expectations.IssueAttribute, Object> attrs) {
    AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation();
    Objects.requireNonNull(textSpan);
    assertAttributeMatch(analyzerMessage, normalizeColumn(textSpan.startCharacter), attrs, START_COLUMN);
    assertAttributeMatch(analyzerMessage, textSpan.endLine, attrs, END_LINE);
    assertAttributeMatch(analyzerMessage, normalizeColumn(textSpan.endCharacter), attrs, END_COLUMN);
}
Also used : AnalyzerMessage(org.sonar.java.reporting.AnalyzerMessage) TextSpan(org.sonar.java.reporting.AnalyzerMessage.TextSpan)

Example 30 with AnalyzerMessage

use of org.sonar.java.reporting.AnalyzerMessage in project sonar-java by SonarSource.

the class InternalCheckVerifier method validateFlowAttributes.

private void validateFlowAttributes(List<AnalyzerMessage> actual, String flowId) {
    SortedSet<Expectations.FlowComment> expected = expectations.flows.get(flowId);
    validateFlowMessages(actual, flowId, expected);
    Iterator<AnalyzerMessage> actualIterator = actual.iterator();
    Iterator<Expectations.FlowComment> expectedIterator = expected.iterator();
    while (actualIterator.hasNext() && expectedIterator.hasNext()) {
        AnalyzerMessage actualFlow = actualIterator.next();
        if (actualFlow.primaryLocation() == null) {
            throw new AssertionError(String.format("Flow without location: %s", actualFlow));
        }
        validateLocation(actualFlow, expectedIterator.next().attributes);
    }
}
Also used : AnalyzerMessage(org.sonar.java.reporting.AnalyzerMessage)

Aggregations

AnalyzerMessage (org.sonar.java.reporting.AnalyzerMessage)30 Test (org.junit.jupiter.api.Test)11 InputFile (org.sonar.api.batch.fs.InputFile)10 ArrayList (java.util.ArrayList)9 List (java.util.List)8 JavaFileScannerContext (org.sonar.plugins.java.api.JavaFileScannerContext)8 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 JavaCheck (org.sonar.plugins.java.api.JavaCheck)7 SonarComponents (org.sonar.java.SonarComponents)6 Tree (org.sonar.plugins.java.api.tree.Tree)5 File (java.io.File)4 Collections (java.util.Collections)4 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4 VisitorsBridgeForTests (org.sonar.java.testing.VisitorsBridgeForTests)4 HashSet (java.util.HashSet)3 Optional (java.util.Optional)3 ValueSource (org.junit.jupiter.params.provider.ValueSource)3 InputComponent (org.sonar.api.batch.fs.InputComponent)3 SensorContextTester (org.sonar.api.batch.sensor.internal.SensorContextTester)3