Skip to content

Commit

Permalink
Fix Quality Flaws S6204: Replace '.collect(Collectors.toList())' with…
Browse files Browse the repository at this point in the history
… '.toList()' (#4662)
  • Loading branch information
alban-auzeill committed Feb 19, 2024
1 parent 7cdd1f2 commit 5cdb018
Show file tree
Hide file tree
Showing 163 changed files with 335 additions and 476 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,13 @@ public void javaCheckTestSources() throws Exception {
newTotal.falsePositives,
newTotal.falsePositives + newTotal.falseNegatives);

List<IssueDiff> rulesCausingFPs = newDiffs.stream().filter(IssueDiff::causesFPs).collect(Collectors.toList());
List<IssueDiff> rulesCausingFPs = newDiffs.stream().filter(IssueDiff::causesFPs).toList();
LOG.info("{} rules causing FPs:\n{}", rulesCausingFPs.size(), IssueDiff.prettyPrint(rulesCausingFPs));

List<IssueDiff> rulesNotReporting = newDiffs.stream().filter(IssueDiff::notReporting).collect(Collectors.toList());
List<IssueDiff> rulesNotReporting = newDiffs.stream().filter(IssueDiff::notReporting).toList();
LOG.info("{} rules never reporting anything:\n{}", rulesNotReporting.size(), IssueDiff.prettyPrint(rulesNotReporting));

List<IssueDiff> rulesSilenced = newDiffs.stream().filter(IssueDiff::onlyFNs).collect(Collectors.toList());
List<IssueDiff> rulesSilenced = newDiffs.stream().filter(IssueDiff::onlyFNs).toList();
LOG.info("{} rules silenced without binaries (only FNs):\n{}", rulesSilenced.size(), IssueDiff.prettyPrint(rulesSilenced));

// Load known diffs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import com.sonar.orchestrator.build.MavenBuild;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.ClassRule;
import org.junit.Test;
import org.sonarqube.ws.Common.Severity;
Expand Down Expand Up @@ -97,7 +96,7 @@ private List<Issue> getExternalIssues(String projectKey) {
return TestUtils.issuesForComponent(orchestrator, projectKey)
.stream()
.filter(issue -> issue.getRule().startsWith("external_"))
.collect(Collectors.toList());
.toList();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import com.sonar.orchestrator.build.MavenBuild;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.junit.ClassRule;
import org.junit.Test;
import org.sonarqube.ws.Issues.Issue;
Expand Down Expand Up @@ -55,11 +54,11 @@ public void should_detect_package_info_issues() {
assertThat(issues.stream().map(Issue::getLine)).allMatch(line -> line == 0);

Pattern packagePattern = Pattern.compile("'org\\.package[12]'");
List<Issue> s1228Issues = issues.stream().filter(issue -> issue.getRule().equals("java:S1228")).collect(Collectors.toList());
List<Issue> s1228Issues = issues.stream().filter(issue -> issue.getRule().equals("java:S1228")).toList();
assertThat(s1228Issues).hasSize(2);
assertThat(s1228Issues).extracting(Issue::getMessage).allMatch(msg -> packagePattern.matcher(msg).find());

List<Issue> s4032Issues = issues.stream().filter(issue -> issue.getRule().equals("java:S4032")).collect(Collectors.toList());
List<Issue> s4032Issues = issues.stream().filter(issue -> issue.getRule().equals("java:S4032")).toList();
assertThat(s4032Issues).hasSize(1);
assertThat(s4032Issues.get(0).getMessage()).isEqualTo("Remove this package.");
assertThat(s4032Issues.get(0).getComponent()).isEqualTo(projectKey + ":src/main/other-src/org/package4/package-info.java");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.check.Rule;
import org.sonar.java.checks.helpers.ExpressionsHelper;
import org.sonar.java.model.ExpressionUtils;
Expand Down Expand Up @@ -86,7 +85,7 @@ private static Optional<String> getSyncCalls(MethodInvocationTree tree) {
// We know there is at least one usage, i.e. the one we just got above.
List<IdentifierTree> localUsages = invokeRequest.symbol().usages().stream()
.filter(u -> u.symbol().isLocalVariable() && !u.equals(invokeRequest))
.collect(Collectors.toList());
.toList();

if (invokeRequest.symbol().isParameter()
|| localUsages.stream().anyMatch(lu -> isArgumentToACall(lu) || statementSetsAsyncCall(lu))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@


import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.event.Level;
Expand All @@ -44,7 +43,7 @@ void uses_empty_collection_when_methods_cannot_be_loaded() {
assertThat(check.getMethods()).isEmpty();
List<String> logs = logTester.getLogs(Level.ERROR).stream()
.map(LogAndArguments::getFormattedMsg)
.collect(Collectors.toList());
.toList();
assertThat(logs)
.containsOnly("Could not load methods from \"non-existing-file.json\".");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.java.annotations.VisibleForTesting;

public final class FilesUtils {
Expand Down Expand Up @@ -74,6 +73,6 @@ public FileVisitResult visitFileFailed(Path file, IOException exc) {
// we already ignore errors in the visitor
}

return files.stream().sorted().collect(Collectors.toList());
return files.stream().sorted().toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@
import org.sonarsource.analyzer.commons.collections.MapBuilder;

import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.sonar.java.checks.verifier.internal.Expectations.IssueAttribute.EFFORT_TO_FIX;
import static org.sonar.java.checks.verifier.internal.Expectations.IssueAttribute.END_COLUMN;
import static org.sonar.java.checks.verifier.internal.Expectations.IssueAttribute.END_LINE;
Expand Down Expand Up @@ -124,7 +123,9 @@ enum IssueAttribute {
}

private static <T> Function<String, List<T>> multiValueAttribute(Function<String, T> convert) {
return (String input) -> isNullOrEmpty(input) ? Collections.emptyList() : Arrays.stream(input.split(",")).map(String::trim).map(convert).collect(toList());
return (String input) -> isNullOrEmpty(input) ?
Collections.emptyList() :
Arrays.stream(input.split(",")).map(String::trim).map(convert).collect(Collectors.toCollection(ArrayList::new));
}

private static boolean isNullOrEmpty(@Nullable String input) {
Expand Down Expand Up @@ -309,14 +310,14 @@ Optional<String> containFlow(List<AnalyzerMessage> actual) {
return Optional.of(flowId);
}
// more than 1 flow with same lines, let's check messages
List<String> actualMessages = actual.stream().map(AnalyzerMessage::getMessage).collect(toList());
List<String> actualMessages = actual.stream().map(AnalyzerMessage::getMessage).toList();
Optional<String> foundFlow = expectedFlows.stream().filter(flowId -> hasSameMessages(flowId, actualMessages)).findFirst();
foundFlow.ifPresent(flowId -> seenFlowIds.add(flowId));
return foundFlow;
}

private boolean hasSameMessages(String flowId, List<String> actualMessages) {
List<String> expectedMessages = flows.get(flowId).stream().map(FlowComment::message).collect(toList());
List<String> expectedMessages = flows.get(flowId).stream().map(FlowComment::message).toList();
return expectedMessages.equals(actualMessages);
}

Expand All @@ -330,7 +331,7 @@ private static <T> List<Integer> flowToLines(Collection<T> flow, ToIntFunction<T
return flow.stream()
.mapToInt(toLineFunction)
.boxed()
.collect(toList());
.toList();
}

String flowToLines(String flowId) {
Expand Down Expand Up @@ -467,7 +468,7 @@ void consolidateQuickFixes() {
JavaQuickFix javaQuickFix = JavaQuickFix.newQuickFix(message).addTextEdits(
edits.stream()
.map(edit -> getEdit(edit, issueTextSpan, quickFixId))
.collect(toList())
.toList()
).build();
quickFixesForIssue.add(javaQuickFix);
}
Expand Down Expand Up @@ -513,7 +514,7 @@ static List<FlowComment> parseFlows(@Nullable String comment, int line) {
return IntStream.range(0, flowIds.size())
.mapToObj(i -> createFlows(flowIds.get(i), line, flowStarts.get(i), comment.substring(flowStarts.get(i), flowStarts.get(i + 1))))
.flatMap(Function.identity())
.collect(Collectors.toList());
.toList();
}

private static Stream<FlowComment> createFlows(List<String> ids, int line, int startColumn, String flow) {
Expand Down Expand Up @@ -616,7 +617,7 @@ private static Map<IssueAttribute, Object> convertSecondaryLocations(Map<IssueAt
EnumMap<IssueAttribute, Object> copy = new EnumMap<>(attributes);
copy.put(SECONDARY_LOCATIONS, secondaryLocation.stream()
.map(stringValue -> relativeValueToInt(line, (String) stringValue))
.collect(toList()));
.collect(Collectors.toCollection(ArrayList::new)));
return copy;
}
return attributes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,9 @@ public InternalCheckVerifier addFiles(InputFile.Status status, Collection<String

var filesToAdd = modifiedFileNames.stream()
.map(name -> InternalInputFile.inputFile("", new File(name), status))
.collect(Collectors.toList());
.toList();

var filesToAddStrings = filesToAdd.stream().map(Object::toString).collect(Collectors.toList());
var filesToAddStrings = filesToAdd.stream().map(Object::toString).toList();

files.forEach(inputFile -> {
if (filesToAddStrings.contains(inputFile.toString())) {
Expand Down Expand Up @@ -411,7 +411,7 @@ private void assertMultipleIssues(Set<AnalyzerMessage> issues, Map<TextSpan, Lis
}
if (!expected.isEmpty() || !unexpectedLines.isEmpty()) {
Collections.sort(unexpectedLines);
List<Integer> expectedLines = expected.keySet().stream().sorted().collect(Collectors.toList());
List<Integer> expectedLines = expected.keySet().stream().sorted().toList();
throw new AssertionError(new StringBuilder()
.append(expectedLines.isEmpty() ? "" : String.format("Expected at %s", expectedLines))
.append(expectedLines.isEmpty() || unexpectedLines.isEmpty() ? "" : ", ")
Expand Down Expand Up @@ -488,7 +488,7 @@ private void validateAnalyzerMessageAttributes(Expectations.Issue attrs, Analyze

validateLocation(analyzerMessage, attrs);
if (attrs.containsKey(SECONDARY_LOCATIONS)) {
List<AnalyzerMessage> actual = analyzerMessage.flows.stream().map(l -> l.isEmpty() ? null : l.get(0)).filter(Objects::nonNull).collect(Collectors.toList());
List<AnalyzerMessage> actual = analyzerMessage.flows.stream().map(l -> l.isEmpty() ? null : l.get(0)).filter(Objects::nonNull).toList();
List<Integer> expected = (List<Integer>) attrs.get(SECONDARY_LOCATIONS);
validateSecondaryLocations(analyzerMessage, actual, expected);
}
Expand All @@ -498,7 +498,7 @@ private void validateAnalyzerMessageAttributes(Expectations.Issue attrs, Analyze
}

private static void validateSecondaryLocations(AnalyzerMessage parentIssue, List<AnalyzerMessage> actual, List<Integer> expected) {
List<Integer> actualLines = actual.stream().map(AnalyzerMessage::getLine).collect(Collectors.toList());
List<Integer> actualLines = actual.stream().map(AnalyzerMessage::getLine).toList();
List<Integer> unexpected = new ArrayList<>();
for (Integer actualLine : actualLines) {
if (expected.contains(actualLine)) {
Expand Down Expand Up @@ -559,8 +559,8 @@ private void assertExpectedAndMissingFlows(List<String> expectedFlowIds, List<Li

private void assertSoleFlowDiscrepancy(String expectedId, List<AnalyzerMessage> actualFlow) {
Set<Expectations.FlowComment> expected = expectations.flows.get(expectedId);
List<Integer> expectedLines = expected.stream().map(flow -> flow.line).collect(Collectors.toList());
List<Integer> actualLines = actualFlow.stream().map(AnalyzerMessage::getLine).collect(Collectors.toList());
List<Integer> expectedLines = expected.stream().map(flow -> flow.line).toList();
List<Integer> actualLines = actualFlow.stream().map(AnalyzerMessage::getLine).toList();
if (!actualLines.equals(expectedLines)) {
throw new AssertionError(String.format("Flow %s has line differences. Expected: %s but was: %s", expectedId, expectedLines, actualLines));
}
Expand Down Expand Up @@ -599,13 +599,13 @@ private void validateFlowMessages(List<AnalyzerMessage> actual, String flowId, S
List<String> actualMessages = actual.stream()
.map(AnalyzerMessage::getMessage)
.map(InternalCheckVerifier::addQuotes)
.collect(Collectors.toList());
.toList();
List<String> expectedMessages = expected.stream()
.map(Expectations.FlowComment::message)
.map(InternalCheckVerifier::addQuotes)
.collect(Collectors.toList());
.toList();

replaceExpectedNullWithActual(actualMessages, expectedMessages);
expectedMessages = replaceExpectedNullWithActual(actualMessages, expectedMessages);
if (!actualMessages.equals(expectedMessages)) {
throw new AssertionError(
String.format("Wrong messages in flow %s [%s]. Expected: %s but was: %s",
Expand All @@ -620,14 +620,16 @@ private static String addQuotes(@Nullable String s) {
return s != null ? String.format("\"%s\"", s) : s;
}

private static void replaceExpectedNullWithActual(List<String> actualMessages, List<String> expectedMessages) {
if (actualMessages.size() == expectedMessages.size()) {
private static List<String> replaceExpectedNullWithActual(List<String> actualMessages, List<String> expectedMessages) {
List<String> newExceptedMessages = new ArrayList<>(expectedMessages);
if (actualMessages.size() == newExceptedMessages.size()) {
for (int i = 0; i < actualMessages.size(); i++) {
if (expectedMessages.get(i) == null) {
expectedMessages.set(i, actualMessages.get(i));
if (newExceptedMessages.get(i) == null) {
newExceptedMessages.set(i, actualMessages.get(i));
}
}
}
return newExceptedMessages;
}

private static String flowToString(List<AnalyzerMessage> flow) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.assertj.core.api.Fail;
import org.junit.jupiter.api.Test;
Expand All @@ -40,7 +39,6 @@
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.tree.Tree;

import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.jupiter.api.Assertions.assertThrows;
Expand Down Expand Up @@ -581,15 +579,15 @@ public void setContext(JavaFileScannerContext context) {
}
List<AnalyzerMessage> anamyerMessages = preciseIssues.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
.toList();
for (AnalyzerMessage analyzerMessage : anamyerMessages) {
Double messageCost = analyzerMessage.getCost();
Integer cost = messageCost != null ? messageCost.intValue() : null;
List<JavaFileScannerContext.Location> secLocations = new ArrayList<>();
if (!analyzerMessage.flows.isEmpty()) {
List<List<JavaFileScannerContext.Location>> flows = analyzerMessage.flows.stream()
.map(FakeVisitor::messagesToLocations)
.collect(toList());
.toList();
context.reportIssueWithFlow(this, mockTree(analyzerMessage), analyzerMessage.getMessage(), flows, null);
} else {
reportIssue(mockTree(analyzerMessage), analyzerMessage.getMessage(), secLocations, cost);
Expand All @@ -601,7 +599,7 @@ public void setContext(JavaFileScannerContext context) {
}

private static List<JavaFileScannerContext.Location> messagesToLocations(List<AnalyzerMessage> flow) {
return flow.stream().map(m -> new JavaFileScannerContext.Location(m.getMessage(), mockTree(m))).collect(toList());
return flow.stream().map(m -> new JavaFileScannerContext.Location(m.getMessage(), mockTree(m))).toList();
}

private static Tree mockTree(final AnalyzerMessage analyzerMessage) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ void issue_and_multiple_flows_on_the_same_line() {
TEST_LINE);
assertThat(iaf.issue).containsEntry(MESSAGE, "issue msg");
assertThat(iaf.flows).hasSize(3);
List<Integer> lines = iaf.flows.stream().map(f -> f.line).collect(Collectors.toList());
List<Integer> lines = iaf.flows.stream().map(f -> f.line).toList();
assertThat(lines).isEqualTo(Arrays.asList(TEST_LINE, TEST_LINE, TEST_LINE));
Map<String, Object> idMsgMap = iaf.flows.stream().collect(Collectors.toMap(f -> f.id, f -> MESSAGE.get(f.attributes)));
assertThat(idMsgMap).isEqualTo(MapBuilder.<String, Object>newMap()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.semantic.Symbol;
Expand Down Expand Up @@ -114,7 +113,7 @@ private static List<Symbol.MethodSymbol> deprecatedMethodSymbols(MethodTree meth
return methodSymbol.overriddenSymbols()
.stream()
.filter(Symbol.MethodSymbol::isDeprecated)
.collect(Collectors.toList());
.toList();
}

abstract void checkOverridingMethod(MethodTree methodTree, List<Symbol.MethodSymbol> deprecatedSymbol);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private List<Pattern> toPatterns(String suffix) {
return Stream.of(getCredentialWords().split(","))
.map(String::trim)
.map(word -> Pattern.compile("(" + word + ")" + suffix, Pattern.CASE_INSENSITIVE))
.collect(Collectors.toList());
.toList();
}

protected Optional<String> isSettingCredential(MethodInvocationTree tree) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.semantic.Symbol;
Expand Down Expand Up @@ -67,7 +66,7 @@ public void leaveNode(Tree tree) {
List<JavaFileScannerContext.Location> secondaries = secondaryTargets.getOrDefault(symbol, Collections.emptyList())
.stream()
.map(mit -> new JavaFileScannerContext.Location(SECONDARY_MESSAGE, mit))
.collect(Collectors.toList());
.toList();
reportIssue(setInvocation, MESSAGE, secondaries, null);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.sonar.check.Rule;
import org.sonar.java.checks.helpers.ExpressionsHelper;
import org.sonar.java.checks.helpers.UnitTestUtils;
Expand Down Expand Up @@ -82,7 +81,7 @@ public void leaveFile(JavaFileScannerContext context) {
List<Location> secondaryLocations = assertions.stream()
.skip(1)
.map(expr -> new Location("Assertion", expr))
.collect(Collectors.toList());
.toList();
reportIssue(primaryLocation, "Remove this assertion from production code.", secondaryLocations, null);
}
assertions.clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.check.Rule;
import org.sonar.java.checks.helpers.QuickFixHelper;
Expand Down Expand Up @@ -77,7 +76,7 @@ public void visitNode(Tree tree) {
.forRule(this)
.onTree(literalList.get(0))
.withMessage("Remove the unnecessary boolean literal%s.", nLiterals > 1 ? "s" : "")
.withSecondaries(literalList.stream().skip(1).map(lit -> new JavaFileScannerContext.Location("", lit)).collect(Collectors.toList()))
.withSecondaries(literalList.stream().skip(1).map(lit -> new JavaFileScannerContext.Location("", lit)).toList())
.withQuickFixes(() -> getQuickFix(tree))
.report();
}
Expand Down

0 comments on commit 5cdb018

Please sign in to comment.