Skip to content

Commit

Permalink
Fix PMD warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
uhafner committed Apr 9, 2024
1 parent e279906 commit e305110
Show file tree
Hide file tree
Showing 27 changed files with 93 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public FileReaderFactory(final Path file) {
this(file, null);
}

@SuppressWarnings("PMD.CloseResource")
@Override @MustBeClosed
public Reader create() {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ private String asHex(final byte[] bytes) {
hexChars[j * 2] = HEX_CHARACTERS[v >>> 4];
hexChars[j * 2 + 1] = HEX_CHARACTERS[v & 0x0F];
}
return new String(hexChars);
return String.valueOf(hexChars);
}

@VisibleForTesting
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/hm/hafner/analysis/Issue.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public static String getPropertyValueAsString(final Issue issue, final String pr
* @return the function that obtains the value
*/
public static Function<Issue, String> getPropertyValueGetter(final String propertyName) {
return issue -> Issue.getPropertyValueAsString(issue, propertyName);
return issue -> getPropertyValueAsString(issue, propertyName);
}

/**
Expand Down
9 changes: 3 additions & 6 deletions src/main/java/edu/hm/hafner/analysis/IssueDifference.java
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,16 @@ public IssueDifference(final Report currentIssues, final String referenceId,

private void findIssuesInChangedCode(final Map<String, Integer> includes) {
for (Entry<String, Integer> include : includes.entrySet()) {
newIssues.filter(issue -> filter(issue, include.getKey(), include.getValue()))
newIssues.filter(issue -> isInFileAtPosition(issue, include.getKey(), include.getValue()))
.stream()
.map(Issue::getId)
.map(newIssues::remove)
.forEach(newIssuesInChangedCode::add);
}
}

private boolean filter(final Issue issue, final String fileName, final int line) {
if (!issue.getFileName().endsWith(fileName)) {
return false;
}
return issue.affectsLine(line);
private boolean isInFileAtPosition(final Issue issue, final String fileName, final int line) {
return issue.getFileName().endsWith(fileName) && issue.affectsLine(line);
}

private List<UUID> matchIssuesByEquals(final Report currentIssues) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ public void markIssuesInModifiedCode(final Report report, final Map<String, Set<
private boolean affectsChangedLineInFile(final Issue issue, final String fileName, final Set<Integer> lines) {
var normalizedPath = PATH_UTIL.getRelativePath(fileName);

if (!issue.getFileName().endsWith(normalizedPath)) { // check only the suffix
return false;
}
return lines.stream().anyMatch(issue::affectsLine);
return issue.getFileName().endsWith(normalizedPath) && lines.stream().anyMatch(issue::affectsLine);
}
}
20 changes: 11 additions & 9 deletions src/main/java/edu/hm/hafner/analysis/LookaheadParser.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package edu.hm.hafner.analysis;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Optional;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
Expand All @@ -12,9 +13,9 @@

/**
* Parses a report file line by line for issues using a pre-defined regular expression. If the regular expression
* matches then the abstract method {@link #createIssue(Matcher, LookaheadStream, IssueBuilder)} will be called. Sub
* classes need to provide an implementation that transforms the {@link Matcher} instance into a new issue. If required,
* sub classes may consume additional lines from the report file before control is handed back to the template method of
* matches then the abstract method {@link #createIssue(Matcher, LookaheadStream, IssueBuilder)} will be called.
* Subclasses need to provide an implementation that transforms the {@link Matcher} instance into a new issue. If required,
* subclasses may consume additional lines from the report file before control is handed back to the template method of
* this parser.
*
* @author Ullrich Hafner
Expand All @@ -38,7 +39,7 @@ public abstract class LookaheadParser extends IssueParser {

private final Pattern pattern;

private final Stack<String> recursiveDirectories;
private final Deque<String> recursiveDirectories;

/**
* Creates a new instance of {@link LookaheadParser}.
Expand All @@ -50,7 +51,7 @@ protected LookaheadParser(final String pattern) {
super();

this.pattern = Pattern.compile(pattern);
this.recursiveDirectories = new Stack<>();
this.recursiveDirectories = new ArrayDeque<>();
}

@Override
Expand All @@ -65,6 +66,7 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException,
return postProcess(report);
}

@SuppressWarnings("PMD.DoNotUseThreads")
private void parse(final Report report, final LookaheadStream lookahead) {
try (IssueBuilder builder = new IssueBuilder()) {
while (lookahead.hasNext()) {
Expand Down Expand Up @@ -107,7 +109,7 @@ protected void preprocessLine(final String line) {
* @return The new directory to change to
*/
private String enterDirectory(final String line, final Report log) {
extractDirectory(line, ENTERING_DIRECTORY_PATH, log).map(recursiveDirectories::push);
extractDirectory(line, ENTERING_DIRECTORY_PATH, log).ifPresent(recursiveDirectories::push);
return recursiveDirectories.isEmpty() ? NO_DIRECTORY : recursiveDirectories.peek();
}

Expand All @@ -118,9 +120,9 @@ private String enterDirectory(final String line, final Report log) {
* @return The last directory seen, or an empty String if we have returned to the beginning
*/
private String leaveDirectory() {
if (!recursiveDirectories.empty()) {
if (!recursiveDirectories.isEmpty()) {
recursiveDirectories.pop();
if (!recursiveDirectories.empty()) {
if (!recursiveDirectories.isEmpty()) {
return recursiveDirectories.peek();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/hm/hafner/analysis/ModuleDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public String guessModuleName(final String originalFileName) {
* @return the found files (as absolute paths)
*/
private List<String> find(final Path path) {
ArrayList<String> absoluteFileNames = new ArrayList<>();
List<String> absoluteFileNames = new ArrayList<>();

for (AbstractModuleDetector moduleDetector : moduleDetectors) {
String[] relativeFileNames = factory.find(path, moduleDetector.getPattern());
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/edu/hm/hafner/analysis/PackageNameResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import edu.hm.hafner.util.VisibleForTesting;
import static edu.hm.hafner.analysis.PackageDetectors.*;

import static edu.hm.hafner.analysis.PackageDetectors.*;
import static java.util.function.Function.*;

/**
Expand All @@ -29,7 +30,7 @@ public PackageNameResolver() {

@VisibleForTesting
PackageNameResolver(final FileSystem fileSystem) {
ArrayList<AbstractPackageDetector> detectors = new ArrayList<>(Arrays.asList(
List<AbstractPackageDetector> detectors = new ArrayList<>(Arrays.asList(
new JavaPackageDetector(fileSystem),
new CSharpNamespaceDetector(fileSystem),
new KotlinPackageDetector(fileSystem)
Expand Down
14 changes: 9 additions & 5 deletions src/main/java/edu/hm/hafner/analysis/Report.java
Original file line number Diff line number Diff line change
Expand Up @@ -358,10 +358,14 @@ public Report addAll(final Report... reports) {
}

private boolean contains(final Issue issue) {
if (elements.contains(issue)) {
return true;
}
return subReports.stream().map(r -> r.contains(issue)).reduce(Boolean::logicalOr).orElse(false);
return elements.contains(issue) || subReportsContains(issue);
}

private Boolean subReportsContains(final Issue issue) {
return subReports.stream()
.map(r -> r.contains(issue))
.reduce(Boolean::logicalOr)
.orElse(false);
}

@VisibleForTesting
Expand Down Expand Up @@ -1157,7 +1161,7 @@ private String readLongString(final ObjectInputStream input) throws IOException
for (int j = 0; j < chars.length; j++) {
chars[j] = input.readChar();
}
return new String(chars);
return String.valueOf(chars);
}

/**
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/edu/hm/hafner/analysis/Severity.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,18 @@ public static Severity valueOf(@CheckForNull final String severity, final Severi
*/
public static Severity guessFromString(@CheckForNull final String severity) {
if (StringUtils.containsAnyIgnoreCase(severity, "error", "severe", "critical", "fatal")) {
return Severity.ERROR;
return ERROR;
}
if (StringUtils.containsAnyIgnoreCase(severity, "info", "note", "low")) {
return Severity.WARNING_LOW;
return WARNING_LOW;
}
if (StringUtils.containsAnyIgnoreCase(severity, "warning", "medium")) {
return Severity.WARNING_NORMAL;
return WARNING_NORMAL;
}
if (StringUtils.containsIgnoreCase(severity, "high")) {
return Severity.WARNING_HIGH;
return WARNING_HIGH;
}
return Severity.WARNING_LOW;
return WARNING_LOW;
}

/**
Expand All @@ -120,7 +120,7 @@ public static Severity guessFromString(@CheckForNull final String severity) {
*/
public static Collection<Severity> collectSeveritiesFrom(final Severity minimumSeverity) {
List<Severity> priorities = new ArrayList<>();
priorities.add(Severity.ERROR);
priorities.add(ERROR);
if (WARNING_HIGH.equals(minimumSeverity)) {
priorities.add(WARNING_HIGH);
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/hm/hafner/analysis/parser/AjcParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private void fillMessageAndCategory(final IssueBuilder builder, final String lin
category = Categories.DEPRECATION;
}
else if (line.contains("adviceDidNotMatch")) {
category = AjcParser.ADVICE;
category = ADVICE;
}
else {
category = "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public class IarCstatParser extends LookaheadParser {

private static final String IAR_WARNING_PATTERN = ANT_TASK
+ "(?:\"?(.*?)\"?[\\(,](\\d+)\\)?\\s+)?(Severity-(?:Low|Medium|High))\\[(\\S+)\\]:(.*)$";
private static final String SEVERITY_LOW = "Severity-Low";
private static final String SEVERITY_HIGH = "Severity-High";

/**
* Creates a new instance of {@link IarCstatParser}.
Expand All @@ -45,10 +47,10 @@ protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStre

private Severity mapSeverity(final String category) {
Severity severity;
if ("Severity-Low".equals(category)) {
if (SEVERITY_LOW.equals(category)) {
severity = Severity.WARNING_LOW;
}
else if ("Severity-High".equals(category)) {
else if (SEVERITY_HIGH.equals(category)) {
severity = Severity.WARNING_HIGH;
}
else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.util.List;
import java.util.Optional;

import edu.hm.hafner.analysis.util.IntegerParser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.w3c.dom.Document;
Expand All @@ -16,6 +15,7 @@
import edu.hm.hafner.analysis.ReaderFactory;
import edu.hm.hafner.analysis.Report;
import edu.hm.hafner.analysis.Severity;
import edu.hm.hafner.analysis.util.IntegerParser;
import edu.hm.hafner.analysis.util.XmlElementUtil;

/**
Expand All @@ -26,6 +26,8 @@
public class IdeaInspectionParser extends IssueParser {
private static final long serialVersionUID = 3307389086106375473L;
private static final String PATH_PREFIX = "file://";
private static final String WARNING = "WARNING";
private static final String ERROR = "ERROR";

@Override
public Report parse(final ReaderFactory readerFactory) throws ParsingException {
Expand Down Expand Up @@ -58,10 +60,10 @@ private Report parseProblems(final List<Element> elements) {

private Severity getPriority(final String severity) {
Severity priority = Severity.WARNING_LOW;
if ("WARNING".equals(severity)) {
if (WARNING.equals(severity)) {
priority = Severity.WARNING_NORMAL;
}
else if ("ERROR".equals(severity)) {
else if (ERROR.equals(severity)) {
priority = Severity.WARNING_HIGH;
}
return priority;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/edu/hm/hafner/analysis/parser/LintParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
*/
public class LintParser extends IssueParser {
private static final long serialVersionUID = 3341424685245834156L;
private static final String FILE = "file";

@Override
public Report parse(final ReaderFactory readerFactory) throws ParsingException {
Expand Down Expand Up @@ -56,7 +57,7 @@ public void startElement(final String namespaceURI,
return; // Start element, good to skip
}

if ("file".equals(key)) {
if (FILE.equals(key)) {
fileName = atts.getValue("name");
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public class MsBuildParser extends LookaheadParser {

private static final Pattern IGNORED_TOOLS_PATTERN = Pattern.compile("(?!.exe)(\\.[^.]+)$");
private static final Pattern LINKER_CAUSE = Pattern.compile(".*imported by '([A-Za-z0-9\\-_.]+)'.*");
private static final String EXPECTED_CATEGORY = "Expected";
private static final String MSBUILD = "MSBUILD";

/**
* Creates a new instance of {@link MsBuildParser}.
Expand Down Expand Up @@ -76,7 +78,7 @@ protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStre
}

String category = matcher.group(9);
if ("Expected".equals(category)) {
if (EXPECTED_CATEGORY.equals(category)) {
return Optional.empty();
}
return builder.setLineStart(matcher.group(5))
Expand Down Expand Up @@ -124,15 +126,15 @@ else if (StringUtils.isNotBlank(matcher.group(7))) {
if (canResolveRelativeFileName(fileName, projectDir)) {
fileName = FilenameUtils.concat(projectDir, fileName);
}
if ("MSBUILD".equals(fileName.trim())) {
if (MSBUILD.equals(fileName.trim())) {
fileName = "-";
}
return fileName;
}

private boolean canResolveRelativeFileName(final String fileName, final String projectDir) {
return StringUtils.isNotBlank(projectDir) && FilenameUtils.getPrefixLength(fileName) == 0
&& !"MSBUILD".equals(fileName.trim());
&& !MSBUILD.equals(fileName.trim());
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
public class RevApiParser extends JsonIssueParser {
private static final long serialVersionUID = -2452699725595063377L;
private static final int CAPACITY = 1024;

@Override
protected void parseJsonArray(final Report report, final JSONArray jsonReport, final IssueBuilder issueBuilder) {
Expand Down Expand Up @@ -102,7 +103,7 @@ private Severity toSeverity(final String level) {
}

private String getDescription(final JSONObject jsonIssue) {
StringBuilder severityDescription = new StringBuilder();
StringBuilder severityDescription = new StringBuilder(CAPACITY);
for (Object severity : jsonIssue.getJSONArray("classification")) {
if (severity instanceof JSONObject) {
severityDescription.append("<p>Compatibility: ")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ public Report parse(final ReaderFactory readerFactory) {
}
}

@SuppressWarnings("PMD.DoNotUseThreads")
private void parseLine(final IssueBuilder builder, final Report warnings, final String line) {
Matcher fileMatcher = FILE_PATTERN.matcher(line);
if (fileMatcher.find()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@
import edu.hm.hafner.util.LookaheadStream;

/**
* A parser for the sbt scala compiler warnings. You should use -feature and -deprecation compiler opts.
* A parser for the sbt scala compiler warnings. You should use {@code -feature} and {@code -deprecation} compiler
* opts.
*
* @author Hochak Hung
*/
public class SbtScalacParser extends LookaheadParser {
private static final long serialVersionUID = -4233964844965517977L;

private static final String SBT_WARNING_PATTERN = "^(\\[warn\\]|\\[error\\](?!\\s+Total\\stime:))\\s*(.*?):(\\d+)(?::\\d+)?:\\s*(.*)$";
private static final String ERROR = "[error]";

/**
* Creates a new instance of {@link SbtScalacParser}.
Expand All @@ -37,7 +39,7 @@ protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStre
}

private Severity mapPriority(final Matcher matcher) {
if ("[error]".equals(matcher.group(1))) {
if (ERROR.equals(matcher.group(1))) {
return Severity.WARNING_HIGH;
}
else {
Expand Down
Loading

0 comments on commit e305110

Please sign in to comment.