diff --git a/pom.xml b/pom.xml index 97e4c988a..3cd64e655 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ edu.hm.hafner codingstyle-pom - 4.13.0 + 4.14.0 @@ -53,7 +53,7 @@ HEAD - 12.5.0 + 12.4.2 -SNAPSHOT edu.hm.hafner.analysis.model @@ -78,6 +78,16 @@ + + + + net.sf.saxon + Saxon-HE + 12.5 + + + + @@ -136,12 +146,6 @@ xercesImpl 2.12.2 - - org.ow2.asm - asm - 9.7 - - com.github.spotbugs @@ -173,23 +177,8 @@ org.slf4j - org.ow2.asm - asm - - - bcel - org.apache.bcel - - - - - org.apache.bcel - bcel - 6.10.0 - - - commons-lang3 - org.apache.commons + error_prone_annotations + com.google.errorprone @@ -225,16 +214,11 @@ com.google.code.gson - jcommander - com.beust + jul-to-slf4j + org.slf4j - - com.beust - jcommander - 1.82 - net.sourceforge.pmd @@ -405,57 +389,8 @@ true false - - - - - true - true - shaded.* - .* - - - true - javax.xml.transform - java.class.externalClassExposedInAPI - - - - - edu.hm.hafner.analysis.parser.checkstyle.TopicRule - - - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - - package - - shade - - - false - - - org.ow2.asm:* - - - - - org.objectweb.asm - shaded.org.objectweb.asm - - - - - - diff --git a/src/main/java/edu/hm/hafner/analysis/AntModuleDetector.java b/src/main/java/edu/hm/hafner/analysis/AntModuleDetector.java index 63b3b1913..72b32926b 100644 --- a/src/main/java/edu/hm/hafner/analysis/AntModuleDetector.java +++ b/src/main/java/edu/hm/hafner/analysis/AntModuleDetector.java @@ -45,7 +45,7 @@ void collectProjects(final Map mapping, final List proje */ private String parseBuildXml(final String buildXml) { try (InputStream file = getFactory().open(buildXml)) { - SecureDigester digester = new SecureDigester(ModuleDetector.class); + var digester = new SecureDigester(ModuleDetector.class); digester.push(new StringBuilder()); String xPath = "project"; diff --git a/src/main/java/edu/hm/hafner/analysis/DuplicationGroup.java b/src/main/java/edu/hm/hafner/analysis/DuplicationGroup.java index b718f5caa..13fb662f0 100644 --- a/src/main/java/edu/hm/hafner/analysis/DuplicationGroup.java +++ b/src/main/java/edu/hm/hafner/analysis/DuplicationGroup.java @@ -3,9 +3,11 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.apache.commons.lang3.StringUtils; +import edu.hm.hafner.util.Generated; import edu.umd.cs.findbugs.annotations.CheckForNull; /** @@ -53,7 +55,7 @@ public void setCodeFragment(@CheckForNull final String codeFragment) { * Adds the specified duplication (represented by an {@link Issue} instance) to this group of duplications. * * @param issue - * the issues that references the position of the duplicated code fragment + * the issues that reference the position of the duplicated code fragment */ public void add(final Issue issue) { occurrences.add(issue); @@ -73,21 +75,21 @@ public List getDuplications() { } @Override - public boolean equals(@CheckForNull final Object o) { + @Generated + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - - DuplicationGroup that = (DuplicationGroup) o; - - return codeFragment.equals(that.codeFragment); + var that = (DuplicationGroup) o; + return Objects.equals(codeFragment, that.codeFragment); } @Override + @Generated public int hashCode() { - return codeFragment.hashCode(); + return Objects.hashCode(codeFragment); } } diff --git a/src/main/java/edu/hm/hafner/analysis/FileReaderFactory.java b/src/main/java/edu/hm/hafner/analysis/FileReaderFactory.java index 585873d4a..790cf1fc0 100644 --- a/src/main/java/edu/hm/hafner/analysis/FileReaderFactory.java +++ b/src/main/java/edu/hm/hafner/analysis/FileReaderFactory.java @@ -40,7 +40,7 @@ public class FileReaderFactory extends ReaderFactory { * @param charset * the charset to use when reading the file (or {@code null} if the charset should be detected) */ - public FileReaderFactory(final Path file, final @CheckForNull Charset charset) { + public FileReaderFactory(final Path file, @CheckForNull final Charset charset) { super(StandardCharsets.UTF_8); this.file = file; diff --git a/src/main/java/edu/hm/hafner/analysis/FingerprintGenerator.java b/src/main/java/edu/hm/hafner/analysis/FingerprintGenerator.java index d8cc4215c..00d466785 100644 --- a/src/main/java/edu/hm/hafner/analysis/FingerprintGenerator.java +++ b/src/main/java/edu/hm/hafner/analysis/FingerprintGenerator.java @@ -7,6 +7,7 @@ import java.nio.charset.MalformedInputException; import java.nio.file.InvalidPathException; import java.nio.file.NoSuchFileException; +import java.util.Locale; import java.util.Set; import org.apache.commons.io.FilenameUtils; @@ -36,7 +37,7 @@ public class FingerprintGenerator { * the character set to use when reading the source files */ public void run(final FullTextFingerprint algorithm, final Report report, final Charset charset) { - FilteredLog log = new FilteredLog("Can't create fingerprints for some files:"); + var log = new FilteredLog("Can't create fingerprints for some files:"); int sum = 0; for (Issue issue : report) { if (!issue.hasFingerprint()) { @@ -88,8 +89,8 @@ private int computeFingerprint(final Issue issue, final FullTextFingerprint algo @VisibleForTesting static String createDefaultFingerprint(final Issue issue) { - HashCodeBuilder builder = new HashCodeBuilder(); - return String.format("FALLBACK-%x", + var builder = new HashCodeBuilder(); + return String.format(Locale.ENGLISH, "FALLBACK-%x", builder.append(issue.getBaseName()) .append(issue.getType()) .append(issue.getCategory()) diff --git a/src/main/java/edu/hm/hafner/analysis/FullTextFingerprint.java b/src/main/java/edu/hm/hafner/analysis/FullTextFingerprint.java index a0d8804d2..d77ea1c92 100644 --- a/src/main/java/edu/hm/hafner/analysis/FullTextFingerprint.java +++ b/src/main/java/edu/hm/hafner/analysis/FullTextFingerprint.java @@ -78,7 +78,7 @@ public String compute(final String fileName, final int line, final Charset chars @VisibleForTesting String getFallbackFingerprint(final String fileName) { - return String.format("%x", fileName.hashCode()); + return String.format(Locale.ENGLISH, "%x", fileName.hashCode()); } @VisibleForTesting @@ -108,7 +108,7 @@ String extractContext(final int affectedLine, final Iterator lines) { int start = computeStartLine(affectedLine); - StringBuilder context = new StringBuilder(LINE_RANGE_BUFFER_SIZE); + var context = new StringBuilder(LINE_RANGE_BUFFER_SIZE); int line = 1; for (; lines.hasNext() && line < start - LINES_LOOK_AHEAD; line++) { lines.next(); // skip the first lines diff --git a/src/main/java/edu/hm/hafner/analysis/Issue.java b/src/main/java/edu/hm/hafner/analysis/Issue.java index 57809817d..2a825abe6 100644 --- a/src/main/java/edu/hm/hafner/analysis/Issue.java +++ b/src/main/java/edu/hm/hafner/analysis/Issue.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.lang.reflect.InvocationTargetException; +import java.util.Locale; import java.util.UUID; import java.util.function.Function; import java.util.function.Predicate; @@ -975,6 +976,8 @@ public int hashCode() { @Override public String toString() { - return String.format("%s%s(%d,%d): %s: %s: %s", isPartOfModifiedCode() ? "*" : StringUtils.EMPTY, getBaseName(), lineStart, columnStart, type, category, message); + return String.format(Locale.ENGLISH, "%s%s(%d,%d): %s: %s: %s", + isPartOfModifiedCode() ? "*" : StringUtils.EMPTY, getBaseName(), + lineStart, columnStart, type, category, message); } } diff --git a/src/main/java/edu/hm/hafner/analysis/LookaheadParser.java b/src/main/java/edu/hm/hafner/analysis/LookaheadParser.java index 98c40ccfd..5a6547c75 100644 --- a/src/main/java/edu/hm/hafner/analysis/LookaheadParser.java +++ b/src/main/java/edu/hm/hafner/analysis/LookaheadParser.java @@ -56,7 +56,7 @@ protected LookaheadParser(final String pattern) { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException { - Report report = new Report(); + var report = new Report(); try (Stream lines = readerFactory.readStream()) { try (LookaheadStream lookahead = new LookaheadStream(lines, readerFactory.getFileName())) { parse(report, lookahead); @@ -148,7 +148,7 @@ else if (line.contains(LEAVING_DIRECTORY)) { builder.setDirectory(leaveDirectory()); } else if (line.contains(CMAKE_PREFIX)) { - extractDirectory(line, CMAKE_PATH, log).map(builder::setDirectory); + extractDirectory(line, CMAKE_PATH, log).ifPresent(builder::setDirectory); } } diff --git a/src/main/java/edu/hm/hafner/analysis/MavenModuleDetector.java b/src/main/java/edu/hm/hafner/analysis/MavenModuleDetector.java index 0bb98b170..b871615f7 100644 --- a/src/main/java/edu/hm/hafner/analysis/MavenModuleDetector.java +++ b/src/main/java/edu/hm/hafner/analysis/MavenModuleDetector.java @@ -52,7 +52,7 @@ private String parsePom(final String pom) { @SuppressWarnings("OverlyBroadCatchBlock") private String parsePomAttribute(final String pom, final String tagName) { try (InputStream file = getFactory().open(pom)) { - SecureDigester digester = new SecureDigester(ModuleDetector.class); + var digester = new SecureDigester(ModuleDetector.class); digester.push(new StringBuilder()); digester.addCallMethod("project/" + tagName, "append", 0); diff --git a/src/main/java/edu/hm/hafner/analysis/OsgiModuleDetector.java b/src/main/java/edu/hm/hafner/analysis/OsgiModuleDetector.java index 2264e2a8a..ac6077246 100644 --- a/src/main/java/edu/hm/hafner/analysis/OsgiModuleDetector.java +++ b/src/main/java/edu/hm/hafner/analysis/OsgiModuleDetector.java @@ -53,9 +53,9 @@ public void collectProjects(final Map mapping, final List lineM @SuppressFBWarnings("OS_OPEN_STREAM") public Stream readStream() { try { - BufferedReader reader = new BufferedReader(create()); + var reader = new BufferedReader(create()); Stream stringStream = reader.lines().onClose(closeReader(reader)); if (hasLineMapper()) { return stringStream.map(lineMapper); @@ -142,7 +142,7 @@ public String readString() { */ public Document readDocument() { try (Reader reader = create()) { - SecureXmlParserFactory parserFactory = new SecureXmlParserFactory(); + var parserFactory = new SecureXmlParserFactory(); return parserFactory.readDocument(reader, getCharset()); } catch (IOException | SecureXmlParserFactory.ParsingException exception) { diff --git a/src/main/java/edu/hm/hafner/analysis/Report.java b/src/main/java/edu/hm/hafner/analysis/Report.java index 14dcebe9a..925098b8b 100644 --- a/src/main/java/edu/hm/hafner/analysis/Report.java +++ b/src/main/java/edu/hm/hafner/analysis/Report.java @@ -13,6 +13,7 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; @@ -28,10 +29,12 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.FormatMethod; import edu.hm.hafner.util.Ensure; import edu.hm.hafner.util.FilteredLog; +import edu.hm.hafner.util.Generated; import edu.hm.hafner.util.LineRangeList; import edu.hm.hafner.util.PathUtil; import edu.hm.hafner.util.TreeString; @@ -259,6 +262,7 @@ public Set getOriginReportFiles() { * * @return this */ + @CanIgnoreReturnValue public Report add(final Issue issue) { if (hasId() && !issue.hasOrigin()) { issue.setOrigin(id, name); @@ -286,6 +290,7 @@ public Report add(final Issue issue) { * @return this * @see #add(Issue) */ + @CanIgnoreReturnValue public Report addAll(final Issue issue, final Issue... additionalIssues) { add(issue); for (Issue additional : additionalIssues) { @@ -305,6 +310,7 @@ public Report addAll(final Issue issue, final Issue... additionalIssues) { * @return this * @see #add(Issue) */ + @CanIgnoreReturnValue public Report addAll(final Collection issues) { for (Issue additional : issues) { add(additional); @@ -322,6 +328,7 @@ public Report addAll(final Collection issues) { * @return this * @see #copyIssuesAndProperties(Report, Report) */ + @CanIgnoreReturnValue public Report addAll(final Report... reports) { Ensure.that(reports).isNotEmpty("No reports given."); @@ -613,7 +620,7 @@ public int getSizeOf(final Severity severity) { @Override public String toString() { - return String.format("%s (%s): %d issues (%d duplicates)", getEffectiveName(), getEffectiveId(), + return String.format(Locale.ENGLISH, "%s (%s): %d issues (%d duplicates)", getEffectiveName(), getEffectiveId(), size(), getDuplicatesSize()); } @@ -833,17 +840,13 @@ public Map getPropertyCount(final Function pro * @see #getProperties(Function) */ public Map groupByProperty(final String propertyName) { - Map> issues = stream() + var issues = stream() .collect(Collectors.groupingBy(Issue.getPropertyValueGetter(propertyName))); return issues.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, - e -> { - Report report = new Report(); - report.addAll(e.getValue()); - return report; - })); + e -> new Report().addAll(e.getValue()))); } /** @@ -852,7 +855,7 @@ public Map groupByProperty(final String propertyName) { * @return a new issue container that contains the same elements in the same order */ public Report copy() { - Report copied = new Report(); + var copied = new Report(); copyIssuesAndProperties(this, copied); return copied; } @@ -884,7 +887,7 @@ private void copyProperties(final Report source, final Report destination) { * @return a new issue container that contains the same properties but no issues */ public Report copyEmptyInstance() { - Report empty = new Report(); + var empty = new Report(); copyProperties(this, empty); return empty; } @@ -991,56 +994,31 @@ public boolean hasErrors() { } @Override - @SuppressWarnings("PMD.NPathComplexity") - public boolean equals(@CheckForNull final Object o) { + @Generated + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - - Report report = (Report) o; - - if (duplicatesSize != report.duplicatesSize) { - return false; - } - if (!id.equals(report.id)) { - return false; - } - if (!name.equals(report.name)) { - return false; - } - if (!originReportFile.equals(report.originReportFile)) { - return false; - } - if (!subReports.equals(report.subReports)) { - return false; - } - if (!elements.equals(report.elements)) { - return false; - } - if (!infoMessages.equals(report.infoMessages)) { - return false; - } - if (!errorMessages.equals(report.errorMessages)) { - return false; - } - return countersByKey.equals(report.countersByKey); + var issues = (Report) o; + return duplicatesSize == issues.duplicatesSize + && Objects.equals(id, issues.id) + && Objects.equals(name, issues.name) + && Objects.equals(originReportFile, issues.originReportFile) + && Objects.equals(subReports, issues.subReports) + && Objects.equals(elements, issues.elements) + && Objects.equals(infoMessages, issues.infoMessages) + && Objects.equals(errorMessages, issues.errorMessages) + && Objects.equals(countersByKey, issues.countersByKey); } @Override + @Generated public int hashCode() { - int result = id.hashCode(); - result = 31 * result + name.hashCode(); - result = 31 * result + originReportFile.hashCode(); - result = 31 * result + subReports.hashCode(); - result = 31 * result + elements.hashCode(); - result = 31 * result + infoMessages.hashCode(); - result = 31 * result + errorMessages.hashCode(); - result = 31 * result + countersByKey.hashCode(); - result = 31 * result + duplicatesSize; - return result; + return Objects.hash(id, name, originReportFile, subReports, elements, infoMessages, errorMessages, + countersByKey, duplicatesSize); } private void writeObject(final ObjectOutputStream output) throws IOException { @@ -1112,7 +1090,7 @@ private void readObject(final ObjectInputStream input) throws IOException, Class int subReportCount = input.readInt(); for (int i = 0; i < subReportCount; i++) { - Report subReport = (Report) input.readObject(); + var subReport = (Report) input.readObject(); subReports.add(subReport); } } @@ -1120,7 +1098,7 @@ private void readObject(final ObjectInputStream input) throws IOException, Class @SuppressFBWarnings("OBJECT_DESERIALIZATION") @SuppressWarnings("BanSerializableRead") private void readIssues(final ObjectInputStream input, final int size) throws IOException, ClassNotFoundException { - final TreeStringBuilder builder = new TreeStringBuilder(); + var builder = new TreeStringBuilder(); for (int i = 0; i < size; i++) { String path = input.readUTF(); TreeString fileName = builder.intern(input.readUTF()); @@ -1128,22 +1106,22 @@ private void readIssues(final ObjectInputStream input, final int size) throws IO int lineEnd = input.readInt(); int columnStart = input.readInt(); int columnEnd = input.readInt(); - LineRangeList lineRanges = (LineRangeList) input.readObject(); + var lineRanges = (LineRangeList) input.readObject(); String category = input.readUTF(); String type = input.readUTF(); - TreeString packageName = builder.intern(input.readUTF()); + var packageName = builder.intern(input.readUTF()); String moduleName = input.readUTF(); - Severity severity = Severity.valueOf(input.readUTF()); - TreeString message = builder.intern(readLongString(input)); + var severity = Severity.valueOf(input.readUTF()); + var message = builder.intern(readLongString(input)); String description = readLongString(input); String origin = input.readUTF(); String originName = input.readUTF(); String reference = input.readUTF(); String fingerprint = input.readUTF(); - Serializable additionalProperties = (Serializable) input.readObject(); - UUID uuid = (UUID) input.readObject(); + var additionalProperties = (Serializable) input.readObject(); + var uuid = (UUID) input.readObject(); - Issue issue = new Issue(path, fileName, + var issue = new Issue(path, fileName, lineStart, lineEnd, columnStart, columnEnd, lineRanges, category, type, packageName, moduleName, severity, message, description, @@ -1290,7 +1268,7 @@ enum FilterType { } /** - * Adds a new filter for each patterns string. Adds the filter either to the include or exclude list. + * Adds a new filter for each pattern string. Adds the filter either to the include or exclude list. * * @param patterns * filter patterns. @@ -1299,7 +1277,8 @@ enum FilterType { * @param type * type of the filter */ - private void addNewFilter(final Collection patterns, final Function propertyToFilter, + private void addNewFilter(final Collection patterns, + final Function propertyToFilter, final FilterType type) { Collection> filters = new ArrayList<>(); for (String pattern : patterns) { @@ -1320,9 +1299,9 @@ private boolean isIncludeFilter(final FilterType type) { } /** - * Create a IssueFilter. Combine by default all includes with or and all excludes with and. + * Creates a new {@link Issue} filter. Combines all includes with or and all excludes with and. * - * @return a IssueFilter which has all added filter as filter criteria. + * @return {@link Issue} filter which has all added filters as filter criteria */ @SuppressWarnings("NoFunctionalReturnType") public Predicate build() { @@ -1333,322 +1312,346 @@ public Predicate build() { // /** - * Add a new filter. + * Add a new filter for {@code Issue::getFileName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeFileNameFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getFileName, FilterType.INCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeFileNameFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getFileName, FilterType.INCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getFileName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeFileNameFilter(final String... pattern) { - return setIncludeFileNameFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeFileNameFilter(final String... patterns) { + return setIncludeFileNameFilter(Arrays.asList(patterns)); } /** - * Add a new filter. + * Add a new filter for {@code Issue::getFileName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeFileNameFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getFileName, FilterType.EXCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeFileNameFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getFileName, FilterType.EXCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getFileName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeFileNameFilter(final String... pattern) { - return setExcludeFileNameFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeFileNameFilter(final String... patterns) { + return setExcludeFileNameFilter(Arrays.asList(patterns)); } // // /** - * Add a new filter. + * Add a new filter for {@code Issue::getPackageName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludePackageNameFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getPackageName, FilterType.INCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludePackageNameFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getPackageName, FilterType.INCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getPackageName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludePackageNameFilter(final String... pattern) { - return setIncludePackageNameFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludePackageNameFilter(final String... patterns) { + return setIncludePackageNameFilter(Arrays.asList(patterns)); } /** - * Add a new filter. + * Add a new filter for {@code Issue::getPackageName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludePackageNameFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getPackageName, FilterType.EXCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludePackageNameFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getPackageName, FilterType.EXCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getPackageName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludePackageNameFilter(final String... pattern) { - return setExcludePackageNameFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludePackageNameFilter(final String... patterns) { + return setExcludePackageNameFilter(Arrays.asList(patterns)); } // // /** - * Add a new filter. + * Add a new filter for {@code Issue::getModuleName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeModuleNameFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getModuleName, FilterType.INCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeModuleNameFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getModuleName, FilterType.INCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getModuleName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeModuleNameFilter(final String... pattern) { - return setIncludeModuleNameFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeModuleNameFilter(final String... patterns) { + return setIncludeModuleNameFilter(Arrays.asList(patterns)); } /** - * Add a new filter. + * Add a new filter for {@code Issue::getModuleName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeModuleNameFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getModuleName, FilterType.EXCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeModuleNameFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getModuleName, FilterType.EXCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getModuleName}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeModuleNameFilter(final String... pattern) { - return setExcludeModuleNameFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeModuleNameFilter(final String... patterns) { + return setExcludeModuleNameFilter(Arrays.asList(patterns)); } // // /** - * Add a new filter. + * Add a new filter for {@code Issue::getCategory}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeCategoryFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getCategory, FilterType.INCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeCategoryFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getCategory, FilterType.INCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getCategory}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeCategoryFilter(final String... pattern) { - return setIncludeCategoryFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeCategoryFilter(final String... patterns) { + return setIncludeCategoryFilter(Arrays.asList(patterns)); } /** - * Add a new filter. + * Add a new filter for {@code Issue::getCategory}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeCategoryFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getCategory, FilterType.EXCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeCategoryFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getCategory, FilterType.EXCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getCategory}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeCategoryFilter(final String... pattern) { - return setExcludeCategoryFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeCategoryFilter(final String... patterns) { + return setExcludeCategoryFilter(Arrays.asList(patterns)); } // // /** - * Add a new filter. + * Add a new filter for {@code Issue::getCategory}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeTypeFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getType, FilterType.INCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeTypeFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getType, FilterType.INCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getType}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeTypeFilter(final String... pattern) { - return setIncludeTypeFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeTypeFilter(final String... patterns) { + return setIncludeTypeFilter(Arrays.asList(patterns)); } /** - * Add a new filter. + * Add a new filter for {@code Issue::getType}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeTypeFilter(final Collection pattern) { - addNewFilter(pattern, Issue::getType, FilterType.EXCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeTypeFilter(final Collection patterns) { + addNewFilter(patterns, Issue::getType, FilterType.EXCLUDE); return this; } /** - * Add a new filter. + * Add a new filter for {@code Issue::getType}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeTypeFilter(final String... pattern) { - return setExcludeTypeFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeTypeFilter(final String... patterns) { + return setExcludeTypeFilter(Arrays.asList(patterns)); } // // /** - * Add a new filter to include issues with matching issue message. + * Add a new filter for {@code Issue::getMessage}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeMessageFilter(final Collection pattern) { - addMessageFilter(pattern, FilterType.INCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeMessageFilter(final Collection patterns) { + addMessageFilter(patterns, FilterType.INCLUDE); return this; } /** - * Add a new filter to include issues with matching issue message. + * Add a new filter for {@code Issue::getMessage}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setIncludeMessageFilter(final String... pattern) { - return setIncludeMessageFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setIncludeMessageFilter(final String... patterns) { + return setIncludeMessageFilter(Arrays.asList(patterns)); } /** - * Add a new filter to exclude issues with matching issue message. + * Add a new filter for {@code Issue::getMessage}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeMessageFilter(final Collection pattern) { - addMessageFilter(pattern, FilterType.EXCLUDE); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeMessageFilter(final Collection patterns) { + addMessageFilter(patterns, FilterType.EXCLUDE); return this; } /** - * Add a new filter to exclude issues with matching issue message. + * Add a new filter for {@code Issue::getMessage}. * - * @param pattern - * pattern + * @param patterns + * the patterns to match * - * @return this. + * @return this */ - public IssueFilterBuilder setExcludeMessageFilter(final String... pattern) { - return setExcludeMessageFilter(Arrays.asList(pattern)); + @CanIgnoreReturnValue + public IssueFilterBuilder setExcludeMessageFilter(final String... patterns) { + return setExcludeMessageFilter(Arrays.asList(patterns)); } - private void addMessageFilter(final Collection pattern, final FilterType filterType) { - addNewFilter(pattern, issue -> String.format("%s%n%s", issue.getMessage(), issue.getDescription()), + private void addMessageFilter(final Collection patterns, final FilterType filterType) { + addNewFilter(patterns, issue -> String.format("%s%n%s", issue.getMessage(), issue.getDescription()), filterType); } // diff --git a/src/main/java/edu/hm/hafner/analysis/SecureDigester.java b/src/main/java/edu/hm/hafner/analysis/SecureDigester.java index b9b52662d..ea200c67e 100644 --- a/src/main/java/edu/hm/hafner/analysis/SecureDigester.java +++ b/src/main/java/edu/hm/hafner/analysis/SecureDigester.java @@ -1,7 +1,5 @@ package edu.hm.hafner.analysis; -import javax.xml.parsers.SAXParserFactory; - import org.apache.commons.digester3.Digester; import org.xml.sax.InputSource; @@ -24,8 +22,8 @@ public SecureDigester(final Class classWithClassLoader) { setClassLoader(classWithClassLoader.getClassLoader()); - SAXParserFactory factory = getFactory(); // Since there is no way to set the factory we need to modify the existing one - SecureXmlParserFactory parserFactory = new SecureXmlParserFactory(); + var factory = getFactory(); // Since there is no way to set the factory we need to modify the existing one + var parserFactory = new SecureXmlParserFactory(); parserFactory.configureSaxParserFactory(factory); setValidating(false); setEntityResolver((publicId, systemId) -> new InputSource()); diff --git a/src/main/java/edu/hm/hafner/analysis/Severity.java b/src/main/java/edu/hm/hafner/analysis/Severity.java index 64fb93019..fddeed690 100644 --- a/src/main/java/edu/hm/hafner/analysis/Severity.java +++ b/src/main/java/edu/hm/hafner/analysis/Severity.java @@ -7,6 +7,7 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Set; import org.apache.commons.lang3.StringUtils; @@ -14,6 +15,7 @@ import com.google.errorprone.annotations.Immutable; import edu.hm.hafner.util.Ensure; +import edu.hm.hafner.util.Generated; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -187,21 +189,21 @@ public boolean equalsIgnoreCase(final String severityName) { } @Override - public boolean equals(@CheckForNull final Object o) { + @Generated + public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } - - Severity severity = (Severity) o; - - return name.equals(severity.name); + var severity = (Severity) o; + return Objects.equals(name, severity.name); } @Override + @Generated public int hashCode() { - return name.hashCode(); + return Objects.hashCode(name); } } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/AjcParser.java b/src/main/java/edu/hm/hafner/analysis/parser/AjcParser.java index a78543f2e..b051c9fc9 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/AjcParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/AjcParser.java @@ -37,7 +37,7 @@ public Report parse(final ReaderFactory reader) throws ParsingException { private Report parse(final Stream lines) { try (IssueBuilder builder = new IssueBuilder()) { - Report warnings = new Report(); + var report = new Report(); States state = States.START; @@ -68,13 +68,13 @@ private Report parse(final Stream lines) { else if (line.isEmpty()) { state = States.PARSING; - warnings.add(builder.buildAndClean()); + report.add(builder.buildAndClean()); } break; } } - return warnings; + return report; } } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/AquaScannerParser.java b/src/main/java/edu/hm/hafner/analysis/parser/AquaScannerParser.java index 3df2a27de..92db9562b 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/AquaScannerParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/AquaScannerParser.java @@ -36,9 +36,9 @@ private void parseResources(final Report report, final JSONArray resources, fina for (int i = 0; i < resources.length(); i++) { final Object item = resources.get(i); if (item instanceof JSONObject) { - final JSONObject resourceWrapper = (JSONObject) item; + var resourceWrapper = (JSONObject) item; if (!resourceWrapper.isNull("vulnerabilities") && !resourceWrapper.isNull("resource")) { - final JSONObject resource = resourceWrapper.getJSONObject("resource"); + var resource = resourceWrapper.getJSONObject("resource"); parseVulnerabilities(report, issueBuilder, resourceWrapper, resource); } } @@ -47,7 +47,7 @@ private void parseResources(final Report report, final JSONArray resources, fina private void parseVulnerabilities(final Report report, final IssueBuilder issueBuilder, final JSONObject resourceWrapper, final JSONObject resource) { - final JSONArray vulnerabilities = resourceWrapper.getJSONArray("vulnerabilities"); + var vulnerabilities = resourceWrapper.getJSONArray("vulnerabilities"); for (Object vulnerability : vulnerabilities) { if (vulnerability instanceof JSONObject) { report.add(convertToIssue(resource, (JSONObject) vulnerability, issueBuilder)); @@ -57,7 +57,7 @@ private void parseVulnerabilities(final Report report, final IssueBuilder issueB private Issue convertToIssue(final JSONObject resource, final JSONObject vulnerability, final IssueBuilder issueBuilder) { - final String fileName = resource.optString("path", resource.optString("name", VALUE_NOT_SET)); + String fileName = resource.optString("path", resource.optString("name", VALUE_NOT_SET)); return issueBuilder .setFileName(fileName) .setSeverity(mapSeverity(vulnerability.optString("aqua_severity", "UNKNOWN"))) @@ -76,15 +76,13 @@ else if (StringUtils.equalsIgnoreCase(string, AQUA_VULNERABILITY_LEVEL_TAG_MEDIU else if (StringUtils.equalsIgnoreCase(string, AQUA_VULNERABILITY_LEVEL_TAG_HIGH)) { return Severity.WARNING_HIGH; } - else { - return Severity.ERROR; - } + return Severity.ERROR; } private String formatDescription(final String fileName, final JSONObject resource, final JSONObject vulnerability) { - final String version = resource.optString("version", VALUE_NOT_SET); - final String severity = vulnerability.optString("aqua_severity", "UNKOWN"); - final String description = vulnerability.optString("description", ""); + String version = resource.optString("version", VALUE_NOT_SET); + String severity = vulnerability.optString("aqua_severity", "UNKOWN"); + String description = vulnerability.optString("description", ""); return join(div(b("Resource: "), text(fileName)), div(b("Installed Version: "), text(version)), div(b("Aqua Severity: "), text(severity)), diff --git a/src/main/java/edu/hm/hafner/analysis/parser/BrakemanParser.java b/src/main/java/edu/hm/hafner/analysis/parser/BrakemanParser.java index eb1cb8bc1..8f85be143 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/BrakemanParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/BrakemanParser.java @@ -32,7 +32,7 @@ private Issue convertToIssue(final JSONObject warning, final IssueBuilder issueB Severity severity = getSeverity(warning.getString("confidence")); String fingerprint = warning.getString("fingerprint"); String warningType = warning.getString("check_name"); - StringBuilder message = new StringBuilder(); + var message = new StringBuilder(); message.append(warning.getString("message")); if (warning.has("code")) { @@ -66,8 +66,6 @@ else if (equalsIgnoreCase(confidence, "High")) { else if (equalsIgnoreCase(confidence, "Weak")) { return Severity.WARNING_LOW; } - else { - return Severity.WARNING_HIGH; - } + return Severity.WARNING_HIGH; } } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/CargoCheckParser.java b/src/main/java/edu/hm/hafner/analysis/parser/CargoCheckParser.java index 4c235993f..55e1c5c0b 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/CargoCheckParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/CargoCheckParser.java @@ -3,7 +3,6 @@ import java.util.Optional; import java.util.stream.Stream; -import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; @@ -69,7 +68,7 @@ public class CargoCheckParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException { - Report report = new Report(); + var report = new Report(); try (Stream lines = readerFactory.readStream(); IssueBuilder issueBuilder = new IssueBuilder()) { lines.map(line -> (JSONObject) new JSONTokener(line).nextValue()) @@ -124,10 +123,10 @@ private Optional extractIssue(final JSONObject object, final IssueBuilder } private Optional parseDetails(final JSONObject message) { - JSONArray spans = message.getJSONArray(MESSAGE_SPANS); + var spans = message.getJSONArray(MESSAGE_SPANS); for (int index = 0; index < spans.length(); index++) { - JSONObject span = spans.getJSONObject(index); + var span = spans.getJSONObject(index); if (span.getBoolean(MESSAGE_SPAN_IS_PRIMARY)) { String fileName = span.getString(MESSAGE_SPAN_FILE_NAME); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/CargoClippyParser.java b/src/main/java/edu/hm/hafner/analysis/parser/CargoClippyParser.java index 4dabaf654..491eb1332 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/CargoClippyParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/CargoClippyParser.java @@ -13,6 +13,7 @@ import edu.hm.hafner.analysis.util.IntegerParser; import edu.hm.hafner.util.LookaheadStream; import edu.umd.cs.findbugs.annotations.CheckForNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static j2html.TagCreator.*; @@ -83,32 +84,32 @@ protected Optional createIssue(final Matcher matcher, final LookaheadStre */ @SuppressWarnings("PMD.CognitiveComplexity") private FileInformation createRecommendationMessage(final LookaheadStream lookahead) { - StringBuilder description = new StringBuilder(); - FileInformation fileInformation = new FileInformation(); + var description = new StringBuilder(); + var fileInformation = new FileInformation(); while (lookahead.hasNext(CARGO_CLIPP_CONTEXT_CONTINUES)) { - final String line = lookahead.next(); + String line = lookahead.next(); - Matcher fileInfoMatcher = CARGO_CLIPPY_FILE_PATTERN.matcher(line); + var fileInfoMatcher = CARGO_CLIPPY_FILE_PATTERN.matcher(line); if (fileInfoMatcher.matches()) { - fileInformation.setFile(fileInfoMatcher.group("file")); - fileInformation.setLine(IntegerParser.parseInt(fileInfoMatcher.group("line"))); + fileInformation.setFileName(fileInfoMatcher.group("file")); + fileInformation.setFileLine(IntegerParser.parseInt(fileInfoMatcher.group("line"))); fileInformation.setColumnStart(IntegerParser.parseInt(fileInfoMatcher.group("column"))); } else { - Matcher clippyRecommendationMatcher = CARGO_CLIPPY_REC_PATTERN.matcher(line); + var clippyRecommendationMatcher = CARGO_CLIPPY_REC_PATTERN.matcher(line); if (clippyRecommendationMatcher.matches()) { description.append(line); continue; } - Matcher clippyHelpMatcher = CARGO_CLIPPY_HELP_PATTERN.matcher(line); + var clippyHelpMatcher = CARGO_CLIPPY_HELP_PATTERN.matcher(line); if (clippyHelpMatcher.matches()) { fileInformation.setHelp(clippyHelpMatcher.group(1), clippyHelpMatcher.group(2)); continue; } - Matcher clippyNotePatcher = CARGO_CLIPPY_NOTE_PATTERN.matcher(line); + var clippyNotePatcher = CARGO_CLIPPY_NOTE_PATTERN.matcher(line); if (clippyNotePatcher.matches()) { fileInformation.setCategory(clippyNotePatcher.group(2)); fileInformation.setLevel(clippyNotePatcher.group(1)); @@ -153,11 +154,12 @@ private static final class FileInformation { /** * Set the filename where the recommendation originated. * - * @param filename + * @param fileName * the filename of the recommendation. */ - public void setFile(final String filename) { - this.fileName = filename; + @SuppressFBWarnings("NM") + public void setFileName(final String fileName) { + this.fileName = fileName; } /** @@ -172,11 +174,11 @@ public String getFile() { /** * Set the file line where the recommendation originated. * - * @param fileline + * @param fileLine * The line number. */ - public void setLine(final Integer fileline) { - this.fileLine = fileline; + public void setFileLine(final Integer fileLine) { + this.fileLine = fileLine; } /** diff --git a/src/main/java/edu/hm/hafner/analysis/parser/ClairParser.java b/src/main/java/edu/hm/hafner/analysis/parser/ClairParser.java index 7d286e2f2..85065d6cd 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/ClairParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/ClairParser.java @@ -31,7 +31,7 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, private Issue convertToIssue(final JSONObject jsonIssue, @CheckForNull final String image, final IssueBuilder issueBuilder) { - StringBuilder message = new StringBuilder(); + var message = new StringBuilder(); appendIfNotEmpty(jsonIssue, message, "featurename", ""); appendIfNotEmpty(jsonIssue, message, "featureversion", ":"); appendIfNotEmpty(jsonIssue, message, "description", ""); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/ClangAnalyzerPlistParser.java b/src/main/java/edu/hm/hafner/analysis/parser/ClangAnalyzerPlistParser.java index ff9a17d46..cae2477bd 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/ClangAnalyzerPlistParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/ClangAnalyzerPlistParser.java @@ -40,25 +40,25 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (IssueBuilder issueBuilder = new IssueBuilder()) { Document doc = readerFactory.readDocument(); - XPathFactory xPathFactory = XPathFactory.newInstance(); - XPath xPath = xPathFactory.newXPath(); + var xPathFactory = XPathFactory.newInstance(); + var xPath = xPathFactory.newXPath(); - XPathExpression filesPath = xPath.compile( + var filesPath = xPath.compile( "/plist/dict/key[text()='files']/following-sibling::array/string"); - XPathExpression diagnosticsPath = xPath.compile( + var diagnosticsPath = xPath.compile( "/plist/dict/key[text()='diagnostics']/following-sibling::array/dict"); - XPathExpression diagDescriptionPath = compileDiagStrPath(xPath, "description"); - XPathExpression diagCategoryPath = compileDiagStrPath(xPath, "category"); - XPathExpression diagTypePath = compileDiagStrPath(xPath, "type"); - XPathExpression diagLocationLinePath = compileDiagLocationPath(xPath, "line"); - XPathExpression diagLocationColPath = compileDiagLocationPath(xPath, "col"); - XPathExpression diagLocationFilePath = compileDiagLocationPath(xPath, "file"); + var diagDescriptionPath = compileDiagStrPath(xPath, "description"); + var diagCategoryPath = compileDiagStrPath(xPath, "category"); + var diagTypePath = compileDiagStrPath(xPath, "type"); + var diagLocationLinePath = compileDiagLocationPath(xPath, "line"); + var diagLocationColPath = compileDiagLocationPath(xPath, "col"); + var diagLocationFilePath = compileDiagLocationPath(xPath, "file"); - Report report = new Report(); + var report = new Report(); - List files = getFilesList(doc, filesPath); + var files = getFilesList(doc, filesPath); - NodeList diagnostics = (NodeList) diagnosticsPath.evaluate(doc, XPathConstants.NODESET); + var diagnostics = (NodeList) diagnosticsPath.evaluate(doc, XPathConstants.NODESET); for (Element diag : XmlElementUtil.nodeListToList(diagnostics)) { issueBuilder.setFileName(getFileName(files, diag, diagLocationFilePath)) .guessSeverity("Warning") @@ -82,7 +82,7 @@ private static List getFilesList(final Document doc, final XPathExpressi throws XPathExpressionException { List files = new ArrayList<>(); - NodeList nodes = (NodeList) filesPath.evaluate(doc, XPathConstants.NODESET); + var nodes = (NodeList) filesPath.evaluate(doc, XPathConstants.NODESET); for (Element filePathStr : XmlElementUtil.nodeListToList(nodes)) { files.add(filePathStr.getTextContent()); } @@ -116,7 +116,7 @@ private static XPathExpression compileDiagLocationPath(final XPath xPath, final } private static String extractField(final Element diag, final XPathExpression expr) throws XPathExpressionException { - NodeList keys = (NodeList) expr.evaluate(diag, XPathConstants.NODESET); + var keys = (NodeList) expr.evaluate(diag, XPathConstants.NODESET); List elements = XmlElementUtil.nodeListToList(keys); if (elements.isEmpty()) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/CrossCoreEmbeddedStudioParser.java b/src/main/java/edu/hm/hafner/analysis/parser/CrossCoreEmbeddedStudioParser.java index b42209465..cc3a69c88 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/CrossCoreEmbeddedStudioParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/CrossCoreEmbeddedStudioParser.java @@ -36,7 +36,7 @@ public CrossCoreEmbeddedStudioParser() { @Override protected Optional createIssue(final Matcher matcher, final LookaheadStream lookahead, final IssueBuilder builder) { - StringBuilder message = new StringBuilder(matcher.group("messageBegin").trim()); + var message = new StringBuilder(matcher.group("messageBegin").trim()); // always grab the second line if (lookahead.hasNext()) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/DockerLintParser.java b/src/main/java/edu/hm/hafner/analysis/parser/DockerLintParser.java index 215966130..f59488392 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/DockerLintParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/DockerLintParser.java @@ -43,7 +43,7 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, } private Issue convertToIssue(final JSONObject jsonIssue, final IssueBuilder builder) { - StringBuilder message = new StringBuilder(); + var message = new StringBuilder(); message.append(jsonIssue.optString("message")); if (jsonIssue.has("description")) { message.append(" - "); @@ -64,7 +64,7 @@ private Issue convertToIssue(final JSONObject jsonIssue, final IssueBuilder buil } private String collapseReferenceUrl(final Object refUrl) { - StringBuilder referenceUrl = new StringBuilder(); + var referenceUrl = new StringBuilder(); if (refUrl instanceof JSONArray) { for (Object part : (JSONArray) refUrl) { referenceUrl.append(part); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/DrMemoryParser.java b/src/main/java/edu/hm/hafner/analysis/parser/DrMemoryParser.java index 227ed5e08..df056fd6a 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/DrMemoryParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/DrMemoryParser.java @@ -47,13 +47,13 @@ protected Optional createIssue(final Matcher matcher, final LookaheadStre throws ParsingException { String header = matcher.group(1); - StringBuilder messageBuilder = new StringBuilder(header); + var messageBuilder = new StringBuilder(header); while (lookahead.hasNext("Elapsed time")) { messageBuilder.append("
"); messageBuilder.append(lookahead.next()); } - StringBuilder stacktraceBuilder = new StringBuilder(); + var stacktraceBuilder = new StringBuilder(); while (lookahead.hasNext("^#.*")) { String stackTrace = lookahead.next(); stacktraceBuilder.append(stackTrace); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/EclipseXMLParser.java b/src/main/java/edu/hm/hafner/analysis/parser/EclipseXMLParser.java index 2eda7e8ae..3d82d8e83 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/EclipseXMLParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/EclipseXMLParser.java @@ -1,13 +1,10 @@ package edu.hm.hafner.analysis.parser; import java.util.Optional; -import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -53,22 +50,22 @@ public boolean accepts(final ReaderFactory readerFactory) { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Document doc = readerFactory.readDocument(); + var doc = readerFactory.readDocument(); - XPathFactory xPathFactory = XPathFactory.newInstance(); - XPath xPath = xPathFactory.newXPath(); - XPathExpression sourcePath = xPath.compile("/compiler/sources/source[problems]"); - XPathExpression fileNamePath = xPath.compile("./@path"); - XPathExpression problemsPath = xPath.compile("problems/problem"); + var xPathFactory = XPathFactory.newInstance(); + var xPath = xPathFactory.newXPath(); + var sourcePath = xPath.compile("/compiler/sources/source[problems]"); + var fileNamePath = xPath.compile("./@path"); + var problemsPath = xPath.compile("problems/problem"); - Report report = new Report(); + var report = new Report(); - NodeList sources = (NodeList)sourcePath.evaluate(doc, XPathConstants.NODESET); + var sources = (NodeList)sourcePath.evaluate(doc, XPathConstants.NODESET); for (Element source : XmlElementUtil.nodeListToList(sources)) { String fileName = fileNamePath.evaluate(source); issueBuilder.setFileName(fileName); - NodeList problems = (NodeList)problemsPath.evaluate(source, XPathConstants.NODESET); + var problems = (NodeList)problemsPath.evaluate(source, XPathConstants.NODESET); for (Element problem : XmlElementUtil.nodeListToList(problems)) { issueBuilder.guessSeverity(extractSeverity(problem)) .setLineStart(extractLineStart(problem)) @@ -171,7 +168,7 @@ private String extractColumnRange(final Element problem) { .filter(e -> "source_context".equals(e.getNodeName())) .findFirst(); - StringBuilder range = new StringBuilder(); + var range = new StringBuilder(); ctx.map(e -> e.getAttribute("sourceStart")).ifPresent(range::append); range.append('-'); ctx.map(e -> e.getAttribute("sourceEnd")).ifPresent(range::append); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/EmbeddedEngineerParser.java b/src/main/java/edu/hm/hafner/analysis/parser/EmbeddedEngineerParser.java index 8ebae1a91..d4d1c2c41 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/EmbeddedEngineerParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/EmbeddedEngineerParser.java @@ -4,10 +4,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; -import edu.hm.hafner.analysis.*; -import edu.hm.hafner.util.LookaheadStream; + import org.apache.commons.lang3.StringUtils; +import edu.hm.hafner.analysis.IssueBuilder; +import edu.hm.hafner.analysis.IssueParser; +import edu.hm.hafner.analysis.ParsingException; +import edu.hm.hafner.analysis.ReaderFactory; +import edu.hm.hafner.analysis.Report; +import edu.hm.hafner.analysis.Severity; +import edu.hm.hafner.util.LookaheadStream; + /** * A parser for the EmbeddedEngineer EA Code Generator tool log files. * @@ -38,18 +45,10 @@ public Report parse(final ReaderFactory reader) throws ParsingException { } } - private String readMultipleLines(final LookaheadStream lookahead) { - StringBuilder multipleLines = new StringBuilder(lookahead.next()); - while (lookahead.hasNext() && !lookahead.hasNext(LOG_BEGINNING_PATTERN)) { - multipleLines.append(" ").append(lookahead.next()); - } - return multipleLines.toString(); - } - private Report parse(final LookaheadStream lookahead) { try (IssueBuilder builder = new IssueBuilder()) { String file = parseFileName(lookahead); - Report report = new Report(); + var report = new Report(); while (lookahead.hasNext() && lookahead.hasNext(LOG_BEGINNING_PATTERN)) { String lines = this.readMultipleLines(lookahead); Matcher matcher = SPECIAL_WARNING_PATTERN.matcher(lines); @@ -87,6 +86,14 @@ private Report parse(final LookaheadStream lookahead) { } } + private String readMultipleLines(final LookaheadStream lookahead) { + var multipleLines = new StringBuilder(lookahead.next()); + while (lookahead.hasNext() && !lookahead.hasNext(LOG_BEGINNING_PATTERN)) { + multipleLines.append(" ").append(lookahead.next()); + } + return multipleLines.toString(); + } + private String parseFileName(final LookaheadStream lineIterator) { while (lineIterator.hasNext()) { String line = lineIterator.next(); @@ -126,4 +133,4 @@ else if (group.contains("Error")) { } return Severity.WARNING_NORMAL; } -} \ No newline at end of file +} diff --git a/src/main/java/edu/hm/hafner/analysis/parser/ErrorProneParser.java b/src/main/java/edu/hm/hafner/analysis/parser/ErrorProneParser.java index 6ce73bb31..1e47880c9 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/ErrorProneParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/ErrorProneParser.java @@ -70,8 +70,8 @@ static String appendPeriod(final Matcher matcher) { * @return the description */ static String createDescription(final LookaheadStream lookahead) { - StringBuilder description = new StringBuilder(); - StringBuilder url = new StringBuilder(); + var description = new StringBuilder(); + var url = new StringBuilder(); boolean urlFound = false; // skip all text before the URL while (lookahead.hasNext("^\\s+.*")) { String line = lookahead.next(); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/FlowParser.java b/src/main/java/edu/hm/hafner/analysis/parser/FlowParser.java index 94ee1e088..ef15c3075 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/FlowParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/FlowParser.java @@ -61,16 +61,15 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, } } - private Report extractIssues(final JSONArray elements, final Report report, + private void extractIssues(final JSONArray elements, final Report report, final IssueBuilder issueBuilder) { for (Object object : elements) { if (object instanceof JSONObject) { - JSONObject issue = (JSONObject) object; + var issue = (JSONObject) object; findFirstMessage(issue).ifPresent( jsonObject -> report.add(createIssueFromJsonObject(issue, jsonObject, issueBuilder))); } } - return report; } /** @@ -82,7 +81,7 @@ private Report extractIssues(final JSONArray elements, final Report report, * @return first message */ private Optional findFirstMessage(final JSONObject issue) { - JSONArray message = issue.optJSONArray(ISSUE_MESSAGE); + var message = issue.optJSONArray(ISSUE_MESSAGE); if (message == null) { return Optional.empty(); } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/Gcc4CompilerParser.java b/src/main/java/edu/hm/hafner/analysis/parser/Gcc4CompilerParser.java index 005390fdd..575f8cdba 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/Gcc4CompilerParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/Gcc4CompilerParser.java @@ -47,7 +47,7 @@ protected boolean isLineInteresting(final String line) { @Override protected Optional createIssue(final Matcher matcher, final LookaheadStream lookahead, final IssueBuilder builder) { - StringBuilder message = new StringBuilder(matcher.group(5)); + var message = new StringBuilder(matcher.group(5)); Matcher classMatcher = CLASS_PATTERN.matcher(message.toString()); if (classMatcher.find() && classMatcher.group(1) != null) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/IdeaInspectionParser.java b/src/main/java/edu/hm/hafner/analysis/parser/IdeaInspectionParser.java index a21ae115a..1b7ab48d9 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/IdeaInspectionParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/IdeaInspectionParser.java @@ -1,7 +1,6 @@ package edu.hm.hafner.analysis.parser; import java.util.List; -import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; @@ -33,16 +32,16 @@ public class IdeaInspectionParser extends IssueParser { public Report parse(final ReaderFactory readerFactory) throws ParsingException { Document document = readerFactory.readDocument(); - Element rootElement = (Element) document.getElementsByTagName("problems").item(0); + var rootElement = (Element) document.getElementsByTagName("problems").item(0); return parseProblems(XmlElementUtil.getChildElementsByName(rootElement, "problem")); } private Report parseProblems(final List elements) { - Report problems = new Report(); + var problems = new Report(); try (IssueBuilder issueBuilder = new IssueBuilder()) { for (Element element : elements) { String file = getChildValue(element, "file"); - Optional problemClass = XmlElementUtil.getFirstChildElementByName(element, "problem_class"); + var problemClass = XmlElementUtil.getFirstChildElementByName(element, "problem_class"); if (problemClass.isPresent()) { Element problem = problemClass.get(); issueBuilder.setFileName(stripPathPrefix(file)) @@ -78,7 +77,7 @@ private String getValue(final Element element) { } private String getChildValue(final Element element, final String childTag) { - Optional firstElement = XmlElementUtil.getFirstChildElementByName(element, childTag); + var firstElement = XmlElementUtil.getFirstChildElementByName(element, childTag); if (firstElement.isPresent()) { Node child = firstElement.get().getFirstChild(); if (child != null) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/JsonBaseParser.java b/src/main/java/edu/hm/hafner/analysis/parser/JsonBaseParser.java index bf0287e81..0e783fe50 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/JsonBaseParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/JsonBaseParser.java @@ -105,7 +105,7 @@ Optional convertToIssue(final JSONObject jsonIssue, final IssueBuilder bu } private LineRangeList convertToLineRangeList(final JSONArray jsonRanges) { - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); for (int i = 0; i < jsonRanges.length(); i++) { JSONObject jsonRange = jsonRanges.getJSONObject(i); if (jsonRange.has(LINE_RANGE_START)) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/JsonIssueParser.java b/src/main/java/edu/hm/hafner/analysis/parser/JsonIssueParser.java index 573b8aeaf..fd5f5905e 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/JsonIssueParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/JsonIssueParser.java @@ -24,16 +24,16 @@ public abstract class JsonIssueParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { - Report report = new Report(); + var report = new Report(); try (Reader reader = readerFactory.create(); IssueBuilder issueBuilder = new IssueBuilder()) { - Object parsedValue = new JSONTokener(reader).nextValue(); + var parsedValue = new JSONTokener(reader).nextValue(); if (parsedValue instanceof JSONObject) { - JSONObject jsonReport = (JSONObject) parsedValue; + var jsonReport = (JSONObject) parsedValue; parseJsonObject(report, jsonReport, issueBuilder); } else if (parsedValue instanceof JSONArray) { - JSONArray jsonReport = (JSONArray) parsedValue; + var jsonReport = (JSONArray) parsedValue; parseJsonArray(report, jsonReport, issueBuilder); } @@ -63,7 +63,7 @@ public boolean accepts(final ReaderFactory readerFactory) { * build to be used to create issues */ protected void parseJsonObject(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) { - // by default no issues are reported + // by default, no issues are reported } /** @@ -77,6 +77,6 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, * build to be used to create issues */ protected void parseJsonArray(final Report report, final JSONArray jsonReport, final IssueBuilder issueBuilder) { - // by default no issues are reported + // by default, no issues are reported } } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/JsonLogParser.java b/src/main/java/edu/hm/hafner/analysis/parser/JsonLogParser.java index 58b6b2cbe..bc1e9b95d 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/JsonLogParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/JsonLogParser.java @@ -28,7 +28,7 @@ public boolean accepts(final ReaderFactory readerFactory) { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (Stream lines = readerFactory.readStream()) { - Report report = new Report(); + var report = new Report(); lines.map(String::trim) .filter(line -> !line.isEmpty()) .filter(line -> !line.startsWith("//")) @@ -43,7 +43,7 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException { private Optional parseIssue(final String line, final Report report) { try { - JSONObject jsonIssue = new JSONObject(line); + var jsonIssue = new JSONObject(line); return convertToIssue(jsonIssue); } catch (JSONException e) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/JsonParser.java b/src/main/java/edu/hm/hafner/analysis/parser/JsonParser.java index e98f84127..849001fac 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/JsonParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/JsonParser.java @@ -34,9 +34,9 @@ public boolean accepts(final ReaderFactory readerFactory) { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (Reader reader = readerFactory.create(); IssueBuilder builder = new IssueBuilder()) { - JSONObject jsonReport = (JSONObject) new JSONTokener(reader).nextValue(); + var jsonReport = (JSONObject) new JSONTokener(reader).nextValue(); - Report report = new Report(); + var report = new Report(); if (jsonReport.has(ISSUES)) { JSONArray issues = jsonReport.getJSONArray(ISSUES); StreamSupport.stream(issues.spliterator(), SEQUENTIAL) diff --git a/src/main/java/edu/hm/hafner/analysis/parser/LintParser.java b/src/main/java/edu/hm/hafner/analysis/parser/LintParser.java index fad15d87b..b4657ea12 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/LintParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/LintParser.java @@ -23,7 +23,7 @@ public class LintParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { - Report report = new Report(); + var report = new Report(); readerFactory.parse(new JSLintXmlSaxParser(report)); return report; } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/MavenConsoleParser.java b/src/main/java/edu/hm/hafner/analysis/parser/MavenConsoleParser.java index 6654b8fe0..5224fef51 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/MavenConsoleParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/MavenConsoleParser.java @@ -69,7 +69,7 @@ protected Optional createIssue(final Matcher matcher, final LookaheadStre String severity = matcher.group("severity"); builder.setLineStart(lookahead.getLine()).guessSeverity(severity); - StringBuilder message = new StringBuilder(matcher.group("message")); + var message = new StringBuilder(matcher.group("message")); if (hasGoals(MAVEN_ENFORCER_PLUGIN)) { String timestamp = matcher.group("timestamp"); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/MentorParser.java b/src/main/java/edu/hm/hafner/analysis/parser/MentorParser.java index c730f53f1..9f138c5ca 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/MentorParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/MentorParser.java @@ -128,7 +128,7 @@ private void parseVsimMessage(final LookaheadStream lookahead, final IssueBuilde @SuppressFBWarnings(value = "POTENTIAL_XML_INJECTION", justification = "Message is cleaned in UI") private String parseSimTime(final LookaheadStream lookahead, final IssueBuilder builder) { - StringBuilder description = new StringBuilder(); + var description = new StringBuilder(); String timeLine = ""; while (lookahead.hasNext() && lookahead.peekNext().startsWith("# ") diff --git a/src/main/java/edu/hm/hafner/analysis/parser/NagFortranParser.java b/src/main/java/edu/hm/hafner/analysis/parser/NagFortranParser.java index a70703c50..0dd850e31 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/NagFortranParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/NagFortranParser.java @@ -35,7 +35,7 @@ public NagFortranParser() { protected Optional createIssue(final Matcher matcher, final LookaheadStream lookahead, final IssueBuilder builder) throws ParsingException { - StringBuilder messageBuilder = new StringBuilder(matcher.group(5)); + var messageBuilder = new StringBuilder(matcher.group(5)); while (lookahead.hasNext("\\s+ .+")) { messageBuilder.append("\n"); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java b/src/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java index 50e02a3cc..9350773b8 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/PnpmAuditParser.java @@ -41,7 +41,7 @@ public class PnpmAuditParser extends JsonIssueParser { @Override protected void parseJsonObject(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) { - JSONObject results = jsonReport.optJSONObject("advisories"); + var results = jsonReport.optJSONObject("advisories"); if (results != null) { parseResults(report, results, issueBuilder); } @@ -49,7 +49,7 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, private void parseResults(final Report report, final JSONObject jsonReport, final IssueBuilder issueBuilder) { for (String key : jsonReport.keySet()) { - JSONObject vulnerability = (JSONObject) jsonReport.get(key); + var vulnerability = (JSONObject) jsonReport.get(key); if (!vulnerability.isEmpty()) { report.add(convertToIssue(vulnerability, issueBuilder)); @@ -68,7 +68,7 @@ private Issue convertToIssue(final JSONObject vulnerability, final IssueBuilder } private String mapType(final JSONObject vulnerability) { - final JSONArray cves = vulnerability.optJSONArray("cves"); + var cves = vulnerability.optJSONArray("cves"); return cves != null && !cves.isNull(0) ? (String) cves.opt(0) : UNCATEGORIZED; } @@ -101,20 +101,18 @@ else if (PNPM_VULNERABILITY_SEVERITY_HIGH.equalsIgnoreCase(string)) { else if (PNPM_VULNERABILITY_SEVERITY_CRITICAL.equalsIgnoreCase(string)) { return Severity.ERROR; } - else { - return Severity.WARNING_NORMAL; - } + return Severity.WARNING_NORMAL; } private String formatDescription(final JSONObject vulnerability) { - final List vulnerabilityTags = new ArrayList<>(); + List vulnerabilityTags = new ArrayList<>(); getValueAsContainerTag(vulnerability, "module_name", "Module").ifPresent(vulnerabilityTags::add); final JSONArray findings = vulnerability.optJSONArray("findings"); if (findings != null && !findings.isEmpty()) { - final JSONObject firstFinding = (JSONObject) findings.opt(0); - final String installedVersion = firstFinding.optString("version"); + var firstFinding = (JSONObject) findings.opt(0); + String installedVersion = firstFinding.optString("version"); getValueAsContainerTag(installedVersion, "Installed Version").ifPresent(vulnerabilityTags::add); } @@ -130,7 +128,7 @@ private String formatDescription(final JSONObject vulnerability) { } private Optional getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue) { - final String value = vulnerability.optString(tagOfValue); + String value = vulnerability.optString(tagOfValue); if (value == null || value.isEmpty()) { return Optional.empty(); @@ -149,7 +147,7 @@ private Optional getValueAsContainerTag(final String value, final private Optional getValueAsContainerTag(final JSONObject vulnerability, final String tagOfValue, final String label) { - final String value = vulnerability.optString(tagOfValue); + String value = vulnerability.optString(tagOfValue); if (value == null || value.isEmpty()) { return Optional.empty(); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/PolyspaceParser.java b/src/main/java/edu/hm/hafner/analysis/parser/PolyspaceParser.java index 8da69f50f..6437ef098 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/PolyspaceParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/PolyspaceParser.java @@ -39,15 +39,15 @@ public Report parse(final ReaderFactory reader) throws ParsingException { private Report parse(final Stream lines) { try (IssueBuilder builder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); - Iterator lineIterator = lines.iterator(); + var lineIterator = lines.iterator(); int offset = detectLineOffset(lineIterator); while (lineIterator.hasNext()) { String line = lineIterator.next(); - String[] attributes = line.split("\\t", 15 + offset); + var attributes = line.split("\\t", 15 + offset); if (containsAnyIgnoreCase(attributes[9], "Unreviewed", "To investigate", "To fix", "Other")) { builder.setFileName(attributes[8]); builder.setCategory(attributes[2]); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/ProtoLintJsonParser.java b/src/main/java/edu/hm/hafner/analysis/parser/ProtoLintJsonParser.java index ddc247499..7e42d72d9 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/ProtoLintJsonParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/ProtoLintJsonParser.java @@ -32,7 +32,7 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, private void parseResults(final Report report, final String basedir, final JSONArray jsonReport, final IssueBuilder issueBuilder) { for (int i = 0; i < jsonReport.length(); i++) { - JSONObject finding = (JSONObject) jsonReport.get(i); + var finding = (JSONObject) jsonReport.get(i); report.add(convertToIssue(basedir, finding, issueBuilder)); } } @@ -56,7 +56,7 @@ private Issue convertToIssue(final String basedir, final JSONObject finding, fin private Severity mapSeverity(final String aProtoLintSeverity) { // ProtoLint knows the following severities // https://github.com/yoheimuta/protolint/blob/master/linter/rule/rule.go#L9 - // which can be mapped with the provided mapping method + // which can be mapped with the provided mapping method return Severity.guessFromString(aProtoLintSeverity); } } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/QtTranslationParser.java b/src/main/java/edu/hm/hafner/analysis/parser/QtTranslationParser.java index c3341f5c0..5200b54d4 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/QtTranslationParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/QtTranslationParser.java @@ -44,7 +44,7 @@ public class QtTranslationParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { - Report report = new Report(); + var report = new Report(); readerFactory.parse(new QtTranslationSaxParser(report, readerFactory.getFileName())); return report; } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/RevApiParser.java b/src/main/java/edu/hm/hafner/analysis/parser/RevApiParser.java index f58e3e4f4..7af953e79 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/RevApiParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/RevApiParser.java @@ -105,7 +105,7 @@ private Severity toSeverity(final String level) { @SuppressFBWarnings(value = "POTENTIAL_XML_INJECTION", justification = "Message is cleaned in UI") private String getDescription(final JSONObject jsonIssue) { - StringBuilder severityDescription = new StringBuilder(CAPACITY); + var severityDescription = new StringBuilder(CAPACITY); for (Object severity : jsonIssue.getJSONArray("classification")) { if (severity instanceof JSONObject) { severityDescription.append("

Compatibility: ") diff --git a/src/main/java/edu/hm/hafner/analysis/parser/RfLintParser.java b/src/main/java/edu/hm/hafner/analysis/parser/RfLintParser.java index d83bc0091..f0a2c3521 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/RfLintParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/RfLintParser.java @@ -159,7 +159,7 @@ public static RfLintRuleName fromName(final String name) { @Override public Report parse(final ReaderFactory readerFactory) { try (Stream lines = readerFactory.readStream(); IssueBuilder builder = new IssueBuilder()) { - Report warnings = new Report(); + var warnings = new Report(); lines.forEach(line -> parseLine(builder, warnings, line)); return warnings; } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/SimulinkCheckParser.java b/src/main/java/edu/hm/hafner/analysis/parser/SimulinkCheckParser.java index 91cf8f4ea..66521b121 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/SimulinkCheckParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/SimulinkCheckParser.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.Reader; -import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.input.ReaderInputStream; @@ -40,14 +39,14 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (IssueBuilder issueBuilder = new IssueBuilder(); Reader reader = readerFactory.create(); InputStream targetStream = ReaderInputStream.builder().setReader(reader).setCharset(readerFactory.getCharset()).get()) { - Document document = Jsoup.parse(targetStream, readerFactory.getCharset().name(), EMPTY_BASE_URI); + var document = Jsoup.parse(targetStream, readerFactory.getCharset().name(), EMPTY_BASE_URI); - Elements systemElements = document.select(REPORT_CONTENT); - Element systemElement = systemElements.first(); + var systemElements = document.select(REPORT_CONTENT); + var systemElement = systemElements.first(); if (systemElement == null) { throw new ParsingException("No system element found"); } - Report report = new Report(); + var report = new Report(); String system = systemElement.id(); parseIssues(report, document, issueBuilder, system, WARNING); @@ -67,8 +66,8 @@ private void parseIssues(final Report report, final Document document, final Iss setSeverity(check, issueBuilder); for (Element element : document.select(check)) { - Elements headings = element.select("span.CheckHeading"); - Element heading = headings.first(); + var headings = element.select("span.CheckHeading"); + var heading = headings.first(); if (heading != null) { parseHeading(report, issueBuilder, system, element, headings, heading.id()); } @@ -77,10 +76,10 @@ private void parseIssues(final Report report, final Document document, final Iss private static void parseHeading(final Report report, final IssueBuilder issueBuilder, final String system, final Element element, final Elements headings, final String headingElement) { - String[] headingSplit = headingElement.split("\\."); + var headingSplit = headingElement.split("\\."); if (headingSplit.length > 0) { String issueTxt = headings.text(); - Matcher textMatcher = TEXT_PATTERN.matcher(issueTxt); + var textMatcher = TEXT_PATTERN.matcher(issueTxt); if (textMatcher.matches()) { issueBuilder.setModuleName(textMatcher.group(1) + "." + headingSplit[headingSplit.length - 1]); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/SonarQubeParser.java b/src/main/java/edu/hm/hafner/analysis/parser/SonarQubeParser.java index e8af2a9e7..849495b12 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/SonarQubeParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/SonarQubeParser.java @@ -93,7 +93,7 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, private void extractIssues(final JSONArray elements, final Report report, final IssueBuilder issueBuilder) { for (Object object : elements) { if (object instanceof JSONObject) { - JSONObject issue = (JSONObject) object; + var issue = (JSONObject) object; if (filterIssue(issue)) { report.add(createIssueFromJsonObject(issue, issueBuilder)); } @@ -102,7 +102,7 @@ private void extractIssues(final JSONArray elements, final Report report, final } /** - * Get the components part to get the file paths on each issue (the component objects contain the most concise + * Get the "components" part to get the file paths on each issue (the component objects contain the most concise * path). * * @param jsonReport @@ -259,7 +259,7 @@ String parseModulePath(final JSONObject moduleKeyObject, final String componentK } /** - * Find the component in the components array which contains this key. + * Find the component in the components-array which contains this key. * * @param key * the key of the desired component. @@ -271,7 +271,7 @@ private JSONObject findComponentByKey(final String key) { if (components != null && key != null) { for (Object component : components) { if (component instanceof JSONObject) { - JSONObject jsonComponent = (JSONObject) component; + var jsonComponent = (JSONObject) component; if (key.equals(jsonComponent.optString(COMPONENT_KEY))) { return (JSONObject) component; } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/StyleCopParser.java b/src/main/java/edu/hm/hafner/analysis/parser/StyleCopParser.java index 284839762..19457b393 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/StyleCopParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/StyleCopParser.java @@ -3,9 +3,7 @@ import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; import edu.hm.hafner.analysis.IssueBuilder; import edu.hm.hafner.analysis.IssueParser; @@ -26,22 +24,22 @@ public class StyleCopParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { - Document document = readerFactory.readDocument(); + var document = readerFactory.readDocument(); // Pre v4.3 uses SourceAnalysisViolations as the parent node name - NodeList mainNode = document.getElementsByTagName("SourceAnalysisViolations"); + var mainNode = document.getElementsByTagName("SourceAnalysisViolations"); if (mainNode.getLength() == 0) { // v4.3 uses StyleCopViolations as the parent node name mainNode = document.getElementsByTagName("StyleCopViolations"); } - Element rootElement = (Element) mainNode.item(0); + var rootElement = (Element) mainNode.item(0); return parseViolations(XmlElementUtil.getChildElementsByName(rootElement, "Violation")); } private Report parseViolations(final List elements) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (Element element : elements) { issueBuilder.setFileName(getString(element, "Source")) .setLineStart(getLineNumber(element)) diff --git a/src/main/java/edu/hm/hafner/analysis/parser/TaglistParser.java b/src/main/java/edu/hm/hafner/analysis/parser/TaglistParser.java index 929c34245..6926a448a 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/TaglistParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/TaglistParser.java @@ -1,11 +1,9 @@ package edu.hm.hafner.analysis.parser; -import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -30,18 +28,18 @@ public class TaglistParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (IssueBuilder issueBuilder = new IssueBuilder()) { - XPathFactory xPathFactory = XPathFactory.newInstance(); - XPath xPath = xPathFactory.newXPath(); + var xPathFactory = XPathFactory.newInstance(); + var xPath = xPathFactory.newXPath(); - Report report = new Report(); + var report = new Report(); - Document document = readerFactory.readDocument(); - NodeList tags = (NodeList)xPath.evaluate("/report/tags/tag", document, XPathConstants.NODESET); + var document = readerFactory.readDocument(); + var tags = (NodeList)xPath.evaluate("/report/tags/tag", document, XPathConstants.NODESET); for (Element tag : XmlElementUtil.nodeListToList(tags)) { String category = xPath.evaluate("@name", tag); issueBuilder.setCategory(category); - NodeList files = (NodeList)xPath.evaluate("files/file", tag, XPathConstants.NODESET); + var files = (NodeList)xPath.evaluate("files/file", tag, XPathConstants.NODESET); for (Element file : XmlElementUtil.nodeListToList(files)) { String clazz = xPath.evaluate("@name", file); if (clazz != null) { @@ -50,7 +48,7 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException { issueBuilder.setAdditionalProperties(clazz); } - NodeList comments = (NodeList)xPath.evaluate("comments/comment", file, XPathConstants.NODESET); + var comments = (NodeList)xPath.evaluate("comments/comment", file, XPathConstants.NODESET); for (Element comment : XmlElementUtil.nodeListToList(comments)) { issueBuilder.setLineStart(xPath.evaluate("lineNumber", comment)); issueBuilder.setMessage(xPath.evaluate("comment", comment)); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/TrivyParser.java b/src/main/java/edu/hm/hafner/analysis/parser/TrivyParser.java index 2ad30d77a..ca7ba65d8 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/TrivyParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/TrivyParser.java @@ -49,9 +49,9 @@ protected void parseJsonArray(final Report report, final JSONArray jsonReport, f private void parseResults(final Report report, final JSONArray jsonReport, final IssueBuilder issueBuilder) { for (int i = 0; i < jsonReport.length(); i++) { - JSONObject component = (JSONObject) jsonReport.get(i); + var component = (JSONObject) jsonReport.get(i); if (!component.isNull("Vulnerabilities")) { - JSONArray vulnerabilities = component.getJSONArray("Vulnerabilities"); + var vulnerabilities = component.getJSONArray("Vulnerabilities"); for (Object vulnerability : vulnerabilities) { report.add(convertToIssue((JSONObject) vulnerability, issueBuilder)); } @@ -80,17 +80,15 @@ else if (TRIVY_VULNERABILITY_LEVEL_TAG_MEDIUM.equalsIgnoreCase(string)) { else if (TRIVY_VULNERABILITY_LEVEL_TAG_HIGH.equalsIgnoreCase(string)) { return Severity.WARNING_HIGH; } - else { - return Severity.ERROR; - } + return Severity.ERROR; } private String formatDescription(final JSONObject vulnerability) { - final String fileName = vulnerability.optString("PkgName", VALUE_NOT_SET); - final String installedVersion = vulnerability.optString("InstalledVersion", VALUE_NOT_SET); - final String fixedVersion = vulnerability.optString("FixedVersion", "still open"); - final String severity = vulnerability.optString("Severity", "UNKOWN"); - final String description = vulnerability.optString("Description", ""); + String fileName = vulnerability.optString("PkgName", VALUE_NOT_SET); + String installedVersion = vulnerability.optString("InstalledVersion", VALUE_NOT_SET); + String fixedVersion = vulnerability.optString("FixedVersion", "still open"); + String severity = vulnerability.optString("Severity", "UNKOWN"); + String description = vulnerability.optString("Description", ""); return join(p(div(b("File: "), text(fileName)), div(b("Installed Version: "), text(installedVersion)), div(b("Fixed Version: "), text(fixedVersion)), diff --git a/src/main/java/edu/hm/hafner/analysis/parser/VeraCodePipelineScannerParser.java b/src/main/java/edu/hm/hafner/analysis/parser/VeraCodePipelineScannerParser.java index 620fb44bb..436d7fa77 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/VeraCodePipelineScannerParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/VeraCodePipelineScannerParser.java @@ -32,9 +32,9 @@ protected void parseJsonObject(final Report report, final JSONObject jsonReport, private void parseFindings(final Report report, final JSONArray resources, final IssueBuilder issueBuilder) { for (int i = 0; i < resources.length(); i++) { - final Object item = resources.get(i); + Object item = resources.get(i); if (item instanceof JSONObject) { - final JSONObject finding = (JSONObject) item; + var finding = (JSONObject) item; report.add(convertToIssue(finding, issueBuilder)); } } @@ -80,9 +80,7 @@ private String getEnrichedFileName(final String rawFileName) { else if (StringUtils.endsWith(rawFileName, ".kt") && !StringUtils.startsWith(rawFileName, "src/main/kotlin/")) { return "src/main/kotlin/" + rawFileName; } - else { - return rawFileName; - } + return rawFileName; } private String getPackageName(final String scope) { @@ -96,19 +94,19 @@ private String getPackageName(final String scope) { /** * Retrieve source file values in a null safe manner. - * Veracode has nested json objects representing a source file ( files -> source_file -> values) for which we need + * Veracode has nested JSON objects representing a source file (files -> source_file -> values) for which we need * to do null checking. * * @param finding - * contains top level vulnerability information. + * contains top level vulnerability information * @param key - * used to retrieve values from nested source file. + * used to retrieve values from the nested source file * @param altValue - * in case there is a missing source file. + * in case there is a missing source file * @param - * type of the return value. + * type of the return value * - * @return field value of the source file. + * @return field value of the source file */ private T getSourceFileField(final JSONObject finding, final String key, final T altValue) { final JSONObject files = finding.optJSONObject("files"); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/XmlParser.java b/src/main/java/edu/hm/hafner/analysis/parser/XmlParser.java index 448c736f0..439106682 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/XmlParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/XmlParser.java @@ -5,7 +5,6 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -72,12 +71,12 @@ public boolean accepts(final ReaderFactory readerFactory) { @Override @SuppressFBWarnings("XPATH_INJECTION") public Report parse(final ReaderFactory readerFactory) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Document doc = readerFactory.readDocument(); - XPathFactory xPathFactory = XPathFactory.newInstance(); - XPath path = xPathFactory.newXPath(); - NodeList issues = (NodeList) path.evaluate(getXmlIssueRoot(), doc, XPathConstants.NODESET); + var doc = readerFactory.readDocument(); + var xPathFactory = XPathFactory.newInstance(); + var path = xPathFactory.newXPath(); + var issues = (NodeList) path.evaluate(getXmlIssueRoot(), doc, XPathConstants.NODESET); - Report report = new Report(); + var report = new Report(); for (Element issue : XmlElementUtil.nodeListToList(issues)) { issueBuilder.setFileName(path.evaluate(FILE_NAME, issue)) @@ -111,7 +110,7 @@ public Report parse(final ReaderFactory readerFactory) { * Reads line ranges from XPath. * * @param path - * path of current xml file. + * path of the current XML file. * @param lineRanges * list of lineRange nodes. * @@ -120,11 +119,11 @@ public Report parse(final ReaderFactory readerFactory) { * for xml reading errors. */ private LineRangeList readLineRanges(final XPath path, final NodeList lineRanges) throws XPathExpressionException { - LineRangeList ranges = new LineRangeList(); + var ranges = new LineRangeList(); for (Element lineRangeNode : XmlElementUtil.nodeListToList(lineRanges)) { if (lineRangeNode != null) { - Element startNode = (Element) path.evaluate(LINE_RANGE_START, lineRangeNode, XPathConstants.NODE); - Element endNode = (Element) path.evaluate(LINE_RANGE_END, lineRangeNode, XPathConstants.NODE); + var startNode = (Element) path.evaluate(LINE_RANGE_START, lineRangeNode, XPathConstants.NODE); + var endNode = (Element) path.evaluate(LINE_RANGE_END, lineRangeNode, XPathConstants.NODE); if (startNode != null && startNode.getFirstChild() != null && endNode != null && endNode.getFirstChild() != null) { String startValue = startNode.getFirstChild().getNodeValue().trim(); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/ccm/CcmParser.java b/src/main/java/edu/hm/hafner/analysis/parser/ccm/CcmParser.java index f4a0363ec..83f31b15a 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/ccm/CcmParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/ccm/CcmParser.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.io.Reader; +import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.xml.sax.SAXException; @@ -17,20 +18,20 @@ /** * A parser for CCM XML files. * - * @author Bruno P. Kinoshita - http://www.kinoshita.eti.br + * @author Bruno P. Kinoshita */ public class CcmParser extends IssueParser { private static final long serialVersionUID = -5172155190810975806L; @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { - Ccm report = parseCCMXmlFile(readerFactory); + var report = parseCcmXmlFile(readerFactory); return convert(report); } - private Ccm parseCCMXmlFile(final ReaderFactory ccmXmlFile) { - SecureDigester digester = new SecureDigester(CcmParser.class); + private Ccm parseCcmXmlFile(final ReaderFactory ccmXmlFile) { + var digester = new SecureDigester(CcmParser.class); String rootXPath = "ccm"; digester.addObjectCreate(rootXPath, Ccm.class); @@ -62,12 +63,12 @@ private Ccm parseCCMXmlFile(final ReaderFactory ccmXmlFile) { private Report convert(final Ccm collection) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (Metric metric : collection.getMetrics()) { Severity priority = calculateMetricPriority(metric); - String complexity = String.format("%s has a complexity of %d", metric.getUnit(), + String complexity = String.format(Locale.ENGLISH, "%s has a complexity of %d", metric.getUnit(), metric.getComplexity()); issueBuilder.setSeverity(priority) diff --git a/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleParser.java b/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleParser.java index 122b20f4c..0845c77eb 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleParser.java @@ -64,7 +64,7 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException { */ private Report convert(final CheckStyle collection) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (File file : collection.getFiles()) { if (isValidWarning(file)) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRules.java b/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRules.java index a8a6fef67..2a66fd549 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRules.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRules.java @@ -64,7 +64,7 @@ private void log(final Throwable exception) { * if digester is not configured properly */ private Digester createDigester() throws ParserConfigurationException { - SecureDigester digester = new SecureDigester(CheckStyleRules.class); + var digester = new SecureDigester(CheckStyleRules.class); String section = "*/section"; digester.addObjectCreate(section, Rule.class); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/TopicRule.java b/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/TopicRule.java index 5a9fa50e0..5213c4870 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/TopicRule.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/checkstyle/TopicRule.java @@ -56,7 +56,7 @@ public void end(final String namespace, final String name) */ @SuppressFBWarnings("SECURITY") private String extractNodeContent(final Element subsection) throws TransformerException { - StringWriter content = new StringWriter(); + var content = new StringWriter(); Transformer transformer = new SecureXmlParserFactory().createTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParser.java b/src/main/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParser.java index f4444b0ba..f6ade4b31 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParser.java @@ -55,10 +55,10 @@ protected void configureParser(final Digester digester) { @Override protected Report convertDuplicationsToIssues(final List duplications, final IssueBuilder issueBuilder) { - Report report = new Report(); + var report = new Report(); for (Duplication duplication : duplications) { - DuplicationGroup group = new DuplicationGroup(duplication.getCodeFragment()); + var group = new DuplicationGroup(duplication.getCodeFragment()); for (SourceFile file : duplication.getFiles()) { issueBuilder.setSeverity(getPriority(duplication.getLines())) .setLineStart(file.getLine()) diff --git a/src/main/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParser.java b/src/main/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParser.java index 233119c4a..f01de58ce 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParser.java @@ -67,10 +67,10 @@ protected void configureParser(final Digester digester) { @Override protected Report convertDuplicationsToIssues(final List duplications, final IssueBuilder issueBuilder) { - Report report = new Report(); + var report = new Report(); for (Duplicate duplication : duplications) { - DuplicationGroup group = new DuplicationGroup(); + var group = new DuplicationGroup(); for (Fragment fragment : duplication.getFragments()) { group.setCodeFragment(fragment.getText()); Range lineRange = fragment.getLineRange(); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParser.java b/src/main/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParser.java index 65b82f750..062488f7c 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParser.java @@ -54,10 +54,10 @@ protected void configureParser(final Digester digester) { @Override protected Report convertDuplicationsToIssues(final List duplications, final IssueBuilder issueBuilder) { - Report report = new Report(); + var report = new Report(); for (Set duplication : duplications) { - DuplicationGroup group = new DuplicationGroup(); + var group = new DuplicationGroup(); for (Block file : duplication.getBlocks()) { issueBuilder.setSeverity(getPriority(duplication.getLineCount())) .setLineStart(file.getStartLineNumber()) diff --git a/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessages.java b/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessages.java index 3904f4e92..1cd693732 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessages.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessages.java @@ -67,7 +67,7 @@ private void loadMessages(final String fileName, final Map messa * if we can't read the file */ public List parse(final InputStream file) throws IOException, SAXException { - SecureDigester digester = new SecureDigester(FindBugsMessages.class); + var digester = new SecureDigester(FindBugsMessages.class); List patterns = new ArrayList<>(); digester.push(patterns); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsParser.java b/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsParser.java index 84391c398..7342dfc89 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsParser.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -24,13 +23,11 @@ import edu.hm.hafner.util.LineRange; import edu.hm.hafner.util.LineRangeList; import edu.hm.hafner.util.VisibleForTesting; -import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.Project; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.annotations.CheckForNull; -import edu.umd.cs.findbugs.ba.SourceFile; import edu.umd.cs.findbugs.ba.SourceFinder; import static edu.hm.hafner.analysis.parser.findbugs.FindBugsParser.PriorityProperty.*; @@ -82,7 +79,7 @@ public FindBugsParser(final PriorityProperty priorityProperty) { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException { try (IssueBuilder builder = new IssueBuilder()) { - Collection sources = new ArrayList<>(); + List sources = new ArrayList<>(); String moduleRoot = StringUtils.substringBefore(readerFactory.getFileName(), "/target/"); sources.add(moduleRoot + "/src/main/java"); sources.add(moduleRoot + "/src/test/java"); @@ -153,10 +150,8 @@ private Report convertBugsToIssues(final Collection sources, final Issue builder.setModuleName(project.getProjectName()); } - Collection bugs = collection.getCollection(); - - Report report = new Report(); - for (BugInstance warning : bugs) { + var report = new Report(); + for (BugInstance warning : collection.getCollection()) { SourceLineAnnotation sourceLine = warning.getPrimarySourceLineAnnotation(); String message = warning.getMessage(); @@ -232,10 +227,10 @@ private Severity getPriority(final BugInstance warning) { @SuppressWarnings("PMD.DoNotUseThreads") private SortedBugCollection readXml(final Reader file) throws IOException, DocumentException { - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + var contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(FindBugsParser.class.getClassLoader()); - SortedBugCollection collection = new SortedBugCollection(); + var collection = new SortedBugCollection(); collection.readXML(file); return collection; } @@ -246,13 +241,13 @@ private SortedBugCollection readXml(final Reader file) throws IOException, Docum private void setAffectedLines(final BugInstance warning, final IssueBuilder builder, final LineRange primary) { - Iterator annotationIterator = warning.annotationIterator(); - LineRangeList lineRanges = new LineRangeList(); + var annotationIterator = warning.annotationIterator(); + var lineRanges = new LineRangeList(); while (annotationIterator.hasNext()) { - BugAnnotation bugAnnotation = annotationIterator.next(); + var bugAnnotation = annotationIterator.next(); if (bugAnnotation instanceof SourceLineAnnotation) { - SourceLineAnnotation annotation = (SourceLineAnnotation) bugAnnotation; - LineRange lineRange = new LineRange(annotation.getStartLine(), annotation.getEndLine()); + var annotation = (SourceLineAnnotation) bugAnnotation; + var lineRange = new LineRange(annotation.getStartLine(), annotation.getEndLine()); if (!lineRanges.contains(lineRange) && !primary.equals(lineRange)) { lineRanges.add(lineRange); } @@ -263,7 +258,7 @@ private void setAffectedLines(final BugInstance warning, final IssueBuilder buil private String findSourceFile(final SourceFinder sourceFinder, final SourceLineAnnotation sourceLine) { try { - SourceFile sourceFile = sourceFinder.findSourceFile(sourceLine); + var sourceFile = sourceFinder.findSourceFile(sourceLine); return sourceFile.getFullFileName(); } catch (IOException ignored) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/fxcop/FxCopParser.java b/src/main/java/edu/hm/hafner/analysis/parser/fxcop/FxCopParser.java index 99962a147..75de64013 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/fxcop/FxCopParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/fxcop/FxCopParser.java @@ -1,10 +1,6 @@ package edu.hm.hafner.analysis.parser.fxcop; -import java.util.Optional; - -import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; import edu.hm.hafner.analysis.IssueBuilder; import edu.hm.hafner.analysis.IssueParser; @@ -36,11 +32,11 @@ private static class XmlParser { public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Document doc = readerFactory.readDocument(); + var doc = readerFactory.readDocument(); - NodeList mainNode = doc.getElementsByTagName("FxCopReport"); + var mainNode = doc.getElementsByTagName("FxCopReport"); - Element rootElement = (Element) mainNode.item(0); + var rootElement = (Element) mainNode.item(0); parseRules(rootElement, issueBuilder); parseNamespaces(rootElement, issueBuilder); parseTargets(rootElement, issueBuilder); @@ -50,7 +46,7 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException, } private void parseRules(final Element rootElement, final IssueBuilder issueBuilder) { - Optional rulesElement = XmlElementUtil.getFirstChildElementByName(rootElement, "Rules"); + var rulesElement = XmlElementUtil.getFirstChildElementByName(rootElement, "Rules"); if (rulesElement.isPresent()) { for (Element rule : XmlElementUtil.getChildElementsByName(rulesElement.get(), "Rule")) { ruleSet.addRule(rule); @@ -59,7 +55,7 @@ private void parseRules(final Element rootElement, final IssueBuilder issueBuild } private void parseTargets(final Element rootElement, final IssueBuilder issueBuilder) { - Optional targetsElement = XmlElementUtil.getFirstChildElementByName(rootElement, "Targets"); + var targetsElement = XmlElementUtil.getFirstChildElementByName(rootElement, "Targets"); if (targetsElement.isPresent()) { for (Element target : XmlElementUtil.getChildElementsByName(targetsElement.get(), "Target")) { String name = getString(target, "Name"); @@ -72,7 +68,7 @@ private void parseTargets(final Element rootElement, final IssueBuilder issueBui private void parseResources(final Element target, final String parentName, final IssueBuilder issueBuilder) { - Optional resources = XmlElementUtil.getFirstChildElementByName(target, "Resources"); + var resources = XmlElementUtil.getFirstChildElementByName(target, "Resources"); if (resources.isPresent()) { for (Element resource : XmlElementUtil.getChildElementsByName(resources.get(), "Resource")) { String name = getString(resource, "Name"); @@ -83,7 +79,7 @@ private void parseResources(final Element target, final String parentName, private void parseModules(final Element target, final String parentName, final IssueBuilder issueBuilder) { - Optional modulesElement = XmlElementUtil.getFirstChildElementByName(target, "Modules"); + var modulesElement = XmlElementUtil.getFirstChildElementByName(target, "Modules"); if (modulesElement.isPresent()) { for (Element module : XmlElementUtil.getChildElementsByName(modulesElement.get(), "Module")) { String name = getString(module, "Name"); @@ -94,7 +90,7 @@ private void parseModules(final Element target, final String parentName, } private void parseNamespaces(final Element rootElement, final IssueBuilder issueBuilder) { - Optional namespacesElement = XmlElementUtil.getFirstChildElementByName(rootElement, "Namespaces"); + var namespacesElement = XmlElementUtil.getFirstChildElementByName(rootElement, "Namespaces"); if (namespacesElement.isPresent()) { for (Element namespace : XmlElementUtil.getChildElementsByName(namespacesElement.get(), "Namespace")) { String name = getString(namespace, "Name"); @@ -107,7 +103,7 @@ private void parseNamespaces(final Element rootElement, final IssueBuilder issue private void parseTypes(final Element typesElement, final String parentName, final IssueBuilder issueBuilder) { - Optional types = XmlElementUtil.getFirstChildElementByName(typesElement, "Types"); + var types = XmlElementUtil.getFirstChildElementByName(typesElement, "Types"); if (types.isPresent()) { for (Element type : XmlElementUtil.getChildElementsByName(types.get(), "Type")) { String name = parentName + "." + getString(type, "Name"); @@ -120,7 +116,7 @@ private void parseTypes(final Element typesElement, final String parentName, private void parseMembers(final Element members, final String parentName, final IssueBuilder issueBuilder) { - Optional membersElement = XmlElementUtil.getFirstChildElementByName(members, "Members"); + var membersElement = XmlElementUtil.getFirstChildElementByName(members, "Members"); if (membersElement.isPresent()) { for (Element member : XmlElementUtil.getChildElementsByName(membersElement.get(), "Member")) { parseMember(member, parentName, issueBuilder); @@ -130,7 +126,7 @@ private void parseMembers(final Element members, final String parentName, private void parseAccessors(final Element accessorsElement, final String parentName, final IssueBuilder issueBuilder) { - Optional accessors = XmlElementUtil.getFirstChildElementByName(accessorsElement, "Accessors"); + var accessors = XmlElementUtil.getFirstChildElementByName(accessorsElement, "Accessors"); if (accessors.isPresent()) { for (Element member : XmlElementUtil.getChildElementsByName(accessors.get(), "Accessor")) { parseMember(member, parentName, issueBuilder); @@ -146,7 +142,7 @@ private void parseMember(final Element member, final String parentName, private void parseMessages(final Element messages, final String parentName, final IssueBuilder issueBuilder) { - Optional messagesElement = XmlElementUtil.getFirstChildElementByName(messages, "Messages"); + var messagesElement = XmlElementUtil.getFirstChildElementByName(messages, "Messages"); if (messagesElement.isPresent()) { for (Element message : XmlElementUtil.getChildElementsByName(messagesElement.get(), "Message")) { for (Element issue : XmlElementUtil.getChildElementsByName(message, "Issue")) { @@ -163,8 +159,8 @@ private void parseIssue(final Element issue, final Element parent, final String String checkId = getString(parent, "CheckId"); String issueLevel = getString(issue, "Level"); - StringBuilder msgBuilder = new StringBuilder(CAPACITY); - FxCopRule rule = ruleSet.getRule(category, checkId); + var msgBuilder = new StringBuilder(CAPACITY); + var rule = ruleSet.getRule(category, checkId); if (rule == null) { msgBuilder.append(typeName); } diff --git a/src/main/java/edu/hm/hafner/analysis/parser/gendarme/GendarmeParser.java b/src/main/java/edu/hm/hafner/analysis/parser/gendarme/GendarmeParser.java index e7ad48b96..049f016e2 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/gendarme/GendarmeParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/gendarme/GendarmeParser.java @@ -9,9 +9,7 @@ import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; -import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; import edu.hm.hafner.analysis.IssueBuilder; import edu.hm.hafner.analysis.IssueParser; @@ -38,13 +36,13 @@ public class GendarmeParser extends IssueParser { @Override public Report parse(final ReaderFactory factory) throws ParsingException { - Document document = factory.readDocument(); + var document = factory.readDocument(); - NodeList mainNode = document.getElementsByTagName("gendarme-output"); + var mainNode = document.getElementsByTagName("gendarme-output"); - Element rootElement = (Element) mainNode.item(0); - Element resultsElement = (Element) rootElement.getElementsByTagName("results").item(0); - Element rulesElement = (Element) rootElement.getElementsByTagName("rules").item(0); + var rootElement = (Element) mainNode.item(0); + var resultsElement = (Element) rootElement.getElementsByTagName("results").item(0); + var rulesElement = (Element) rootElement.getElementsByTagName("rules").item(0); Map rules = parseRules(XmlElementUtil.getChildElementsByName(rulesElement, "rule")); return parseViolations(XmlElementUtil.getChildElementsByName(resultsElement, "rule"), rules); @@ -52,16 +50,16 @@ public Report parse(final ReaderFactory factory) throws ParsingException { private Report parseViolations(final List ruleElements, final Map rules) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report warnings = new Report(); + var warnings = new Report(); for (Element ruleElement : ruleElements) { String ruleName = ruleElement.getAttribute("Name"); String problem = ruleElement.getElementsByTagName("problem").item(0).getTextContent(); List targetElements = XmlElementUtil.getChildElementsByName(ruleElement, "target"); - GendarmeRule rule = rules.get(ruleName); + var rule = rules.get(ruleName); if (rule != null) { for (Element targetElement : targetElements) { - Element defectElement = (Element) targetElement.getElementsByTagName("defect").item(0); + var defectElement = (Element) targetElement.getElementsByTagName("defect").item(0); String source = defectElement.getAttribute("Source"); String fileName = extractFileNameMatch(rule, source, 1); @@ -106,8 +104,8 @@ private String extractFileNameMatch(final GendarmeRule rule, final String source private Map parseRules(final List ruleElements) { Map rules = new HashMap<>(); - for (Element ruleElement : ruleElements) { - GendarmeRule rule = new GendarmeRule(); + for (var ruleElement : ruleElements) { + var rule = new GendarmeRule(); rule.setName(ruleElement.getAttribute("Name")); rule.setTypeName(ruleElement.getTextContent()); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/jcreport/JcReportParser.java b/src/main/java/edu/hm/hafner/analysis/parser/jcreport/JcReportParser.java index da46cf2ed..697fb14df 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/jcreport/JcReportParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/jcreport/JcReportParser.java @@ -24,7 +24,7 @@ public class JcReportParser extends IssueParser { public Report parse(final ReaderFactory reader) { try (IssueBuilder issueBuilder = new IssueBuilder()) { edu.hm.hafner.analysis.parser.jcreport.Report report = createReport(reader); - Report warnings = new Report(); + var warnings = new Report(); for (int i = 0; i < report.getFiles().size(); i++) { File file = report.getFiles().get(i); @@ -58,7 +58,7 @@ public Report parse(final ReaderFactory reader) { */ public edu.hm.hafner.analysis.parser.jcreport.Report createReport(final ReaderFactory readerFactory) throws ParsingException { - SecureDigester digester = new SecureDigester(JcReportParser.class); + var digester = new SecureDigester(JcReportParser.class); String report = "report"; digester.addObjectCreate(report, edu.hm.hafner.analysis.parser.jcreport.Report.class); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdMessages.java b/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdMessages.java index 7e3f1988d..7a2ef167b 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdMessages.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdMessages.java @@ -24,8 +24,8 @@ public class PmdMessages { * Loads the available rules into a map. */ public PmdMessages() { - RuleSetLoader loader = new RuleSetLoader(); - List ruleSets = loader.getStandardRuleSets(); + var loader = new RuleSetLoader(); + var ruleSets = loader.getStandardRuleSets(); for (RuleSet ruleSet : ruleSets) { rules.put(ruleSet.getName(), ruleSet); } @@ -55,8 +55,8 @@ public int size() { */ public String getMessage(final String ruleSetName, final String ruleName) { if (rules.containsKey(ruleSetName)) { - RuleSet ruleSet = rules.get(ruleSetName); - Rule rule = ruleSet.getRuleByName(ruleName); + var ruleSet = rules.get(ruleSetName); + var rule = ruleSet.getRuleByName(ruleName); if (rule != null) { return createMessage(rule); } @@ -73,7 +73,7 @@ public String getMessage(final String ruleSetName, final String ruleName) { * @return the message string to be shown for the specified rule */ private String createMessage(final Rule rule) { - StringBuilder message = new StringBuilder(rule.getDescription()); + var message = new StringBuilder(rule.getDescription()); List examples = rule.getExamples(); if (!examples.isEmpty()) { message.append(pre().with(code(examples.get(0))).renderFormatted()); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdParser.java b/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdParser.java index b23910c90..ab49e1898 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/pmd/PmdParser.java @@ -35,7 +35,7 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException { } private Report parseIssues(final ReaderFactory readerFactory) { - SecureDigester digester = new SecureDigester(PmdParser.class); + var digester = new SecureDigester(PmdParser.class); String rootXPath = "pmd"; digester.addObjectCreate(rootXPath, Pmd.class); @@ -66,7 +66,7 @@ private Report parseIssues(final ReaderFactory readerFactory) { } private Report parseErrors(final ReaderFactory readerFactory) { - SecureDigester digester = new SecureDigester(PmdParser.class); + var digester = new SecureDigester(PmdParser.class); String rootXPath = "pmd"; digester.addObjectCreate(rootXPath, Pmd.class); @@ -93,7 +93,7 @@ private Report parseErrors(final ReaderFactory readerFactory) { private Report convertIssues(final Pmd pmdIssues) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (File file : pmdIssues.getFiles()) { for (Violation warning : file.getViolations()) { issueBuilder.setSeverity(mapPriority(warning)) @@ -115,7 +115,7 @@ private Report convertIssues(final Pmd pmdIssues) { private Report convertErrors(final Pmd pmdIssues) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (PmdError error : pmdIssues.getErrors()) { issueBuilder.setSeverity(Severity.ERROR) .setMessage(error.getMsg()) diff --git a/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PVSStudioParser.java b/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PVSStudioParser.java index 0beb0a86e..55ad6f125 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PVSStudioParser.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PVSStudioParser.java @@ -1,7 +1,5 @@ package edu.hm.hafner.analysis.parser.pvsstudio; -import java.util.List; - import edu.hm.hafner.analysis.IssueBuilder; import edu.hm.hafner.analysis.IssueParser; import edu.hm.hafner.analysis.ParsingCanceledException; @@ -39,11 +37,9 @@ else if (SEVERITY_LOW.equals(level)) { @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException { try (IssueBuilder issueBuilder = new IssueBuilder()) { - List plogMessages = PlogMessage.getMessagesFromReport(readerFactory); - - Report report = new Report(); + var report = new Report(); - for (PlogMessage plogMessage : plogMessages) { + for (PlogMessage plogMessage : PlogMessage.getMessagesFromReport(readerFactory)) { issueBuilder.setFileName(plogMessage.getFilePath()); issueBuilder.setSeverity(getSeverity(plogMessage.getLevel())); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PlogMessage.java b/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PlogMessage.java index 43fc78aa8..361f7b6d8 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PlogMessage.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/pvsstudio/PlogMessage.java @@ -68,17 +68,17 @@ private static boolean errorCodeIsValid(final String errorCode) { } private static void processNode(final List plogMessages, final Node node) { - Element eElement = (Element) node; + var eElement = (Element) node; - NodeList nodeFalseAlarm = eElement.getElementsByTagName("FalseAlarm"); + var nodeFalseAlarm = eElement.getElementsByTagName("FalseAlarm"); if (skipMessage(nodeFalseAlarm)) { ++falseAlarmCount; return; } - NodeList nodeFile = eElement.getElementsByTagName("File"); + var nodeFile = eElement.getElementsByTagName("File"); - PlogMessage msg = new PlogMessage(); + var msg = new PlogMessage(); if (nodeNotNull(nodeFile)) { msg.file = nodeFile.item(0).getTextContent().trim(); @@ -89,7 +89,7 @@ private static void processNode(final List plogMessages, final Node return; } - NodeList nodeErrorCode = eElement.getElementsByTagName("ErrorCode"); + var nodeErrorCode = eElement.getElementsByTagName("ErrorCode"); if (nodeNotNull(nodeErrorCode)) { msg.errorCode = nodeErrorCode.item(0).getTextContent().trim(); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptions.java b/src/main/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptions.java index 778a73af0..8c1f02323 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptions.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptions.java @@ -24,12 +24,12 @@ public class PyLintDescriptions { */ @SuppressWarnings("PMD.LooseCoupling") public PyLintDescriptions() { - JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE); + var parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE); try (InputStream inputStream = PyLintDescriptions.class.getResourceAsStream("pylint-descriptions.json")) { - JSONArray elements = (JSONArray) parser.parse(inputStream); + var elements = (JSONArray) parser.parse(inputStream); for (Object element : elements) { - JSONObject object = (JSONObject) element; + var object = (JSONObject) element; String description = object.getAsString("description"); descriptionByName.put(object.getAsString("name"), description); descriptionById.put(object.getAsString("code"), description); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/violations/AbstractViolationAdapter.java b/src/main/java/edu/hm/hafner/analysis/parser/violations/AbstractViolationAdapter.java index 90ec0bebe..cfb0534c3 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/violations/AbstractViolationAdapter.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/violations/AbstractViolationAdapter.java @@ -61,7 +61,7 @@ public Report parse(final ReaderFactory readerFactory) */ Report convertToReport(final Set violations) { try (IssueBuilder builder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (Violation violation : violations) { if (isValid(violation)) { diff --git a/src/main/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapter.java b/src/main/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapter.java index 68b179761..8a7969dbe 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapter.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapter.java @@ -2,7 +2,6 @@ import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -30,15 +29,15 @@ CPPCheckParser createParser() { @Override Report convertToReport(final Set violations) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Map> violationsPerGroup = - new LinkedHashSet<>(violations).stream().collect(Collectors.groupingBy(Violation::getGroup)); + var violationsPerGroup = new LinkedHashSet<>(violations).stream() + .collect(Collectors.groupingBy(Violation::getGroup)); - Report report = new Report(); + var report = new Report(); for (List group : violationsPerGroup.values()) { updateIssueBuilder(group.get(0), issueBuilder); - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); for (int i = 1; i < group.size(); i++) { - Violation violation = group.get(i); + var violation = group.get(i); lineRanges.add(new LineRange(violation.getStartLine())); } issueBuilder.setLineRanges(lineRanges); diff --git a/src/main/java/edu/hm/hafner/analysis/parser/violations/ValgrindAdapter.java b/src/main/java/edu/hm/hafner/analysis/parser/violations/ValgrindAdapter.java index a9c7c789d..4952d9ae1 100644 --- a/src/main/java/edu/hm/hafner/analysis/parser/violations/ValgrindAdapter.java +++ b/src/main/java/edu/hm/hafner/analysis/parser/violations/ValgrindAdapter.java @@ -4,7 +4,6 @@ import java.util.Set; import org.apache.commons.lang3.StringUtils; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -12,15 +11,15 @@ import edu.hm.hafner.analysis.IssueBuilder; import edu.hm.hafner.analysis.Report; - import edu.umd.cs.findbugs.annotations.CheckForNull; import j2html.tags.ContainerTag; -import static j2html.TagCreator.*; - +import j2html.tags.DomContentJoiner; import se.bjurr.violations.lib.model.Violation; import se.bjurr.violations.lib.parsers.ValgrindParser; +import static j2html.TagCreator.*; + /** * Parses Valgrind XML report files. * @@ -39,7 +38,7 @@ ValgrindParser createParser() { @Override Report convertToReport(final Set violations) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (Violation violation: violations) { updateIssueBuilder(violation, issueBuilder); @@ -53,11 +52,10 @@ Report convertToReport(final Set violations) { } private String generateDescriptionHtml(final Violation violation) { - final Map specifics = violation.getSpecifics(); - final JSONArray auxWhats = getAuxWhatsArray(specifics); + var specifics = violation.getSpecifics(); + var auxWhats = getAuxWhatsArray(specifics); - return - j2html.tags.DomContentJoiner.join( + return DomContentJoiner.join( "", false, generateGeneralTableHtml(violation.getSource(), violation.getGroup(), specifics.get("tid"), specifics.get("threadname"), auxWhats), @@ -85,15 +83,16 @@ private ContainerTag generateGeneralTableHtml(final String executable, final Str return generalTable; } - private @CheckForNull ContainerTag maybeGenerateStackTracesHtml(@CheckForNull final String stacksJson, final String message, @CheckForNull final JSONArray auxWhats) { + @CheckForNull + private ContainerTag maybeGenerateStackTracesHtml(@CheckForNull final String stacksJson, final String message, @CheckForNull final JSONArray auxWhats) { if (StringUtils.isBlank(stacksJson)) { return null; } - final JSONArray stacks = new JSONArray(new JSONTokener(stacksJson)); + var stacks = new JSONArray(new JSONTokener(stacksJson)); if (!stacks.isEmpty()) { - ContainerTag stackTraces = div(); + var stackTraces = div(); stackTraces.with(generateStackTraceHtml("Primary Stack Trace", message, stacks.getJSONArray(0))); @@ -120,7 +119,7 @@ private ContainerTag generateGeneralTableHtml(final String executable, final Str } private ContainerTag generateStackTraceHtml(final String title, @CheckForNull final String message, final JSONArray frames) { - ContainerTag stackTraceContainer = + var stackTraceContainer = div( br(), h4(title), @@ -128,7 +127,7 @@ private ContainerTag generateStackTraceHtml(final String title, @CheckForNull fi ); for (int frameIndex = 0; frameIndex < frames.length(); ++frameIndex) { - final JSONObject frame = frames.getJSONObject(frameIndex); + var frame = frames.getJSONObject(frameIndex); if (frameIndex > 0) { stackTraceContainer.with(br()); @@ -161,13 +160,14 @@ private ContainerTag maybeGenerateTableRowHtml(final String name, @CheckForNull return iff(StringUtils.isNotBlank(value), tr(td(text(name), td(text(value))))); } - private @CheckForNull ContainerTag maybeGenerateStackFrameFileTableRowHtml(final JSONObject frame) throws JSONException { - final String file = frame.optString("file"); + @CheckForNull + private ContainerTag maybeGenerateStackFrameFileTableRowHtml(final JSONObject frame) throws JSONException { + String file = frame.optString("file"); if (StringUtils.isNotBlank(file)) { - final String dir = frame.optString("dir"); - final int line = frame.optInt("line", NO_LINE); - final StringBuilder fileBuilder = new StringBuilder(256); + String dir = frame.optString("dir"); + int line = frame.optInt("line", NO_LINE); + var fileBuilder = new StringBuilder(256); if (StringUtils.isNotBlank(dir)) { fileBuilder.append(dir).append('/'); @@ -187,7 +187,7 @@ private ContainerTag maybeGenerateTableRowHtml(final String name, @CheckForNull @CheckForNull private JSONArray getAuxWhatsArray(final Map specifics) { - final String auxWhatsJson = specifics.get("auxwhats"); + String auxWhatsJson = specifics.get("auxwhats"); return StringUtils.isNotBlank(auxWhatsJson) ? new JSONArray(new JSONTokener(auxWhatsJson)) : null; } -} \ No newline at end of file +} diff --git a/src/main/java/edu/hm/hafner/analysis/registry/CompositeParserDescriptor.java b/src/main/java/edu/hm/hafner/analysis/registry/CompositeParserDescriptor.java index 9eeff1340..776e9b350 100644 --- a/src/main/java/edu/hm/hafner/analysis/registry/CompositeParserDescriptor.java +++ b/src/main/java/edu/hm/hafner/analysis/registry/CompositeParserDescriptor.java @@ -78,7 +78,7 @@ private static class CompositeParser extends IssueParser { @Override public Report parse(final ReaderFactory readerFactory) { - Report aggregated = new Report(); + var aggregated = new Report(); for (IssueParser parser : parsers) { if (parser.accepts(readerFactory)) { aggregated.addAll(parser.parse(readerFactory)); diff --git a/src/test/java/edu/hm/hafner/analysis/AbstractModuleDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/AbstractModuleDetectorTest.java index 6f55c3591..409d6230d 100644 --- a/src/test/java/edu/hm/hafner/analysis/AbstractModuleDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/AbstractModuleDetectorTest.java @@ -33,7 +33,7 @@ void shouldIgnoreExceptionsDuringParsing() { when(stub.open(anyString())).thenThrow(new FileNotFoundException("File not found")); }); - ModuleDetector detector = new ModuleDetector(ROOT, fileSystem); + var detector = new ModuleDetector(ROOT, fileSystem); assertThat(detector.guessModuleName(PREFIX + getFileName())).isEqualTo(StringUtils.EMPTY); } diff --git a/src/test/java/edu/hm/hafner/analysis/AntModuleDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/AntModuleDetectorTest.java index c03256bba..4710ebdc0 100644 --- a/src/test/java/edu/hm/hafner/analysis/AntModuleDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/AntModuleDetectorTest.java @@ -3,7 +3,6 @@ import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; -import edu.hm.hafner.analysis.ModuleDetector.FileSystem; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static org.assertj.core.api.Assertions.*; @@ -31,11 +30,11 @@ String getProjectFileName() { @Test void shouldIdentifyModuleByReadingAntProjectFile() { - FileSystem factory = createFileSystemStub(stub -> { + var factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_ANT + AntModuleDetector.ANT_PROJECT}); when(stub.open(anyString())).thenAnswer(filename -> read(AntModuleDetector.ANT_PROJECT)); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_ANT + "something.txt")) .isEqualTo(EXPECTED_ANT_MODULE); diff --git a/src/test/java/edu/hm/hafner/analysis/CSharpNamespaceDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/CSharpNamespaceDetectorTest.java index 7db28ce1d..0ecfdf2aa 100644 --- a/src/test/java/edu/hm/hafner/analysis/CSharpNamespaceDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/CSharpNamespaceDetectorTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.params.provider.CsvSource; import edu.hm.hafner.util.ResourceTest; + import static org.assertj.core.api.Assertions.*; /** @@ -34,7 +35,7 @@ void shouldExtractPackageNameFromJavaSource(final String fileName, final String @Test void shouldAcceptCorrectFileSuffix() { - CSharpNamespaceDetector namespaceDetector = new CSharpNamespaceDetector(); + var namespaceDetector = new CSharpNamespaceDetector(); assertThat(namespaceDetector.accepts("ActionBinding.cs")) .as("Does not accept a C# file.").isTrue(); assertThat(namespaceDetector.accepts("ActionBinding.cs.c")) diff --git a/src/test/java/edu/hm/hafner/analysis/DuplicationGroupTest.java b/src/test/java/edu/hm/hafner/analysis/DuplicationGroupTest.java index 7ffd0f38e..df9dae26d 100644 --- a/src/test/java/edu/hm/hafner/analysis/DuplicationGroupTest.java +++ b/src/test/java/edu/hm/hafner/analysis/DuplicationGroupTest.java @@ -25,7 +25,7 @@ class DuplicationGroupTest extends SerializableTest { @Override protected DuplicationGroup createSerializable() { - DuplicationGroup group = new DuplicationGroup(); + var group = new DuplicationGroup(); try (IssueBuilder builder = new IssueBuilder()) { group.add(builder.setAdditionalProperties(group).setFileName("1").build()); @@ -54,7 +54,7 @@ void shouldReadIssueFromOldSerialization() { @Test void shouldBeEmptyWhenCreated() { - DuplicationGroup group = new DuplicationGroup(); + var group = new DuplicationGroup(); assertThat(group.getCodeFragment()).isEmpty(); assertThat(group.getDuplications()).isEmpty(); @@ -62,7 +62,7 @@ void shouldBeEmptyWhenCreated() { @Test void shouldNotOverwriteFragmentOnceItHasBeenSet() { - DuplicationGroup group = new DuplicationGroup(); + var group = new DuplicationGroup(); assertThat(group.getCodeFragment()).isEmpty(); @@ -72,7 +72,7 @@ void shouldNotOverwriteFragmentOnceItHasBeenSet() { group.setCodeFragment("other"); assertThat(group.getCodeFragment()).isEqualTo(CODE_FRAGMENT); - DuplicationGroup groupWithFragment = new DuplicationGroup(CODE_FRAGMENT); + var groupWithFragment = new DuplicationGroup(CODE_FRAGMENT); assertThat(groupWithFragment.getCodeFragment()).isEqualTo(CODE_FRAGMENT); groupWithFragment.setCodeFragment("other"); @@ -82,7 +82,7 @@ void shouldNotOverwriteFragmentOnceItHasBeenSet() { @Test void shouldReferenceAllDuplications() { try (IssueBuilder builder = new IssueBuilder()) { - DuplicationGroup group = new DuplicationGroup(CODE_FRAGMENT); + var group = new DuplicationGroup(CODE_FRAGMENT); assertThat(group.getDuplications()).isEmpty(); @@ -100,9 +100,9 @@ void shouldReferenceAllDuplications() { @Test void shouldObeyEqualsContract() { try (IssueBuilder builder = new IssueBuilder()) { - LineRangeList red = new LineRangeList(); + var red = new LineRangeList(); red.add(new LineRange(1)); - LineRangeList blue = new LineRangeList(); + var blue = new LineRangeList(); blue.add(new LineRange(2)); EqualsVerifier .forClass(DuplicationGroup.class) diff --git a/src/test/java/edu/hm/hafner/analysis/FileNameResolverTest.java b/src/test/java/edu/hm/hafner/analysis/FileNameResolverTest.java index 6d67006ec..36f28c845 100644 --- a/src/test/java/edu/hm/hafner/analysis/FileNameResolverTest.java +++ b/src/test/java/edu/hm/hafner/analysis/FileNameResolverTest.java @@ -46,7 +46,7 @@ class FileNameResolverTest { @ValueSource(strings = {"/does/not/exist", "!<>$&/&(", "\0 Null-Byte", "C:/!<>$&/&( \0", "/!<>$&/&( \0"}) @DisplayName("Should not change path on errors") void shouldReturnFallbackOnError(final String fileName) { - Report report = createIssuesSingleton(fileName, new IssueBuilder()); + var report = createIssuesSingleton(fileName, new IssueBuilder()); resolvePaths(report, RESOURCE_FOLDER_PATH); @@ -66,7 +66,7 @@ private void resolvePaths(final Report report, final Path resourceFolderPath, @Test @DisplayName("Should skip processing if there are no issues") void shouldDoNothingIfNoIssuesPresent() { - Report report = new Report(); + var report = new Report(); resolvePaths(report, RESOURCE_FOLDER_PATH); @@ -77,7 +77,7 @@ void shouldDoNothingIfNoIssuesPresent() { @Test @DisplayName("Should set path if the relative file name exists") void shouldSetPath() { - Report report = new Report(); + var report = new Report(); try (IssueBuilder builder = new IssueBuilder()) { report.add(builder.setFileName(RELATIVE_FILE).build()); @@ -98,7 +98,7 @@ void shouldSetPath() { @Test @DisplayName("Should not set path if the relative file name doe not exist") void shouldNotSetPath() { - Report report = new Report(); + var report = new Report(); try (IssueBuilder builder = new IssueBuilder()) { report.add(builder.setFileName("not here").build()); @@ -119,7 +119,7 @@ void shouldNotSetPath() { @Test @DisplayName("Should skip existing absolute paths") void shouldNotTouchAbsolutePathOrEmptyPath() { - Report report = new Report(); + var report = new Report(); try (IssueBuilder builder = new IssueBuilder()) { report.add(builder.setFileName("").build()); @@ -170,8 +170,7 @@ void shouldNotTouchAbsolutePathOrEmptyPath() { @DisplayName("Should normalize different relative paths to the same file (file name is relative)") void shouldResolveRelativePath(final String fileName) { try (IssueBuilder builder = new IssueBuilder()) { - Report report; - report = createIssuesSingleton(fileName, builder.setOrigin(ID)); + var report = createIssuesSingleton(fileName, builder.setOrigin(ID)); resolvePaths(report, RESOURCE_FOLDER_PATH); assertThatFileResolvesToRelativeFile(report, fileName); @@ -183,12 +182,11 @@ void shouldResolveRelativePath(final String fileName) { @DisplayName("Should normalize different relative paths to the same file (file name is absolute)") void shouldNormalizePaths(final String fileName) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Report report = new Report(); - Issue issue; - issue = issueBuilder + Issue issue = issueBuilder .setDirectory(RESOURCE_FOLDER_STRING) .setFileName(normalize(fileName)) .build(); + var report = new Report(); report.add(issue); resolvePaths(report, Paths.get(RESOURCE_FOLDER)); @@ -252,7 +250,7 @@ private static boolean isWindows() { } private Report createIssuesSingleton(final String fileName, final IssueBuilder issueBuilder) { - Report report = new Report(); + var report = new Report(); Issue issue = issueBuilder.setFileName(fileName).build(); report.add(issue); return report; diff --git a/src/test/java/edu/hm/hafner/analysis/FileReaderFactoryTest.java b/src/test/java/edu/hm/hafner/analysis/FileReaderFactoryTest.java index 974042834..a7a4f0633 100644 --- a/src/test/java/edu/hm/hafner/analysis/FileReaderFactoryTest.java +++ b/src/test/java/edu/hm/hafner/analysis/FileReaderFactoryTest.java @@ -26,7 +26,7 @@ class FileReaderFactoryTest extends ResourceTest { @Test void shouldRemoveColorCodesAfterAllLineMappers() { - ConsoleLogReaderFactory factory = new ConsoleLogReaderFactory( + var factory = new ConsoleLogReaderFactory( getResourceAsFile("ath-colored.log")); assertThat(factory.readString()).isEqualTo("[WARNING]\n" diff --git a/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorBenchmark.java b/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorBenchmark.java index 003746567..c8302951f 100644 --- a/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorBenchmark.java +++ b/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorBenchmark.java @@ -28,7 +28,7 @@ public class FingerprintGeneratorBenchmark extends AbstractBenchmark { */ @Benchmark public void benchmarkingOneIssue(final BenchmarkState state) { - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); generator.run(state.getFullTextFingerprint(), state.getSingleIssueReport(), CHARSET_AFFECTED_FILE); } @@ -41,7 +41,7 @@ public void benchmarkingOneIssue(final BenchmarkState state) { */ @Benchmark public void benchmarkingMultipleIssues(final BenchmarkState state) { - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); generator.run(new FullTextFingerprint(), state.getMultipleIssuesReport(), CHARSET_AFFECTED_FILE); } @@ -57,6 +57,7 @@ public static class BenchmarkState { private Report singleIssueReport = new Report(); private FullTextFingerprint fingerprint = new FullTextFingerprint(); private Report multipleIssuesReport = new Report(); + @SuppressWarnings("NullAway") private Random random; public Report getSingleIssueReport() { @@ -87,7 +88,7 @@ public void doSetup() { @SuppressFBWarnings("PREDICTABLE_RANDOM") private Report createMultipleIssues(final int number) { - Report report = new Report(); + var report = new Report(); try (IssueBuilder builder = new IssueBuilder()) { builder.setFileName(AFFECTED_FILE_NAME); for (int i = 0; i < number; i++) { diff --git a/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorTest.java b/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorTest.java index 1874563fc..24d529584 100644 --- a/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/FingerprintGeneratorTest.java @@ -27,7 +27,7 @@ class FingerprintGeneratorTest extends ResourceTest { @Test void shouldSkipFingerprintingIfEncodingIsWrong() throws IOException { - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); Report report; try (IssueBuilder issueBuilder = new IssueBuilder()) { @@ -50,7 +50,7 @@ void shouldSkipFingerprintingIfEncodingIsWrong() throws IOException { @Test void shouldNotChangeIssuesWithFingerPrint() { try (IssueBuilder issueBuilder = new IssueBuilder()) { - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); issueBuilder.setFileName(AFFECTED_FILE_NAME); Report report = createIssues(); @@ -70,9 +70,9 @@ void shouldNotChangeIssuesWithFingerPrint() { @Test void shouldSetDefaultFingerprintIfNoFileIsGiven() { try (IssueBuilder issueBuilder = new IssueBuilder()) { - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); - Report report = new Report(); + var report = new Report(); report.add(issueBuilder.build()); generator.run(new FullTextFingerprint(), report, CHARSET_AFFECTED_FILE); @@ -84,14 +84,14 @@ void shouldSetDefaultFingerprintIfNoFileIsGiven() { @Test void shouldAssignIdenticalFingerprint() { - Report report = createTwoIssues(); - FingerprintGenerator generator = new FingerprintGenerator(); - FullTextFingerprint fingerprint = createFullTextFingerprint("fingerprint-one.txt"); + var report = createTwoIssues(); + var generator = new FingerprintGenerator(); + var fingerprint = createFullTextFingerprint("fingerprint-one.txt"); generator.run(fingerprint, report, CHARSET_AFFECTED_FILE); - Issue referenceIssue = report.get(0); - Issue currentIssue = report.get(1); + var referenceIssue = report.get(0); + var currentIssue = report.get(1); assertThat(referenceIssue).isNotEqualTo(currentIssue); assertThat(referenceIssue.getFingerprint()).isEqualTo(currentIssue.getFingerprint()); @@ -105,7 +105,7 @@ void shouldAssignIdenticalFingerprint() { @SuppressWarnings("MustBeClosedChecker") private FileSystem stubFileSystem(final String firstFile, final String secondFile) { try { - FileSystem fileSystem = mock(FileSystem.class); + var fileSystem = mock(FileSystem.class); when(fileSystem.readLinesFromFile(anyString(), any())) .thenReturn(asStream(firstFile)).thenReturn(asStream(secondFile)); return fileSystem; @@ -117,9 +117,9 @@ private FileSystem stubFileSystem(final String firstFile, final String secondFil @Test void shouldAssignDifferentFingerprint() { - Report report = createTwoIssues(); - FingerprintGenerator generator = new FingerprintGenerator(); - FullTextFingerprint fingerprint = createFullTextFingerprint("fingerprint-two.txt"); + var report = createTwoIssues(); + var generator = new FingerprintGenerator(); + var fingerprint = createFullTextFingerprint("fingerprint-two.txt"); generator.run(fingerprint, report, CHARSET_AFFECTED_FILE); @@ -135,7 +135,7 @@ void shouldAssignDifferentFingerprint() { void shouldUseFallbackFingerprintOnError(final String fileName) { var report = createReportWithOneIssueFor(fileName); - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); generator.run(new FullTextFingerprint(), report, CHARSET_AFFECTED_FILE); assertThatIssueHasDefaultFingerprint(report); @@ -148,7 +148,7 @@ void shouldUseFallbackFingerprintOnError(final String fileName) { void shouldUseFallbackFingerprintOnNonSourceFiles(final String fileName) { var report = createReportWithOneIssueFor(fileName); - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); generator.run(createFullTextFingerprint("fingerprint-two.txt"), report, CHARSET_AFFECTED_FILE); @@ -162,7 +162,7 @@ void shouldUseFallbackFingerprintOnIllegalFilenamesOnWindows(final String fileNa var report = createReportWithOneIssueFor(fileName); - FingerprintGenerator generator = new FingerprintGenerator(); + var generator = new FingerprintGenerator(); generator.run(createFullTextFingerprint("fingerprint-two.txt"), report, CHARSET_AFFECTED_FILE); @@ -170,12 +170,11 @@ void shouldUseFallbackFingerprintOnIllegalFilenamesOnWindows(final String fileNa } private Report createReportWithOneIssueFor(final String fileName) { - Report report; try (IssueBuilder issueBuilder = new IssueBuilder()) { - report = new Report(); + var report = new Report(); report.add(issueBuilder.setFileName(fileName).build()); + return report; } - return report; } private void assertThatIssueHasDefaultFingerprint(final Report report) { diff --git a/src/test/java/edu/hm/hafner/analysis/FullTextFingerprintTest.java b/src/test/java/edu/hm/hafner/analysis/FullTextFingerprintTest.java index dcc48594e..4b2b700ed 100644 --- a/src/test/java/edu/hm/hafner/analysis/FullTextFingerprintTest.java +++ b/src/test/java/edu/hm/hafner/analysis/FullTextFingerprintTest.java @@ -24,9 +24,9 @@ class FullTextFingerprintTest extends ResourceTest { */ @Test void shouldExtractCorrectLines() { - String affectedFile = new String(readAllBytes("context.txt"), StandardCharsets.UTF_8); + var affectedFile = new String(readAllBytes("context.txt"), StandardCharsets.UTF_8); - FullTextFingerprint fingerprint = new FullTextFingerprint(); + var fingerprint = new FullTextFingerprint(); assertThat(fingerprint.extractContext(-1, asIterator(affectedFile))) .as("Fingerprint for illegal line numbers should be empty").isEmpty(); @@ -44,7 +44,7 @@ void shouldExtractCorrectLines() { assertThat(fingerprint.extractContext(29, asIterator(affectedFile))).isEqualTo("67890"); assertThat(fingerprint.extractContext(30, asIterator(affectedFile))).isEqualTo("7890"); - // actually illegal but we use the remaining lines: + // actually illegal, but we use the remaining lines: assertThat(fingerprint.extractContext(31, asIterator(affectedFile))).isEqualTo("890"); assertThat(fingerprint.extractContext(32, asIterator(affectedFile))).isEqualTo("90"); assertThat(fingerprint.extractContext(33, asIterator(affectedFile))).isEqualTo("0"); @@ -59,11 +59,11 @@ void shouldExtractCorrectLines() { */ @Test void shouldAssignIdenticalFingerprints() { - String affectedFile = new String(readAllBytes("context.txt"), StandardCharsets.UTF_8); + var affectedFile = new String(readAllBytes("context.txt"), StandardCharsets.UTF_8); - FullTextFingerprint code = new FullTextFingerprint(); + var code = new FullTextFingerprint(); - String fingerprint = code.createFingerprint(10, getTextLinesAsStream(affectedFile), StandardCharsets.UTF_8); + var fingerprint = code.createFingerprint(10, getTextLinesAsStream(affectedFile), StandardCharsets.UTF_8); assertThat(fingerprint).isEqualTo("C10CFE4EC75F0C7F54980D432624D1C9"); for (int line = 0; line < 34; line++) { @@ -80,7 +80,7 @@ void shouldAssignIdenticalFingerprints() { @Test void shouldThrowNoSuchFileExceptionIfFileDoesNotExist() { - FullTextFingerprint fingerprint = new FullTextFingerprint(); + var fingerprint = new FullTextFingerprint(); assertThatExceptionOfType(NoSuchFileException.class) .isThrownBy(() -> fingerprint.compute("/does/not/exist", 1, StandardCharsets.UTF_8)); diff --git a/src/test/java/edu/hm/hafner/analysis/GradleModuleDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/GradleModuleDetectorTest.java index b5e059da3..acc0f16c3 100644 --- a/src/test/java/edu/hm/hafner/analysis/GradleModuleDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/GradleModuleDetectorTest.java @@ -37,7 +37,7 @@ void shouldIdentifyModuleByReadingGradlePath() { when(stub.find(any(), anyString())).thenReturn( new String[] {PATH_PREFIX_GRADLE + GradleModuleDetector.BUILD_GRADLE})); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_GRADLE + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); @@ -54,7 +54,7 @@ void shouldIdentifyModuleByFindingClosestGradlePath() { PATH_PREFIX_GRADLE + "a-module/" + GradleModuleDetector.BUILD_GRADLE, })); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName( @@ -75,7 +75,7 @@ void shouldIdentifyModuleByReadingGradleKtsPath() { when(stub.find(any(), anyString())).thenReturn( new String[] {PATH_PREFIX_GRADLE + GradleModuleDetector.BUILD_GRADLE_KTS})); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_GRADLE + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); @@ -94,7 +94,7 @@ void shouldIdentifyModuleByReadingGradleSettings() { when(stub.open(anyString())).thenAnswer(filename -> read("settings-1.gradle")); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName( @@ -118,7 +118,7 @@ void shouldIdentifyModuleByReadingGradleSettingsKts() { when(stub.open(anyString())).thenAnswer(filename -> read("settings-1.gradle")); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) @@ -139,7 +139,7 @@ void shouldEnsureThatGradleSettingsHasPrecedenceOverRootBuild() { when(stub.open(anyString())).thenAnswer(filename -> read("settings-1.gradle")); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName( @@ -165,7 +165,7 @@ void shouldEnsureThatGradleSettingsCanParseFormat1() { String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT); } @@ -181,7 +181,7 @@ void shouldEnsureThatGradleSettingsCanParseFormat2() { String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo("root-project-2"); } @@ -197,7 +197,7 @@ void shouldEnsureThatGradleSettingsCanParseFormat3() { String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo("root-project-3"); } @@ -213,7 +213,7 @@ void shouldEnsureThatGradleSettingsCanParseFormat4() { String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo("root-project-4"); } @@ -230,7 +230,7 @@ void shouldIgnoreGradleSettingsWithoutProjectName() { String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); } @@ -242,7 +242,7 @@ void shouldIgnoreGradleFileWithNoParentPath() { GradleModuleDetector.BUILD_GRADLE, })); - ModuleDetector detector = new ModuleDetector(ROOT_ABSOLUTE, factory); + var detector = new ModuleDetector(ROOT_ABSOLUTE, factory); assertThat(detector.guessModuleName("build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } diff --git a/src/test/java/edu/hm/hafner/analysis/IssueBuilderTest.java b/src/test/java/edu/hm/hafner/analysis/IssueBuilderTest.java index 15fb3908b..190c506ac 100644 --- a/src/test/java/edu/hm/hafner/analysis/IssueBuilderTest.java +++ b/src/test/java/edu/hm/hafner/analysis/IssueBuilderTest.java @@ -239,12 +239,12 @@ void shouldCreateNewInstanceOnEveryCall() { void shouldCollectLineRanges() { try (IssueBuilder builder = new IssueBuilder()) { builder.setLineStart(1).setLineEnd(2); - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); lineRanges.add(new LineRange(3, 4)); lineRanges.add(new LineRange(5, 6)); builder.setLineRanges(lineRanges); - Issue issue = builder.build(); + var issue = builder.build(); assertThat(issue).hasLineStart(1).hasLineEnd(2); assertThat(issue).hasOnlyLineRanges(new LineRange(3, 4), new LineRange(5, 6)); @@ -258,11 +258,11 @@ void shouldCollectLineRanges() { @Test void shouldMoveLineRangeToAttributes() { try (IssueBuilder builder = new IssueBuilder()) { - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); lineRanges.add(new LineRange(1, 2)); builder.setLineRanges(lineRanges); - Issue issue = builder.build(); + var issue = builder.build(); assertThat(issue).hasLineStart(1).hasLineEnd(2); assertThat(issue).hasNoLineRanges(); } @@ -272,11 +272,11 @@ void shouldMoveLineRangeToAttributes() { void shouldMoveLineRangeToAttributesEvenIfLineEndIsSet() { try (IssueBuilder builder = new IssueBuilder()) { builder.setLineEnd(2); - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); lineRanges.add(new LineRange(1, 2)); builder.setLineRanges(lineRanges); - Issue issue = builder.build(); + var issue = builder.build(); assertThat(issue).hasLineStart(1).hasLineEnd(2); assertThat(issue).hasNoLineRanges(); } @@ -286,11 +286,11 @@ void shouldMoveLineRangeToAttributesEvenIfLineEndIsSet() { void shouldCleanupLineRanges() { try (IssueBuilder builder = new IssueBuilder()) { builder.setLineStart(1).setLineEnd(2); - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); lineRanges.add(new LineRange(1, 2)); builder.setLineRanges(lineRanges); - Issue issue = builder.build(); + var issue = builder.build(); assertThat(issue).hasLineStart(1).hasLineEnd(2); assertThat(issue).hasNoLineRanges(); } @@ -300,11 +300,11 @@ void shouldCleanupLineRanges() { void shouldNotCleanupDifferentLineRanges() { try (IssueBuilder builder = new IssueBuilder()) { builder.setLineStart(1).setLineEnd(2); - LineRangeList lineRanges = new LineRangeList(); + var lineRanges = new LineRangeList(); lineRanges.add(new LineRange(1, 3)); builder.setLineRanges(lineRanges); - Issue issue = builder.build(); + var issue = builder.build(); assertThat(issue).hasLineStart(1).hasLineEnd(2); assertThat(issue).hasOnlyLineRanges(new LineRange(1, 3)); } @@ -327,7 +327,7 @@ void shouldUseProvidedId() { @Test void testFileNameBackslashConversion() { try (IssueBuilder builder = new IssueBuilder()) { - Issue issue = builder.setFileName(FILE_NAME_WITH_BACKSLASHES).build(); + var issue = builder.setFileName(FILE_NAME_WITH_BACKSLASHES).build(); assertThat(issue).hasFileName(FILE_NAME); } @@ -336,8 +336,8 @@ void testFileNameBackslashConversion() { @Test void shouldCacheFileName() { try (IssueBuilder builder = new IssueBuilder()) { - Issue issue = builder.setFileName("fileName").build(); - Issue anotherIssue = builder.setFileName("fileName").build(); + var issue = builder.setFileName("fileName").build(); + var anotherIssue = builder.setFileName("fileName").build(); assertThat(issue.getFileNameTreeString()).isSameAs(anotherIssue.getFileNameTreeString()); } @@ -346,8 +346,8 @@ void shouldCacheFileName() { @Test void shouldCachePackageName() { try (IssueBuilder builder = new IssueBuilder()) { - Issue issue = builder.setPackageName("packageName").build(); - Issue anotherIssue = builder.setFileName("packageName").build(); + var issue = builder.setPackageName("packageName").build(); + var anotherIssue = builder.setFileName("packageName").build(); assertThat(issue.getPackageNameTreeString()).isSameAs(anotherIssue.getPackageNameTreeString()); } diff --git a/src/test/java/edu/hm/hafner/analysis/IssueDifferenceTest.java b/src/test/java/edu/hm/hafner/analysis/IssueDifferenceTest.java index 87e121289..a28153ef7 100644 --- a/src/test/java/edu/hm/hafner/analysis/IssueDifferenceTest.java +++ b/src/test/java/edu/hm/hafner/analysis/IssueDifferenceTest.java @@ -23,28 +23,28 @@ class IssueDifferenceTest extends ResourceTest { @Test void shouldCreateIssueDifferenceBasedOnPropertiesAndThenOnFingerprint() { - Report referenceIssues = new Report().addAll( + var referenceIssues = new Report().addAll( createIssue("OUTSTANDING 1", "OUT 1"), createIssue("OUTSTANDING 2", "OUT 2"), createIssue("OUTSTANDING 3", "OUT 3"), createIssue("TO FIX 1", "FIX 1"), createIssue("TO FIX 2", "FIX 2")); - Report currentIssues = new Report().addAll( + var currentIssues = new Report().addAll( createIssue("UPD OUTSTANDING 1", "OUT 1"), createIssue("OUTSTANDING 2", "UPD OUT 2"), createIssue("OUTSTANDING 3", "OUT 3"), createIssue("NEW 1", "NEW 1")); - IssueDifference issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); + var issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); - Report outstanding = issueDifference.getOutstandingIssues(); + var outstanding = issueDifference.getOutstandingIssues(); assertThat(outstanding).hasSize(3); assertThat(outstanding.get(0)).hasMessage("OUTSTANDING 2").hasReference(REFERENCE_BUILD); assertThat(outstanding.get(1)).hasMessage("OUTSTANDING 3").hasReference(REFERENCE_BUILD); assertThat(outstanding.get(2)).hasMessage("UPD OUTSTANDING 1").hasReference(REFERENCE_BUILD); - Report fixed = issueDifference.getFixedIssues(); + var fixed = issueDifference.getFixedIssues(); assertThat(fixed).hasSize(2); assertThat(fixed.get(0)).hasMessage("TO FIX 1").hasReference(REFERENCE_BUILD); assertThat(fixed.get(1)).hasMessage("TO FIX 2").hasReference(REFERENCE_BUILD); @@ -66,14 +66,14 @@ void shouldCreateOutstandingIssueDifference() { private void shouldFindOutstandingFromEqualsOrFingerprint( final String currentMessage, final String currentFingerprint) { - Report referenceIssues = new Report().add(createIssue("OLD", "OLD")); - Report currentIssues = new Report().add(createIssue(currentMessage, currentFingerprint)); + var referenceIssues = new Report().add(createIssue("OLD", "OLD")); + var currentIssues = new Report().add(createIssue(currentMessage, currentFingerprint)); - IssueDifference issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); + var issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); assertThat(issueDifference.getFixedIssues()).isEmpty(); assertThat(issueDifference.getNewIssues()).isEmpty(); - Report outstanding = issueDifference.getOutstandingIssues(); + var outstanding = issueDifference.getOutstandingIssues(); assertThat(outstanding).hasSize(1); assertThat(outstanding.get(0)) @@ -84,11 +84,11 @@ private void shouldFindOutstandingFromEqualsOrFingerprint( @Test void shouldCreateIssueDifferenceWithEmptyCurrent() { - Report referenceIssues = new Report().addAll(createIssue("OLD 1", "FA"), + var referenceIssues = new Report().addAll(createIssue("OLD 1", "FA"), createIssue("OLD 2", "FB")); - Report currentIssues = new Report(); + var currentIssues = new Report(); - IssueDifference issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); + var issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); assertThat(issueDifference.getNewIssues()).isEmpty(); assertThat(issueDifference.getOutstandingIssues()).isEmpty(); @@ -102,11 +102,11 @@ void shouldCreateIssueDifferenceWithEmptyCurrent() { @Test void shouldCreateIssueDifferenceWithEmptyReference() { - Report referenceIssues = new Report(); - Report currentIssues = new Report().addAll(createIssue("NEW 1", "FA"), + var referenceIssues = new Report(); + var currentIssues = new Report().addAll(createIssue("NEW 1", "FA"), createIssue("NEW 2", "FB")); - IssueDifference issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); + var issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); assertThat(issueDifference.getFixedIssues()).isEmpty(); assertThat(issueDifference.getOutstandingIssues()).isEmpty(); @@ -126,7 +126,7 @@ void shouldAlsoUseFingerprintIfIssuesAreEqual() { createIssue("NEW 1", "FP"), createIssue("OLD 1", "FP")); - IssueDifference issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); + var issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); assertThat(issueDifference.getFixedIssues()).isEmpty(); @@ -148,7 +148,7 @@ void shouldRemoveForSecondPass() { createIssue("NEW 1", "FP1"), createIssue("NEW 3", "FP2")); - IssueDifference issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); + var issueDifference = new IssueDifference(currentIssues, CURRENT_BUILD, referenceIssues); assertThat(issueDifference.getFixedIssues()).hasSize(1); assertThat(issueDifference.getNewIssues()).hasSize(1); @@ -184,20 +184,20 @@ private Issue createIssue(final String message, final String fingerprint, final @Test @org.junitpioneer.jupiter.Issue("JENKINS-65482") void shouldHandleAggregatedResults() { - Report firstAxis = readSpotBugsWarnings(); + var firstAxis = readSpotBugsWarnings(); assertThat(firstAxis).hasSize(2); - Report secondAxis = readSpotBugsWarnings(); + var secondAxis = readSpotBugsWarnings(); assertThat(secondAxis).hasSize(2); - Report aggregation = new Report(); + var aggregation = new Report(); aggregation.addAll(firstAxis, secondAxis); assertThat(aggregation).hasSize(2); - Report reference = new Report(); + var reference = new Report(); reference.addAll(firstAxis, secondAxis); - IssueDifference issueDifference = new IssueDifference(aggregation, CURRENT_BUILD, reference); + var issueDifference = new IssueDifference(aggregation, CURRENT_BUILD, reference); assertThat(issueDifference).hasNoFixedIssues().hasNoNewIssues(); assertThat(issueDifference.getOutstandingIssues()).hasSize(2); } diff --git a/src/test/java/edu/hm/hafner/analysis/IssueFilterTest.java b/src/test/java/edu/hm/hafner/analysis/IssueFilterTest.java index 81b31eae9..4ae9b00cd 100644 --- a/src/test/java/edu/hm/hafner/analysis/IssueFilterTest.java +++ b/src/test/java/edu/hm/hafner/analysis/IssueFilterTest.java @@ -13,6 +13,7 @@ * * @author Raphael Furch */ +@SuppressWarnings("resource") class IssueFilterTest { private static final Issue ISSUE1 = new IssueBuilder() .setFileName("FileName1") @@ -47,21 +48,21 @@ class IssueFilterTest { */ @Test void shouldHandleApostrophe() { - Predicate predicate = new IssueFilterBuilder().setExcludeMessageFilter( + var predicate = new IssueFilterBuilder().setExcludeMessageFilter( "'tools.jar' was not found, kapt may work unreliably").build(); - Report report = new Report(); + var report = new Report(); report.add(new IssueBuilder().setMessage("'tools.jar' was not found, kapt may work unreliably").build()); - Report filtered = report.filter(predicate); + var filtered = report.filter(predicate); assertThat(filtered).hasSize(0); } @Test void shouldUseFindRatherThanMatch() { - Predicate predicate = new IssueFilterBuilder().setIncludeMessageFilter("something").build(); + var predicate = new IssueFilterBuilder().setIncludeMessageFilter("something").build(); - Report report = new Report(); + var report = new Report(); report.add(new IssueBuilder().setLineStart(1).setMessage("something").build()); report.add(new IssueBuilder().setLineStart(2).setMessage(" something").build()); report.add(new IssueBuilder().setLineStart(3).setMessage("something ").build()); @@ -70,21 +71,20 @@ void shouldUseFindRatherThanMatch() { report.add(new IssueBuilder().setLineStart(6).setMessage("Before something").build()); report.add(new IssueBuilder().setLineStart(7).setMessage("something After").build()); - Report filtered = report.filter(predicate); + var filtered = report.filter(predicate); assertThat(filtered).hasSize(7); } @Test void shouldMatchMultiLinesInMessage() { - Predicate predicate - = new IssueFilterBuilder().setExcludeMessageFilter(".*something.*").build(); + var predicate = new IssueFilterBuilder().setExcludeMessageFilter(".*something.*").build(); - Report report = new Report(); + var report = new Report(); report.add(new IssueBuilder().setMessage("something").build()); report.add(new IssueBuilder().setMessage("something\nelse").build()); report.add(new IssueBuilder().setMessage("else\nsomething").build()); - Report filtered = report.filter(predicate); + var filtered = report.filter(predicate); assertThat(filtered).hasSize(0); } @@ -95,15 +95,14 @@ void shouldMatchMultiLinesInMessage() { */ @Test void shouldMatchMultiLinesInDescription() { - Predicate predicate - = new IssueFilterBuilder().setExcludeMessageFilter(".*something.*").build(); + var predicate = new IssueFilterBuilder().setExcludeMessageFilter(".*something.*").build(); - Report report = new Report(); + var report = new Report(); report.add(new IssueBuilder().setDescription("something").build()); report.add(new IssueBuilder().setDescription("something\nelse").build()); report.add(new IssueBuilder().setDescription("else\nsomething").build()); - Report filtered = report.filter(predicate); + var filtered = report.filter(predicate); assertThat(filtered).hasSize(0); } @@ -114,28 +113,27 @@ void shouldMatchMultiLinesInDescription() { */ @Test void shouldMatchMessageOrDescriptionInIncludeFilter() { - Predicate predicate - = new IssueFilterBuilder().setIncludeMessageFilter(".*something.*").build(); + var predicate = new IssueFilterBuilder().setIncludeMessageFilter(".*something.*").build(); - Report report = new Report(); + var report = new Report(); report.add(new IssueBuilder().setDescription("something").setMessage("else").build()); report.add(new IssueBuilder().setDescription("else").setMessage("something").build()); report.add(new IssueBuilder().setDescription("else").setMessage("else").build()); report.add(new IssueBuilder().setDescription("something").setMessage("something").build()); - Report filtered = report.filter(predicate); + var filtered = report.filter(predicate); assertThat(filtered).hasSize(3); } @Test void shouldNothingChangeWhenNoFilterIsAdded() { - Predicate filter = new IssueFilterBuilder().build(); + var filter = new IssueFilterBuilder().build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1, ISSUE2, ISSUE3); } @Test void shouldPassAllWhenUselessFilterIsAdded() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeFileNameFilter("[a-zA-Z1]*") .setIncludeFileNameFilter("[a-zA-Z2]*") .setIncludeFileNameFilter("[a-zA-Z3]*") @@ -145,7 +143,7 @@ void shouldPassAllWhenUselessFilterIsAdded() { @Test void shouldPassAllWhenUselessFilterIsAddedAsList() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeFileNameFilter("[a-zA-Z1]*", "[a-zA-Z2]*", "[a-zA-Z3]*") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1, ISSUE2, ISSUE3); @@ -153,7 +151,7 @@ void shouldPassAllWhenUselessFilterIsAddedAsList() { @Test void shouldPassNoWhenMasterFilterIsAdded() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeFileNameFilter("[a-zA-Z_1-3]*") .build(); applyFilterAndCheckResult(filter, getIssues()); @@ -161,7 +159,7 @@ void shouldPassNoWhenMasterFilterIsAdded() { @Test void shouldPassNoWhenMasterFilterIsAddedAsList() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeFileNameFilter("[a-zA-Z1]*", "[a-zA-Z2]*", "[a-zA-Z3]*") .build(); applyFilterAndCheckResult(filter, getIssues()); @@ -169,7 +167,7 @@ void shouldPassNoWhenMasterFilterIsAddedAsList() { @Test void shouldFindIssue1ByAFileNameIncludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeFileNameFilter("FileName1") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1); @@ -177,7 +175,7 @@ void shouldFindIssue1ByAFileNameIncludeMatch() { @Test void shouldFindIssue1ByAFileNameExcludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeFileNameFilter("FileName1") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE2, ISSUE3); @@ -185,7 +183,7 @@ void shouldFindIssue1ByAFileNameExcludeMatch() { @Test void shouldFindIssue2ByAPackageNameIncludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludePackageNameFilter("PackageName2") .build(); @@ -194,7 +192,7 @@ void shouldFindIssue2ByAPackageNameIncludeMatch() { @Test void shouldFindIssue2ByAPackageNameExcludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludePackageNameFilter("PackageName2") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1, ISSUE3); @@ -202,7 +200,7 @@ void shouldFindIssue2ByAPackageNameExcludeMatch() { @Test void shouldFindIssue3ByAModuleNameIncludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeModuleNameFilter("ModuleName3") .build(); @@ -211,7 +209,7 @@ void shouldFindIssue3ByAModuleNameIncludeMatch() { @Test void shouldFindIssue3ByAModuleNameExcludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeModuleNameFilter("ModuleName3") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1, ISSUE2); @@ -219,7 +217,7 @@ void shouldFindIssue3ByAModuleNameExcludeMatch() { @Test void shouldFindIssue1ByACategoryIncludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeCategoryFilter("CategoryName1") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1); @@ -227,7 +225,7 @@ void shouldFindIssue1ByACategoryIncludeMatch() { @Test void shouldFindIssue1ByACategoryExcludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeCategoryFilter("CategoryName1") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE2, ISSUE3); @@ -235,7 +233,7 @@ void shouldFindIssue1ByACategoryExcludeMatch() { @Test void shouldFindIssue2ByATypeIncludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeTypeFilter("Type2") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE2); @@ -243,7 +241,7 @@ void shouldFindIssue2ByATypeIncludeMatch() { @Test void shouldFindIssue2ByACategoryExcludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeTypeFilter("Type2") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1, ISSUE3); @@ -251,7 +249,7 @@ void shouldFindIssue2ByACategoryExcludeMatch() { @Test void shouldFindIntersectionFromIncludeAndExcludeBySameProperty() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeFileNameFilter("FileName1") .setIncludeFileNameFilter("FileName2") .setExcludeFileNameFilter("FileName2") @@ -261,7 +259,7 @@ void shouldFindIntersectionFromIncludeAndExcludeBySameProperty() { @Test void shouldFindIntersectionFromIncludeAndExcludeByOtherProperty() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeFileNameFilter("FileName1") .setIncludeFileNameFilter("FileName2") .setExcludeTypeFilter("Type2") @@ -271,7 +269,7 @@ void shouldFindIntersectionFromIncludeAndExcludeByOtherProperty() { @Test void shouldFindNoIntersectionFromEmptyIncludeAndExclude() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeFileNameFilter("FileNameNotExisting") .setExcludeTypeFilter("Type2") .build(); @@ -280,7 +278,7 @@ void shouldFindNoIntersectionFromEmptyIncludeAndExclude() { @Test void shouldFindIssue1ByAMessageIncludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setIncludeMessageFilter("Message1") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1); @@ -288,7 +286,7 @@ void shouldFindIssue1ByAMessageIncludeMatch() { @Test void shouldRemoveIssue2ByAMessageExcludeMatch() { - Predicate filter = new IssueFilterBuilder() + var filter = new IssueFilterBuilder() .setExcludeMessageFilter("Message2") .build(); applyFilterAndCheckResult(filter, getIssues(), ISSUE1, ISSUE3); diff --git a/src/test/java/edu/hm/hafner/analysis/IssueTest.java b/src/test/java/edu/hm/hafner/analysis/IssueTest.java index 6933143cc..df5fdb3a5 100644 --- a/src/test/java/edu/hm/hafner/analysis/IssueTest.java +++ b/src/test/java/edu/hm/hafner/analysis/IssueTest.java @@ -60,7 +60,7 @@ class IssueTest extends SerializableTest { @Test void shouldSplitFileNameElements() { - Issue issue = new Issue(PATH_NAME, FILE_NAME_TS, 2, 1, 2, 1, LINE_RANGES, CATEGORY, + var issue = new Issue(PATH_NAME, FILE_NAME_TS, 2, 1, 2, 1, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, SEVERITY, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, ADDITIONAL_PROPERTIES, UUID.randomUUID()); @@ -73,7 +73,7 @@ void shouldSplitFileNameElements() { .hasBaseName(BASE_NAME); } - TreeString newName = TreeString.valueOf("new.txt"); + var newName = TreeString.valueOf("new.txt"); issue.setFileName("/new", newName); try (SoftAssertions softly = new SoftAssertions()) { softly.assertThat(issue) @@ -83,13 +83,13 @@ void shouldSplitFileNameElements() { .hasBaseName("new.txt"); } - Issue other = new Issue(PATH_NAME, newName, 2, 1, 2, 1, LINE_RANGES, CATEGORY, + var other = new Issue(PATH_NAME, newName, 2, 1, 2, 1, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, SEVERITY, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, ADDITIONAL_PROPERTIES, UUID.randomUUID()); assertThat(issue).as("Equals should not consider pathName in computation").isEqualTo(other); - Issue emptyPath = new Issue("", FILE_NAME_TS, 2, 1, 2, 1, LINE_RANGES, CATEGORY, + var emptyPath = new Issue("", FILE_NAME_TS, 2, 1, 2, 1, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, SEVERITY, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, ADDITIONAL_PROPERTIES, UUID.randomUUID()); @@ -105,7 +105,7 @@ void shouldSplitFileNameElements() { @Test void shouldConvertWindowsNames() { - Issue issue = new Issue("C:\\Windows", FILE_NAME_TS, 2, 1, 2, 1, LINE_RANGES, CATEGORY, + var issue = new Issue("C:\\Windows", FILE_NAME_TS, 2, 1, 2, 1, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, SEVERITY, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, ADDITIONAL_PROPERTIES, UUID.randomUUID()); @@ -135,7 +135,7 @@ void shouldExpandPath() { @Test void shouldEnsureThatEndIsGreaterOrEqualStart() { - Issue issue = new Issue(PATH_NAME, FILE_NAME_TS, 3, 2, 2, 1, LINE_RANGES, CATEGORY, + var issue = new Issue(PATH_NAME, FILE_NAME_TS, 3, 2, 2, 1, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, SEVERITY, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, ADDITIONAL_PROPERTIES, UUID.randomUUID()); @@ -158,7 +158,7 @@ void shouldEnsureThatEndIsGreaterOrEqualStart() { */ @Test void shouldSetAllPropertiesInConstructor() { - Issue issue = createFilledIssue(); + var issue = createFilledIssue(); try (SoftAssertions softly = new SoftAssertions()) { softly.assertThat(issue.getId()).isNotNull(); @@ -197,7 +197,7 @@ void shouldSetAllPropertiesInConstructor() { @Test void shouldChangeMutableProperties() { - Issue issue = createFilledIssue(); + var issue = createFilledIssue(); String origin = "new-origin"; issue.setOrigin(origin); @@ -245,7 +245,7 @@ void shouldChangeMutableProperties() { @Test @SuppressWarnings("NullAway") void testDefaultIssueNullStringsNegativeIntegers() { - Issue issue = new Issue(null, UNDEFINED_TS, 0, 0, 0, 0, LINE_RANGES, null, null, + var issue = new Issue(null, UNDEFINED_TS, 0, 0, 0, 0, LINE_RANGES, null, null, UNDEFINED_TS, null, SEVERITY, EMPTY_TS, EMPTY, null, ORIGIN_NAME, null, null, null, UUID.randomUUID()); @@ -255,7 +255,7 @@ void testDefaultIssueNullStringsNegativeIntegers() { @Test void testDefaultIssueEmptyStringsNegativeIntegers() { - Issue issue = new Issue(EMPTY, UNDEFINED_TS, -1, -1, -1, -1, LINE_RANGES, EMPTY, EMPTY, + var issue = new Issue(EMPTY, UNDEFINED_TS, -1, -1, -1, -1, LINE_RANGES, EMPTY, EMPTY, UNDEFINED_TS, EMPTY, SEVERITY, EMPTY_TS, EMPTY, EMPTY, ORIGIN_NAME, EMPTY, EMPTY, EMPTY, UUID.randomUUID()); @@ -286,7 +286,7 @@ private void assertIsDefaultIssue(final Issue issue) { @Test void testZeroLineColumnEndsDefaultToLineColumnStarts() { - Issue issue = new Issue(PATH_NAME, FILE_NAME_TS, LINE_START, 0, COLUMN_START, 0, LINE_RANGES, CATEGORY, TYPE, + var issue = new Issue(PATH_NAME, FILE_NAME_TS, LINE_START, 0, COLUMN_START, 0, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, SEVERITY, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, ADDITIONAL_PROPERTIES, UUID.randomUUID()); @@ -302,7 +302,7 @@ void testZeroLineColumnEndsDefaultToLineColumnStarts() { @Test void testNullPriorityDefaultsToNormal() { - Issue issue = new Issue(PATH_NAME, FILE_NAME_TS, LINE_START, LINE_END, COLUMN_START, COLUMN_END, LINE_RANGES, + var issue = new Issue(PATH_NAME, FILE_NAME_TS, LINE_START, LINE_END, COLUMN_START, COLUMN_END, LINE_RANGES, CATEGORY, TYPE, PACKAGE_NAME_TS, MODULE_NAME, null, MESSAGE_TS, DESCRIPTION, ORIGIN, ORIGIN_NAME, REFERENCE, FINGERPRINT, @@ -334,7 +334,7 @@ protected Issue createFilledIssue() { @Test void shouldObeyEqualsContract() { - LineRangeList filled = new LineRangeList(15); + var filled = new LineRangeList(15); filled.add(new LineRange(15)); EqualsVerifier.simple() diff --git a/src/test/java/edu/hm/hafner/analysis/JavaPackageDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/JavaPackageDetectorTest.java index b7a795707..99d73edbb 100644 --- a/src/test/java/edu/hm/hafner/analysis/JavaPackageDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/JavaPackageDetectorTest.java @@ -36,14 +36,14 @@ void shouldExtractPackageNameFromJavaSource(final String fileName, final String @ParameterizedTest(name = "{index} => Invalid package name: {0}") @ValueSource(strings = {"package EDU.hm.hafner.analysis;", "package 0123.hm.hafner.analysis;"}) void shouldSkipPackagesThatDoNotStartWithLowerCase(final String name) throws IOException { - JavaPackageDetector detector = new JavaPackageDetector(); + var detector = new JavaPackageDetector(); assertThat(detector.detectPackageName(IOUtils.toInputStream(name, UTF_8), UTF_8)).isEqualTo("-"); } @Test void shouldAcceptCorrectFileSuffix() { - JavaPackageDetector packageDetector = new JavaPackageDetector(); + var packageDetector = new JavaPackageDetector(); assertThat(packageDetector.accepts("Action.java")).as("Does not accept a Java file.") .isTrue(); assertThat(packageDetector.accepts("ActionBinding.cs")).as("Accepts a non-Java file.") diff --git a/src/test/java/edu/hm/hafner/analysis/KotlinPackageDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/KotlinPackageDetectorTest.java index bfbfc33d0..115d31cae 100644 --- a/src/test/java/edu/hm/hafner/analysis/KotlinPackageDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/KotlinPackageDetectorTest.java @@ -36,14 +36,14 @@ void shouldExtractPackageNameFromKotlinSource(final String fileName, final Strin @ParameterizedTest(name = "{index} => Invalid package name: {0}") @ValueSource(strings = {"package EDU.hm.hafner.analysis;", "package 0123.hm.hafner.analysis;"}) void shouldSkipPackagesThatDoNotStartWithLowerCase(final String name) throws IOException { - KotlinPackageDetector detector = new KotlinPackageDetector(); + var detector = new KotlinPackageDetector(); assertThat(detector.detectPackageName(IOUtils.toInputStream(name, UTF_8), UTF_8)).isEqualTo("-"); } @Test void shouldAcceptCorrectFileSuffix() { - KotlinPackageDetector packageDetector = new KotlinPackageDetector(); + var packageDetector = new KotlinPackageDetector(); assertThat(packageDetector.accepts("Action.kt")).as("Does not accept a Kotlin file.") .isTrue(); assertThat(packageDetector.accepts("ActionBinding.cs")).as("Accepts a non-Java file.") diff --git a/src/test/java/edu/hm/hafner/analysis/MavenModuleDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/MavenModuleDetectorTest.java index 11c3b57b6..676dab477 100644 --- a/src/test/java/edu/hm/hafner/analysis/MavenModuleDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/MavenModuleDetectorTest.java @@ -36,7 +36,7 @@ void shouldIdentifyModuleByReadingMavenPom() { when(stub.open(anyString())).thenAnswer(fileName -> read(MavenModuleDetector.MAVEN_POM)); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_MAVEN + "something.txt")).isEqualTo( EXPECTED_MAVEN_MODULE); @@ -52,7 +52,7 @@ void shouldIdentifyModuleByReadingMavenPomWithoutName() { when(stub.open(anyString())).thenAnswer(filename -> read("no-name-pom.xml")); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); String artifactId = "com.avaloq.adt.core"; assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_MAVEN + "something.txt")) diff --git a/src/test/java/edu/hm/hafner/analysis/ModuleDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/ModuleDetectorTest.java index f64b46317..a639d4db2 100644 --- a/src/test/java/edu/hm/hafner/analysis/ModuleDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/ModuleDetectorTest.java @@ -48,7 +48,7 @@ void shouldIdentifyModuleIfThereAreMoreEntries() { when(stub.open(PREFIX + maven)).thenAnswer(filename -> read(MavenModuleDetector.MAVEN_POM)); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_ANT + "something.txt")) .isEqualTo(EXPECTED_ANT_MODULE); @@ -89,7 +89,7 @@ private void verifyOrder(final String prefix, final String ant, final String mav when(stub.open(maven)).thenAnswer(filename -> read(MavenModuleDetector.MAVEN_POM)); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(prefix + "something.txt")).isEqualTo(EXPECTED_MAVEN_MODULE); } @@ -105,7 +105,7 @@ private void verifyOrder(final String prefix, final String ant, final String mav when(stub.open(prefix + "/" + OsgiModuleDetector.BUNDLE_PROPERTIES)).thenAnswer(filename -> createEmptyStream()); }); - ModuleDetector detector = new ModuleDetector(ROOT, fileSystem); + var detector = new ModuleDetector(ROOT, fileSystem); assertThat(detector.guessModuleName(prefix + "something.txt")).isEqualTo(EXPECTED_OSGI_MODULE); } diff --git a/src/test/java/edu/hm/hafner/analysis/ModuleResolverTest.java b/src/test/java/edu/hm/hafner/analysis/ModuleResolverTest.java index 2c82cf90b..668704f86 100644 --- a/src/test/java/edu/hm/hafner/analysis/ModuleResolverTest.java +++ b/src/test/java/edu/hm/hafner/analysis/ModuleResolverTest.java @@ -17,7 +17,7 @@ class ModuleResolverTest { @SuppressFBWarnings("DMI") void shouldAssignModuleName() { try (IssueBuilder builder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); String fileName = "/file/with/warnings.txt"; builder.setFileName(fileName); Issue noModule = builder.build(); @@ -27,10 +27,10 @@ void shouldAssignModuleName() { Issue withModule = builder.build(); report.add(withModule); - ModuleDetector detector = mock(ModuleDetector.class); + var detector = mock(ModuleDetector.class); when(detector.guessModuleName(fileName)).thenReturn("module1"); - ModuleResolver resolver = new ModuleResolver(); + var resolver = new ModuleResolver(); resolver.run(report, detector); assertThat(report.get(0)).hasModuleName("module1"); diff --git a/src/test/java/edu/hm/hafner/analysis/OsgiModuleDetectorTest.java b/src/test/java/edu/hm/hafner/analysis/OsgiModuleDetectorTest.java index f9e8da95b..6a18235c4 100644 --- a/src/test/java/edu/hm/hafner/analysis/OsgiModuleDetectorTest.java +++ b/src/test/java/edu/hm/hafner/analysis/OsgiModuleDetectorTest.java @@ -38,7 +38,7 @@ void shouldIdentifyModuleByReadingOsgiBundle() { when(stub.open(anyString())).thenReturn(read(MANIFEST)); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_OSGI + "something.txt")) .isEqualTo(EXPECTED_OSGI_MODULE); @@ -55,7 +55,7 @@ void shouldIdentifyModuleByReadingOsgiBundleWithVendorInL10nProperties() { when(stub.open(anyString())).thenReturn(read(MANIFEST), read("l10n.properties")); }); - ModuleDetector detector = new ModuleDetector(ROOT, factory); + var detector = new ModuleDetector(ROOT, factory); String expectedName = "de.faktorlogik.prototyp (My Vendor)"; assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_OSGI + "something.txt")) @@ -74,7 +74,7 @@ void shouldIdentifyModuleByReadingOsgiBundleWithManifestName() { when(stub.open(anyString())).thenReturn(read(MANIFEST_NAME), read("l10n.properties")); }); - ModuleDetector detector = new ModuleDetector(ROOT, fileSystem); + var detector = new ModuleDetector(ROOT, fileSystem); String expectedName = "My Bundle"; assertThat(detector.guessModuleName(PREFIX + PATH_PREFIX_OSGI + "something.txt")) diff --git a/src/test/java/edu/hm/hafner/analysis/PackageNameResolverBenchmark.java b/src/test/java/edu/hm/hafner/analysis/PackageNameResolverBenchmark.java index aecf4bdec..0aca7a051 100644 --- a/src/test/java/edu/hm/hafner/analysis/PackageNameResolverBenchmark.java +++ b/src/test/java/edu/hm/hafner/analysis/PackageNameResolverBenchmark.java @@ -36,7 +36,7 @@ public class PackageNameResolverBenchmark extends AbstractBenchmark { @BenchmarkMode(Mode.Throughput) @Fork(value = 5, warmups = 5) public void benchmark1000IssuesTest(final BenchmarkState state) throws IOException { - PackageNameResolver resolver = new PackageNameResolver(createFileSystemStub()); + var resolver = new PackageNameResolver(createFileSystemStub()); resolver.run(state.getReport(), StandardCharsets.UTF_8); } diff --git a/src/test/java/edu/hm/hafner/analysis/PackageNameResolverTest.java b/src/test/java/edu/hm/hafner/analysis/PackageNameResolverTest.java index 7d647d0d6..3366e8734 100644 --- a/src/test/java/edu/hm/hafner/analysis/PackageNameResolverTest.java +++ b/src/test/java/edu/hm/hafner/analysis/PackageNameResolverTest.java @@ -28,7 +28,7 @@ class PackageNameResolverTest { void shouldDoNothingForEmptyIssues() { Report report = createIssues(); - PackageNameResolver resolver = new PackageNameResolver(); + var resolver = new PackageNameResolver(); resolver.run(report, StandardCharsets.UTF_8); assertThat(report).hasSize(0); @@ -39,7 +39,7 @@ void shouldSkipExistingPackage() { Report report = createIssues(); report.add(ISSUE_WITH_PACKAGE); - PackageNameResolver resolver = new PackageNameResolver(); + var resolver = new PackageNameResolver(); resolver.run(report, StandardCharsets.UTF_8); assertThat(report).hasSize(1); @@ -51,7 +51,7 @@ void shouldResolvePackage() throws IOException { Report report = createIssues(); report.add(ISSUE_WITHOUT_PACKAGE); - PackageNameResolver resolver = new PackageNameResolver(createFileSystemStub()); + var resolver = new PackageNameResolver(createFileSystemStub()); resolver.run(report, StandardCharsets.UTF_8); @@ -65,7 +65,7 @@ void shouldResolvePackageAndSkipExistingPackage() throws IOException { report.add(ISSUE_WITHOUT_PACKAGE); report.add(ISSUE_WITH_PACKAGE); - PackageNameResolver resolver = new PackageNameResolver(createFileSystemStub()); + var resolver = new PackageNameResolver(createFileSystemStub()); resolver.run(report, StandardCharsets.UTF_8); diff --git a/src/test/java/edu/hm/hafner/analysis/ReportSerializationBenchmark.java b/src/test/java/edu/hm/hafner/analysis/ReportSerializationBenchmark.java index 12d5a367e..716fdcc77 100644 --- a/src/test/java/edu/hm/hafner/analysis/ReportSerializationBenchmark.java +++ b/src/test/java/edu/hm/hafner/analysis/ReportSerializationBenchmark.java @@ -47,8 +47,7 @@ public void benchmarkingReportDeserialization(final Blackhole blackhole) { private static Report createReportWith(final int number) { try (IssueBuilder builder = new IssueBuilder()) { - Report report; - report = new Report(); + var report = new Report(); builder.setFileName(AFFECTED_FILE_NAME); builder.setLineStart(5); @@ -68,16 +67,13 @@ private static Report createReportWith(final int number) { * @return bytes */ private static byte[] toByteArray(final Report report) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - try (ObjectOutputStream stream = new ObjectOutputStream(out)) { + try (var out = new ByteArrayOutputStream(); ObjectOutputStream stream = new ObjectOutputStream(out)) { stream.writeObject(report); + return out.toByteArray(); } catch (IOException exception) { throw new IllegalStateException("Can't serialize report " + report, exception); } - - return out.toByteArray(); } /** @@ -89,10 +85,9 @@ private static byte[] toByteArray(final Report report) { * @return report */ @SuppressFBWarnings("OBJECT_DESERIALIZATION") + @SuppressWarnings("BanSerializableRead") private static Report toReport(final byte[] bytes) { - ByteArrayInputStream in = new ByteArrayInputStream(bytes); - - try (ObjectInputStream stream = new ObjectInputStream(in)) { + try (var in = new ByteArrayInputStream(bytes); ObjectInputStream stream = new ObjectInputStream(in)) { return (Report) stream.readObject(); } catch (IOException | ClassNotFoundException exception) { diff --git a/src/test/java/edu/hm/hafner/analysis/ReportTest.java b/src/test/java/edu/hm/hafner/analysis/ReportTest.java index e994a90c4..f13d96744 100644 --- a/src/test/java/edu/hm/hafner/analysis/ReportTest.java +++ b/src/test/java/edu/hm/hafner/analysis/ReportTest.java @@ -99,7 +99,7 @@ static Issue build(final Consumer configuration) { @Test void shouldFindIssuesInModifiedCode() { - Report report = new Report(); + var report = new Report(); report.addAll(allIssuesAsList()); assertThat(report).hasNoInModifiedCode(); @@ -132,7 +132,7 @@ void shouldMergeLog() { @Test void shouldVerifyExistenceOfProperties() { - Report report = new Report(); + var report = new Report(); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); @@ -167,8 +167,7 @@ void shouldVerifyExistenceOfProperties() { private void verifySeverity(final Report report) { try (IssueBuilder issueBuilder = new IssueBuilder()) { - Issue additional; - additional = issueBuilder.setSeverity(Severity.WARNING_HIGH).build(); + Issue additional = issueBuilder.setSeverity(Severity.WARNING_HIGH).build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); @@ -304,7 +303,7 @@ private void verifyOrigin(final Report report) { @Test void shouldFilterPriorities() { - Report report = new Report(); + var report = new Report(); report.addAll(allIssuesAsList()); assertThat(report.getSeverities()) @@ -328,7 +327,7 @@ void shouldFilterPriorities() { @Test @SuppressWarnings("NullAway") void shouldGroupIssuesByProperty() { - Report report = new Report(); + var report = new Report(); report.addAll(allIssuesAsList()); Map byPriority = report.groupByProperty("severity"); @@ -349,7 +348,7 @@ void shouldGroupIssuesByProperty() { */ @Test void shouldProvideNoWritingIterator() { - Report report = new Report(); + var report = new Report(); report.addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); Iterator iterator = report.iterator(); iterator.next(); @@ -361,22 +360,22 @@ void shouldProvideNoWritingIterator() { */ @Test void shouldCopyProperties() { - Report expected = new Report(ID, NAME, SOURCE_FILE); + var expected = new Report(ID, NAME, SOURCE_FILE); expected.addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); expected.logInfo("Hello"); expected.logInfo("World!"); expected.logError("Boom!"); expected.setCounter(KEY, VALUE); - Report copy = expected.copy(); + var copy = expected.copy(); assertThat(copy).isEqualTo(expected); assertThatAllIssuesHaveBeenAdded(copy); - Report report = new Report(); + var report = new Report(); report.addAll(expected); assertThatAllIssuesHaveBeenAdded(report); - Report empty = expected.copyEmptyInstance(); + var empty = expected.copyEmptyInstance(); assertThat(empty).isEmpty(); assertThat(empty.getErrorMessages()).isEqualTo(expected.getErrorMessages()); assertThat(empty.getInfoMessages()).isEqualTo(expected.getInfoMessages()); @@ -393,13 +392,13 @@ void shouldCopyProperties() { @Test void shouldSumCountersOnMerge() { - Report first = new Report(); + var first = new Report(); first.addAll(HIGH, NORMAL_1, NORMAL_2); first.addAll(HIGH, NORMAL_1, NORMAL_2); // 3 duplicates first.setCounter(KEY, 10); first.setCounter("one", 100); - Report second = new Report(); + var second = new Report(); second.addAll(LOW_2_A, LOW_2_B); second.addAll(LOW_2_A, LOW_2_B); // 2 duplicates second.setCounter(KEY, 1); @@ -416,17 +415,17 @@ void shouldSumCountersOnMerge() { /** Verifies some additional variants of the {@link Report#addAll(Report[])}. */ @Test void shouldVerifyPathInteriorCoverageOfAddAll() { - Report first = new Report().add(HIGH); + var first = new Report().add(HIGH); first.logInfo("1 info"); first.logError("1 error"); - Report second = new Report().addAll(NORMAL_1, NORMAL_2); + var second = new Report().addAll(NORMAL_1, NORMAL_2); second.logInfo("2 info"); second.logError("2 error"); - Report third = new Report().addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); + var third = new Report().addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); third.logInfo("3 info"); third.logError("3 error"); - Report report = new Report(); + var report = new Report(); report.addAll(first); assertThat((Iterable) report).containsExactly(HIGH); assertThat(report.getInfoMessages()).containsExactly("1 info"); @@ -437,13 +436,13 @@ void shouldVerifyPathInteriorCoverageOfAddAll() { assertThat(report.getInfoMessages()).containsExactly("1 info", "2 info", "3 info"); assertThat(report.getErrorMessages()).containsExactly("1 error", "2 error", "3 error"); - Report altogether = new Report(); + var altogether = new Report(); altogether.addAll(first, second, third); assertThatAllIssuesHaveBeenAdded(report); assertThat(report.getInfoMessages()).containsExactly("1 info", "2 info", "3 info"); assertThat(report.getErrorMessages()).containsExactly("1 error", "2 error", "3 error"); - Report inConstructor = new Report(first, second, third); + var inConstructor = new Report(first, second, third); assertThatAllIssuesHaveBeenAdded(inConstructor); assertThat(inConstructor.getInfoMessages()).containsExactly("1 info", "2 info", "3 info"); assertThat(inConstructor.getErrorMessages()).containsExactly("1 error", "2 error", "3 error"); @@ -451,7 +450,7 @@ void shouldVerifyPathInteriorCoverageOfAddAll() { @Test void shouldBeEmptyWhenCreated() { - Report report = new Report(); + var report = new Report(); assertThat(report).isEmpty(); assertThat(report.isNotEmpty()).isFalse(); @@ -470,7 +469,7 @@ private void assertThatReportHasSeverities(final Report report, final int expect @Test void shouldAddMultipleIssuesOneByOne() { - Report report = new Report(); + var report = new Report(); report.add(HIGH); report.add(NORMAL_1); @@ -484,7 +483,7 @@ void shouldAddMultipleIssuesOneByOne() { @Test void shouldAddMultipleIssuesAsCollection() { - Report report = new Report(); + var report = new Report(); List issueList = allIssuesAsList(); report.addAll(issueList); @@ -494,7 +493,7 @@ void shouldAddMultipleIssuesAsCollection() { @Test void shouldIterateOverAllElementsInCorrectOrder() { - Report report = new Report(); + var report = new Report(); report.add(HIGH); report.addAll(NORMAL_1, NORMAL_2); @@ -510,9 +509,9 @@ void shouldIterateOverAllElementsInCorrectOrder() { @Test void shouldSkipAddedElements() { - Report report = new Report().addAll(allIssuesAsList()); + var report = new Report().addAll(allIssuesAsList()); - Report fromEmpty = new Report(); + var fromEmpty = new Report(); fromEmpty.addAll(report.get()); assertThatAllIssuesHaveBeenAdded(fromEmpty); @@ -521,17 +520,17 @@ void shouldSkipAddedElements() { .hasDuplicatesSize(6); assertThatReportHasSeverities(report, 0, 1, 2, 3); - Report left = new Report().addAll(HIGH, NORMAL_1, NORMAL_2); - Report right = new Report().addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); + var left = new Report().addAll(HIGH, NORMAL_1, NORMAL_2); + var right = new Report().addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); - Report everything = new Report(); + var everything = new Report(); everything.addAll(left, right); assertThat(everything).hasSize(6); } @Test void shouldAddMultipleIssuesToNonEmpty() { - Report report = new Report(); + var report = new Report(); report.add(HIGH); report.addAll(asList(NORMAL_1, NORMAL_2)); @@ -566,7 +565,7 @@ private void assertThatAllIssuesHaveBeenAdded(final Report report) { @Test void shouldSkipDuplicates() { - Report report = new Report(); + var report = new Report(); report.add(HIGH); assertThat(report).hasSize(1).hasDuplicatesSize(0); report.add(HIGH); @@ -589,7 +588,7 @@ void shouldRemoveById() { } private void shouldRemoveOneIssue(final Issue... initialElements) { - Report report = new Report(); + var report = new Report(); report.addAll(asList(initialElements)); assertThat(report.remove(HIGH.getId())).isEqualTo(HIGH); @@ -599,7 +598,7 @@ private void shouldRemoveOneIssue(final Issue... initialElements) { @Test void shouldThrowExceptionWhenRemovingWithWrongKey() { - Report report = new Report(); + var report = new Report(); UUID id = HIGH.getId(); assertThatThrownBy(() -> report.remove(id)) @@ -609,7 +608,7 @@ void shouldThrowExceptionWhenRemovingWithWrongKey() { @Test void shouldFindIfOnlyOneIssue() { - Report report = new Report(); + var report = new Report(); report.addAll(Collections.singletonList(HIGH)); Issue found = report.findById(HIGH.getId()); @@ -625,7 +624,7 @@ void shouldFindWithinMultipleIssues() { } private void shouldFindIssue(final Issue... elements) { - Report report = new Report(); + var report = new Report(); report.addAll(asList(elements)); Issue found = report.findById(HIGH.getId()); @@ -640,7 +639,7 @@ void shouldThrowExceptionWhenSearchingWithWrongKey() { } private void shouldFindNothing(final Issue... elements) { - Report report = new Report(); + var report = new Report(); report.addAll(asList(elements)); UUID id = NORMAL_2.getId(); @@ -651,7 +650,7 @@ private void shouldFindNothing(final Issue... elements) { @Test void shouldReturnEmptyListIfPropertyDoesNotMatch() { - Report report = new Report(); + var report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); Set found = report.findByProperty(Issue.bySeverity(Severity.WARNING_LOW)); @@ -661,7 +660,7 @@ void shouldReturnEmptyListIfPropertyDoesNotMatch() { @Test void testFindByProperty() { - Report report = new Report(); + var report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); Set found = report.findByProperty(Issue.bySeverity(Severity.WARNING_HIGH)); @@ -671,7 +670,7 @@ void testFindByProperty() { @Test void shouldReturnIndexedValue() { - Report report = new Report(); + var report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); assertThat(report.get(0)).isSameAs(HIGH); @@ -682,7 +681,7 @@ void shouldReturnIndexedValue() { @Test @SuppressFBWarnings("RV") void shouldThrowExceptionOnWrongIndex() { - Report report = new Report(); + var report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); assertThatThrownBy(() -> report.get(-1)) @@ -695,7 +694,7 @@ void shouldThrowExceptionOnWrongIndex() { @Test void shouldReturnFiles() { - Report report = new Report(); + var report = new Report(); report.addAll(allIssuesAsList()); assertThat(report.getFiles()).contains("file-1", "file-1", "file-3"); @@ -707,7 +706,7 @@ private List allIssuesAsList() { @Test void shouldReturnSizeInToString() { - Report report = new Report(); + var report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); assertThat(report.toString()).contains("3"); @@ -715,7 +714,7 @@ void shouldReturnSizeInToString() { @Test void shouldReturnProperties() { - Report report = new Report(); + var report = new Report(); report.addAll(allIssuesAsList()); Set properties = report.getProperties(Issue::getMessage); @@ -728,10 +727,10 @@ void shouldReturnProperties() { @Test void testCopy() { - Report original = new Report(); + var original = new Report(); original.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); - Report copy = original.copy(); + var copy = original.copy(); assertThat(copy).isNotSameAs(original); assertThat(copy.iterator()).toIterable().containsExactly(HIGH, NORMAL_1, NORMAL_2); @@ -755,7 +754,7 @@ private void assertFilterFor(final BiFunction> propertyGetter, final String propertyName, final Function> predicate) { try (IssueBuilder builder = new IssueBuilder()) { - Report report = new Report(); + var report = new Report(); for (int i = 1; i < 4; i++) { for (int j = i; j < 4; j++) { @@ -778,7 +777,7 @@ private void assertFilterFor(final BiFunction predicate = filterBuilder.setIncludeCategoryFilter("Style").build(); assertThat(checkStyle.filter(predicate)).hasSize(1).hasId(CHECKSTYLE_ID).hasName(CHECKSTYLE_NAME); - Report filtered = container.filter(predicate); + var filtered = container.filter(predicate); verifyContainer(filtered, checkstyleWarning, spotBugsWarning); - Report copy = container.copy(); + var copy = container.copy(); verifyContainer(copy, checkstyleWarning, spotBugsWarning); - Report copyOfCopy = copy.copy(); + var copyOfCopy = copy.copy(); verifyContainer(copyOfCopy, checkstyleWarning, spotBugsWarning); assertThat(container.stream().map(Issue::getOrigin).collect(Collectors.toSet())) diff --git a/src/test/java/edu/hm/hafner/analysis/SeverityTest.java b/src/test/java/edu/hm/hafner/analysis/SeverityTest.java index 671f9e9bc..073e58a80 100644 --- a/src/test/java/edu/hm/hafner/analysis/SeverityTest.java +++ b/src/test/java/edu/hm/hafner/analysis/SeverityTest.java @@ -41,7 +41,7 @@ void shouldAssignSeverities() { @Test @SuppressWarnings("PMD.LiteralsFirstInComparisons") void shouldCreateNewSeverityThatOverridesEqualsAndToString() { String name = "severity"; - Severity severity = new Severity(name); + var severity = new Severity(name); assertThat(severity.getName()).isEqualTo(name); assertThat(severity).hasToString(name); diff --git a/src/test/java/edu/hm/hafner/analysis/parser/ParserBenchmark.java b/src/test/java/edu/hm/hafner/analysis/parser/ParserBenchmark.java index c71b6535d..dcb407093 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/ParserBenchmark.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/ParserBenchmark.java @@ -65,7 +65,9 @@ public void benchmarkPmdParser(final BenchmarkState state, final Blackhole black */ @State(Scope.Benchmark) public static class BenchmarkState { + @SuppressWarnings("NullAway") private ReaderFactory checkstyleFileReaderFactory; + @SuppressWarnings("NullAway") private ReaderFactory pmdFileReaderFactory; private ReaderFactory createFileReaderFactory(final String fileName) throws URISyntaxException { diff --git a/src/test/java/edu/hm/hafner/analysis/parser/XmlParserTest.java b/src/test/java/edu/hm/hafner/analysis/parser/XmlParserTest.java index 7bfc8f8b7..7c6907e9d 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/XmlParserTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/XmlParserTest.java @@ -62,9 +62,9 @@ protected XmlParser createParser() { @Test void shouldParseWithCustomPath() { - XmlParser parser = new XmlParser(CUSTOM_PATH); - Report report = parser.parse(createReaderFactory(ISSUES_CUSTOM_PATH_FILE)); - Iterator iterator = report.iterator(); + var parser = new XmlParser(CUSTOM_PATH); + var report = parser.parse(createReaderFactory(ISSUES_CUSTOM_PATH_FILE)); + var iterator = report.iterator(); try (SoftAssertions softly = new SoftAssertions()) { softly.assertThat(report) .hasSize(2); diff --git a/src/test/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRulesTest.java b/src/test/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRulesTest.java index dad8b5b5e..f399a0abc 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRulesTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/checkstyle/CheckStyleRulesTest.java @@ -13,11 +13,13 @@ */ class CheckStyleRulesTest { private static final int NUMBER_OF_AVAILABLE_CHECKSTYLE_RULES = 163; + private static final Pattern EMPTY_ANNOTATION + = Pattern.compile(".*// empty annotation type\\s+.*", Pattern.MULTILINE | Pattern.DOTALL); /** Test whether we could parse the Checkstyle rule meta data. */ @Test void shouldLoadAndParseAllRules() { - CheckStyleRules rules = new CheckStyleRules(); + var rules = new CheckStyleRules(); assertThat(rules.getRules()).hasSize(NUMBER_OF_AVAILABLE_CHECKSTYLE_RULES); assertThat(rules.getRule("EmptyBlock")) @@ -42,7 +44,7 @@ void shouldLoadAndParseAllRules() { assertThat(rules.getRule("WhitespaceAround").getDescription()) .as("Wrong substitution of tag.") .contains("

public MyClass() {}      // empty constructor")
-                .matches(Pattern.compile(".*// empty annotation type\\s+
.*", Pattern.MULTILINE | Pattern.DOTALL)); + .matches(EMPTY_ANNOTATION); for (Rule rule : rules.getRules()) { assertThat(rule.getDescription()).as("Rule %s has no description", rule.getName()) diff --git a/src/test/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParserTest.java b/src/test/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParserTest.java index 4ceba3743..8ee1c3c45 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParserTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/dry/cpd/CpdParserTest.java @@ -123,7 +123,7 @@ void shouldAssignPriority() { } private Report parse(final int highThreshold, final int normalThreshold) { - CpdParser parser = new CpdParser(highThreshold, normalThreshold); + var parser = new CpdParser(highThreshold, normalThreshold); return parser.parse(createReaderFactory("issue12516.xml")); } diff --git a/src/test/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParserTest.java b/src/test/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParserTest.java index a14904b5d..7d00589bc 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParserTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/dry/dupfinder/DupFinderParserTest.java @@ -126,7 +126,7 @@ void shouldAssignPriority() { } private Report parse(final int highThreshold, final int normalThreshold) { - DupFinderParser parser = new DupFinderParser(highThreshold, normalThreshold); + var parser = new DupFinderParser(highThreshold, normalThreshold); return parser.parse(createReaderFactory("without-sourcecode.xml")); } } diff --git a/src/test/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParserTest.java b/src/test/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParserTest.java index 06527d467..531ded6d3 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParserTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/dry/simian/SimianParserTest.java @@ -1,5 +1,7 @@ package edu.hm.hafner.analysis.parser.dry.simian; +import java.util.Locale; + import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.Issue; @@ -108,7 +110,7 @@ void shouldFindOneDuplicationInFourFiles() { } private String getFileName(final int number) { - return String.format("C:/java/foo%d.java", number); + return String.format(Locale.ENGLISH, "C:/java/foo%d.java", number); } @Test @@ -147,7 +149,7 @@ void shouldAssignPriority() { } private Report parse(final int highThreshold, final int normalThreshold) { - SimianParser parser = new SimianParser(highThreshold, normalThreshold); + var parser = new SimianParser(highThreshold, normalThreshold); return parser.parse(createReaderFactory("twofile.xml")); } } diff --git a/src/test/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessagesTest.java b/src/test/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessagesTest.java index ebaf4abf5..476daca85 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessagesTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/findbugs/FindBugsMessagesTest.java @@ -48,7 +48,7 @@ void shouldReadAllFbContribMessages() { @Test void shouldMapMessagesToTypes() { - FindBugsMessages messages = new FindBugsMessages(); + var messages = new FindBugsMessages(); String expectedMessage = "A value that could be null is stored into a field that has been annotated as @Nonnull."; assertThat(messages.getMessage(NP_STORE_INTO_NONNULL_FIELD)) .contains(expectedMessage); @@ -64,7 +64,7 @@ void shouldMapMessagesToTypes() { @Test void issue55707() { - FindBugsMessages messages = new FindBugsMessages(); + var messages = new FindBugsMessages(); assertThat(messages.getShortMessage(PATH_TRAVERSAL_IN)) .isEqualTo("Potential Path Traversal (file read)"); assertThat(messages.getMessage(PATH_TRAVERSAL_IN)) diff --git a/src/test/java/edu/hm/hafner/analysis/parser/pmd/PmdMessagesTest.java b/src/test/java/edu/hm/hafner/analysis/parser/pmd/PmdMessagesTest.java index a8adaed1d..d9dcc7901 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/pmd/PmdMessagesTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/pmd/PmdMessagesTest.java @@ -14,7 +14,7 @@ class PmdMessagesTest { @Test void shouldInitializeRuleSets() { - PmdMessages messages = new PmdMessages(); + var messages = new PmdMessages(); assertThat(messages.size()) .as("Wrong number of rule sets found") .isEqualTo(EXPECTED_RULE_SETS_SIZE); diff --git a/src/test/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptionsTest.java b/src/test/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptionsTest.java index 37cbf6c7a..d304cd9f3 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptionsTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/pylint/PyLintDescriptionsTest.java @@ -12,7 +12,7 @@ class PyLintDescriptionsTest { @Test void shouldReadAllRules() { - PyLintDescriptions descriptions = new PyLintDescriptions(); + var descriptions = new PyLintDescriptions(); assertThat(descriptions.size()).isEqualTo(274); assertThat(descriptions.getDescription("C0112")) diff --git a/src/test/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapterTest.java b/src/test/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapterTest.java index 1fb8cdbc1..9a982e400 100644 --- a/src/test/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapterTest.java +++ b/src/test/java/edu/hm/hafner/analysis/parser/violations/CppCheckAdapterTest.java @@ -140,12 +140,12 @@ void shouldFindErrorWithoutLocation() { */ @Test void shouldSkipDuplicatesJenkins61939() { - Report first = parse("cpp-check-1.xml"); + var first = parse("cpp-check-1.xml"); assertThat(first).hasSize(2); - Report second = parse("cpp-check-2.xml"); + var second = parse("cpp-check-2.xml"); assertThat(second).hasSize(3); - Report aggregation = new Report(); + var aggregation = new Report(); aggregation.addAll(first, second); assertThat(second).hasSize(3); } diff --git a/src/test/java/edu/hm/hafner/analysis/registry/AbstractParserTest.java b/src/test/java/edu/hm/hafner/analysis/registry/AbstractParserTest.java index 84efb190a..d711ca065 100644 --- a/src/test/java/edu/hm/hafner/analysis/registry/AbstractParserTest.java +++ b/src/test/java/edu/hm/hafner/analysis/registry/AbstractParserTest.java @@ -137,7 +137,7 @@ protected Report parseDefaultFile() { void shouldBeSerializable() throws IOException { IssueParser parser = createParser(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + var out = new ByteArrayOutputStream(); try (ObjectOutputStream stream = new ObjectOutputStream(out)) { stream.writeObject(parser); } @@ -153,7 +153,7 @@ void shouldBeSerializable() throws IOException { void shouldHandleEmptyFile() { boolean passed; try { - Report report = parseStringContent(""); + var report = parseStringContent(""); passed = report.isEmpty(); } catch (ParsingException e) { diff --git a/src/test/java/edu/hm/hafner/analysis/registry/ParserRegistryTest.java b/src/test/java/edu/hm/hafner/analysis/registry/ParserRegistryTest.java index 6fca68a0c..a4c58ae2c 100644 --- a/src/test/java/edu/hm/hafner/analysis/registry/ParserRegistryTest.java +++ b/src/test/java/edu/hm/hafner/analysis/registry/ParserRegistryTest.java @@ -26,7 +26,7 @@ class ParserRegistryTest extends ResourceTest { @Test void shouldThrowExceptionIfParserNotFound() { - ParserRegistry parserRegistry = new ParserRegistry(); + var parserRegistry = new ParserRegistry(); assertThatExceptionOfType(NoSuchElementException.class) .isThrownBy(() -> parserRegistry.get("-")); @@ -34,7 +34,7 @@ void shouldThrowExceptionIfParserNotFound() { @Test void shouldFindSomeParsers() { - ParserRegistry parserRegistry = new ParserRegistry(); + var parserRegistry = new ParserRegistry(); assertThat(parserRegistry).hasIds(SPOTBUGS, CHECKSTYLE, PMD).hasNames("SpotBugs", "CheckStyle", "PMD"); assertThat(parserRegistry.get(SPOTBUGS)).hasId(SPOTBUGS).hasName("SpotBugs"); @@ -47,8 +47,8 @@ void shouldFindSomeParsers() { @Test void shouldConfigureCpdParser() { - ParserRegistry parserRegistry = new ParserRegistry(); - ParserDescriptor cpdDescriptor = parserRegistry.get("cpd"); + var parserRegistry = new ParserRegistry(); + var cpdDescriptor = parserRegistry.get("cpd"); IssueParser parser = cpdDescriptor.createParser(); @@ -78,8 +78,8 @@ void shouldAssignCorrectSeverityForSpotBugs() { private void verifyPriority(final String type, final int expectedHighSize, final int expectedNormalSize, final int expectedLowSize) { - ParserRegistry parserRegistry = new ParserRegistry(); - ParserDescriptor findbugsDescriptor = parserRegistry.get("findbugs"); + var parserRegistry = new ParserRegistry(); + var findbugsDescriptor = parserRegistry.get("findbugs"); IssueParser parser = findbugsDescriptor.createParser(new Option(FindBugsDescriptor.PRIORITY_OPTION_KEY, type)); diff --git a/src/test/java/edu/hm/hafner/analysis/registry/ParsersTest.java b/src/test/java/edu/hm/hafner/analysis/registry/ParsersTest.java index 44de4e6f5..49698a990 100644 --- a/src/test/java/edu/hm/hafner/analysis/registry/ParsersTest.java +++ b/src/test/java/edu/hm/hafner/analysis/registry/ParsersTest.java @@ -348,8 +348,8 @@ void shouldFindAllCheckStyleIssues() { private void assertThatDescriptionOfIssueIsSet(final String tool, final Issue issue, final String expectedDescription) { - ParserRegistry parserRegistry = new ParserRegistry(); - ParserDescriptor descriptor = parserRegistry.get(tool); + var parserRegistry = new ParserRegistry(); + var descriptor = parserRegistry.get(tool); assertThat(issue).hasDescription(""); assertThat(descriptor.getDescription(issue)).contains(expectedDescription); @@ -359,7 +359,7 @@ private void assertThatDescriptionOfIssueIsSet(final String tool, final Issue is @Test void shouldFindAllFindBugsIssues() { String findbugs = "findbugs"; - Report report = findIssuesOfTool(2, findbugs, "findbugs-native.xml"); + var report = findIssuesOfTool(2, findbugs, "findbugs-native.xml"); assertThatDescriptionOfIssueIsSet(findbugs, report.get(0), "

The fields of this class appear to be accessed inconsistently with respect\n" @@ -406,7 +406,7 @@ void shouldFindAllSpotBugsIssues() { + "

"; String spotBugs = "spotbugs"; - Report report = findIssuesOfTool(2, spotBugs, "spotbugsXml.xml"); + var report = findIssuesOfTool(2, spotBugs, "spotbugsXml.xml"); assertThatDescriptionOfIssueIsSet(spotBugs, report.get(0), expectedDescription); } @@ -420,8 +420,8 @@ void shouldProvideMessagesAndDescriptionForSecurityIssuesWithSpotBugs() { + "by the user. If that is the case, the reported instance is a false positive.

"; String spotBugs = "spotbugs"; - Report report = findIssuesOfTool(1, spotBugs, "issue55707.xml"); - Issue issue = report.get(0); + var report = findIssuesOfTool(1, spotBugs, "issue55707.xml"); + var issue = report.get(0); assertThatDescriptionOfIssueIsSet(spotBugs, issue, expectedDescription); assertThat(issue).hasMessage( "java/nio/file/Paths.get(Ljava/lang/String;[Ljava/lang/String;)Ljava/nio/file/Path; reads a file whose location might be specified by user input"); @@ -868,10 +868,10 @@ void shouldFindAllOELintAdvIssues() { } private Report findIssuesOfTool(final int expectedSizeOfIssues, final String tool, final String... fileNames) { - ParserRegistry registry = new ParserRegistry(); - ParserDescriptor descriptor = registry.get(tool); + var registry = new ParserRegistry(); + var descriptor = registry.get(tool); - Report allIssues = new Report(); + var allIssues = new Report(); for (String fileName : fileNames) { IssueParser parser = descriptor.createParser(); Report report = parser.parse(new FileReaderFactory(getResourceAsFile("../parser/").resolve(fileName)));