Skip to content

Commit

Permalink
Apply recipes of org.openrewrite.staticanalysis.
Browse files Browse the repository at this point in the history
  • Loading branch information
uhafner committed Nov 19, 2024
1 parent 1a306f2 commit 8111479
Show file tree
Hide file tree
Showing 226 changed files with 1,616 additions and 1,598 deletions.
15 changes: 15 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,21 @@

<build>
<plugins>
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<version>${rewrite-maven-plugin.version}</version>
<configuration>
<activeRecipes>
<recipe>org.openrewrite.java.migrate.UpgradeToJava17</recipe>
<recipe>org.openrewrite.java.migrate.util.SequencedCollection</recipe>
<recipe>org.openrewrite.java.migrate.lang.var.UseVarForObject</recipe>
<recipe>org.openrewrite.java.migrate.net.JavaNetAPIs</recipe>
<recipe>org.openrewrite.java.migrate.util.JavaUtilAPIs</recipe>
<recipe>org.openrewrite.java.migrate.lang.StringRulesRecipes</recipe>
</activeRecipes>
</configuration>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ abstract class AbstractPackageDetector {
*/
public String detectPackageName(final String fileName, final Charset charset) {
if (accepts(fileName)) {
try (InputStream stream = fileSystem.openFile(fileName)) {
try (var stream = fileSystem.openFile(fileName)) {
return detectPackageName(stream, charset);
}
catch (IOException | InvalidPathException ignore) {
Expand All @@ -58,7 +58,7 @@ public String detectPackageName(final String fileName, final Charset charset) {

@VisibleForTesting
String detectPackageName(final InputStream stream, final Charset charset) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(BOMInputStream.builder().setInputStream(stream).get(), charset))) {
try (var buffer = new BufferedReader(new InputStreamReader(BOMInputStream.builder().setInputStream(stream).get(), charset))) {
return detectPackageName(buffer.lines());
}
}
Expand All @@ -73,7 +73,7 @@ String detectPackageName(final InputStream stream, final Charset charset) throws
* @return the detected package or namespace name
*/
String detectPackageName(final Stream<String> lines) {
Pattern pattern = getPattern();
var pattern = getPattern();
return lines.map(pattern::matcher)
.filter(Matcher::matches)
.findFirst()
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/edu/hm/hafner/analysis/AntModuleDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,15 @@ void collectProjects(final Map<String, String> mapping, final List<String> proje
* @return the project name or an empty string if the name could not be resolved
*/
private String parseBuildXml(final String buildXml) {
try (InputStream file = getFactory().open(buildXml)) {
try (var file = getFactory().open(buildXml)) {
var digester = new SecureDigester(ModuleDetector.class);

digester.push(new StringBuilder());
String xPath = "project";
var xPath = "project";
digester.addCallMethod(xPath, "append", 1);
digester.addCallParam(xPath, 0, "name");

StringBuilder result = digester.parse(file);
var result = digester.parse(file);
return result.toString();
}
catch (IOException | SAXException | InvalidPathException ignored) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/hm/hafner/analysis/Categories.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public static String guessCategory(@CheckForNull final String message) {
* @return the actual category
*/
public static String guessCategoryIfEmpty(@CheckForNull final String category, @CheckForNull final String message) {
String capitalized = StringUtils.capitalize(category);
var capitalized = StringUtils.capitalize(category);
if (StringUtils.isEmpty(capitalized)) {
capitalized = guessCategory(message);
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/hm/hafner/analysis/FileNameResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void run(final Report report, final String sourceDirectoryPrefix,
.filter(entry -> PATH_UTIL.exists(entry.getValue(), sourceDirectoryPrefix))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

try (IssueBuilder builder = new IssueBuilder()) {
try (var builder = new IssueBuilder()) {
report.stream()
.filter(issue -> pathMapping.containsKey(issue.getFileName()))
.forEach(issue -> issue.setFileName(sourceDirectoryPrefix,
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/edu/hm/hafner/analysis/FileReaderFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ public Reader create() {

@CheckForNull
private Charset detectCharset(final InputStream inputStream) throws IOException {
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.US_ASCII)) {
XMLStreamReader xmlStreamReader = new SecureXmlParserFactory().createXmlStreamReader(reader);
String encodingTitle = xmlStreamReader.getCharacterEncodingScheme();
try (var reader = new InputStreamReader(inputStream, StandardCharsets.US_ASCII)) {
var xmlStreamReader = new SecureXmlParserFactory().createXmlStreamReader(reader);
var encodingTitle = xmlStreamReader.getCharacterEncodingScheme();
if (encodingTitle != null) {
return Charset.forName(encodingTitle);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ private boolean hasAllowedExtension(final String fileName) {

private int computeFingerprint(final Issue issue, final FullTextFingerprint algorithm, final Charset charset,
final FilteredLog log) {
String absolutePath = issue.getAbsolutePath();
var absolutePath = issue.getAbsolutePath();
try {
if (issue.hasFileName()) {
String digest = algorithm.compute(absolutePath, issue.getLineStart(), charset);
var digest = algorithm.compute(absolutePath, issue.getLineStart(), charset);
issue.setFingerprint(digest);
return 1;
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/edu/hm/hafner/analysis/FullTextFingerprint.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
Expand Down Expand Up @@ -83,7 +83,7 @@ String getFallbackFingerprint(final String fileName) {

@VisibleForTesting
String createFingerprint(final int line, final Stream<String> lines, final Charset charset) {
String context = extractContext(line, lines.iterator());
var context = extractContext(line, lines.iterator());
lines.close();
digest.update(context.getBytes(charset));

Expand Down Expand Up @@ -137,7 +137,7 @@ static class FileSystem {
@MustBeClosed
Stream<String> readLinesFromFile(final String fileName, final Charset charset)
throws IOException, InvalidPathException {
return Files.lines(Paths.get(fileName), charset);
return Files.lines(Path.of(fileName), charset);
}
}
}
10 changes: 5 additions & 5 deletions src/main/java/edu/hm/hafner/analysis/GradleModuleDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ else if (fileName.endsWith(SETTINGS_GRADLE) || fileName.endsWith(SETTINGS_GRADLE
* @return the project name or an empty string if the name could not be resolved
*/
private String parseGradle(final String buildScript) {
String basePath = FilenameUtils.getPathNoEndSeparator(buildScript);
String parentDirName = FilenameUtils.getName(basePath);
var basePath = FilenameUtils.getPathNoEndSeparator(buildScript);
var parentDirName = FilenameUtils.getName(basePath);
return StringUtils.trimToEmpty(parentDirName);
}

Expand All @@ -75,10 +75,10 @@ private String parseGradle(final String buildScript) {
private String parseGradleSettings(final String settingsFile) {
String name = null;

try (InputStream input = getFactory().open(settingsFile);
Scanner scan = new Scanner(input, "UTF-8")) {
try (var input = getFactory().open(settingsFile);
var scan = new Scanner(input, "UTF-8")) {
while (scan.hasNextLine()) {
String line = scan.findInLine(RE_GRADLE_SET_PROJECT_NAME);
var line = scan.findInLine(RE_GRADLE_SET_PROJECT_NAME);

if (line != null) {
name = scan.match().group(2);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/edu/hm/hafner/analysis/Issue.java
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ TreeString getFileNameTreeString() {
*/
public String getFolder() {
try {
String folder = FilenameUtils.getPath(getFileName());
var folder = FilenameUtils.getPath(getFileName());
if (StringUtils.isBlank(folder)) {
return UNDEFINED;
}
Expand Down Expand Up @@ -905,7 +905,7 @@ public boolean equals(@CheckForNull final Object o) {
return false;
}

Issue issue = (Issue) o;
var issue = (Issue) o;

if (lineStart != issue.lineStart) {
return false;
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/edu/hm/hafner/analysis/IssueBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ public IssueBuilder copy(final Issue copy) {
* @return the created issue
*/
public Issue build() {
Issue issue = buildWithConstructor();
var issue = buildWithConstructor();
id = UUID.randomUUID(); // make sure that multiple invocations will create different IDs
return issue;
}
Expand All @@ -546,7 +546,7 @@ public Issue build() {
* @return the created issue
*/
public Issue buildAndClean() {
Issue issue = buildWithConstructor();
var issue = buildWithConstructor();
clean();
return issue;
}
Expand All @@ -566,7 +566,7 @@ private Issue buildWithConstructor() {
@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH", justification = "False positive, `lineRanges != null` avoids a NullPointerException")
private void cleanupLineRanges() {
if (lineRanges != null && !lineRanges.isEmpty()) {
LineRange firstRange = lineRanges.get(0);
var firstRange = lineRanges.get(0);
if (lineStart == 0) {
this.lineStart = firstRange.getStart();
this.lineEnd = firstRange.getEnd();
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/edu/hm/hafner/analysis/IssueDifference.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public IssueDifference(final Report currentIssues, final String referenceId,
}

List<UUID> removed = matchIssuesByEquals(currentIssues);
Report secondPass = currentIssues.copy();
var secondPass = currentIssues.copy();
removed.forEach(secondPass::remove);
matchIssuesByFingerprint(secondPass);

Expand Down Expand Up @@ -128,8 +128,8 @@ private <K> void removeIssueFromMap(final Map<K, List<Issue>> map, final K key,
}

private UUID remove(final Issue current, final Issue oldIssue) {
UUID id = current.getId();
Issue issueWithLatestProperties = newIssues.remove(id);
var id = current.getId();
var issueWithLatestProperties = newIssues.remove(id);
issueWithLatestProperties.setReference(oldIssue.getReference());
outstandingIssues.add(issueWithLatestProperties);
fixedIssues.remove(oldIssue.getId());
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/hm/hafner/analysis/IssueParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public abstract class IssueParser implements Serializable {
* Signals that the user has aborted the parsing
*/
public Report parseFile(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException {
Report report = parse(readerFactory);
var report = parse(readerFactory);
report.setOriginReportFile(readerFactory.getFileName());
return report;
}
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/edu/hm/hafner/analysis/LookaheadParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ protected LookaheadParser(final String pattern) {
public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException {
var report = new Report();
try (Stream<String> lines = readerFactory.readStream()) {
try (LookaheadStream lookahead = new LookaheadStream(lines, readerFactory.getFileName())) {
try (var lookahead = new LookaheadStream(lines, readerFactory.getFileName())) {
parse(report, lookahead);
}
}
Expand All @@ -70,13 +70,13 @@ public Report parse(final ReaderFactory readerFactory) throws ParsingException,

@SuppressWarnings("PMD.DoNotUseThreads")
private void parse(final Report report, final LookaheadStream lookahead) {
try (IssueBuilder builder = new IssueBuilder()) {
try (var builder = new IssueBuilder()) {
while (lookahead.hasNext()) {
String line = lookahead.next();
var line = lookahead.next();
handleDirectoryChanges(builder, line, report);
preprocessLine(line);
if (isLineInteresting(line)) {
Matcher matcher = pattern.matcher(line);
var matcher = pattern.matcher(line);
if (matcher.find()) {
createIssue(matcher, lookahead, builder).ifPresent(report::add);
}
Expand Down Expand Up @@ -174,10 +174,10 @@ private Optional<String> extractDirectory(final String line, final Pattern makeP
throws ParsingException {
if (!makePath.toString().contains("<dir>")) {
throw new IllegalArgumentException(
String.format("%s does not contain a capture group named 'dir'", makePath));
"%s does not contain a capture group named 'dir'".formatted(makePath));
}

Matcher makeLineMatcher = makePath.matcher(line);
var makeLineMatcher = makePath.matcher(line);
if (makeLineMatcher.matches()) {
return Optional.of(removeHyphen(makeLineMatcher.group("dir")));
}
Expand Down Expand Up @@ -239,7 +239,7 @@ protected Report postProcess(final Report report) {
* @return directory path without leading or trailing hyphen
*/
private String removeHyphen(final String dir) {
String path = dir;
var path = dir;
path = StringUtils.stripStart(path, HYPHEN);
path = StringUtils.stripEnd(path, HYPHEN);
return path;
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/edu/hm/hafner/analysis/MavenModuleDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,19 @@ public void collectProjects(final Map<String, String> mapping, final List<String
* @return the project name or an empty string if the name could not be resolved
*/
private String parsePom(final String pom) {
String name = parsePomAttribute(pom, "name");
var name = parsePomAttribute(pom, "name");

return StringUtils.defaultIfBlank(name, parsePomAttribute(pom, "artifactId"));
}

@SuppressWarnings("OverlyBroadCatchBlock")
private String parsePomAttribute(final String pom, final String tagName) {
try (InputStream file = getFactory().open(pom)) {
try (var file = getFactory().open(pom)) {
var digester = new SecureDigester(ModuleDetector.class);
digester.push(new StringBuilder());
digester.addCallMethod("project/" + tagName, "append", 0);

StringBuilder result = digester.parse(file);
var result = digester.parse(file);
return result.toString();
}
catch (IOException | SAXException | InvalidPathException ignored) {
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/edu/hm/hafner/analysis/ModuleDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ private Map<String, String> createFilesToModuleMapping(final Path workspace) {
* @return a module name or an empty string
*/
public String guessModuleName(final String originalFileName) {
String fullPath = originalFileName.replace('\\', '/');
var fullPath = originalFileName.replace('\\', '/');

String guessedModule = StringUtils.EMPTY;
var guessedModule = StringUtils.EMPTY;
for (String path : prefixes) {
if (fullPath.startsWith(path) && fileNameToModuleName.containsKey(path)) {
guessedModule = fileNameToModuleName.get(path);
Expand All @@ -111,9 +111,9 @@ private List<String> find(final Path path) {
List<String> absoluteFileNames = new ArrayList<>();

for (AbstractModuleDetector moduleDetector : moduleDetectors) {
String[] relativeFileNames = factory.find(path, moduleDetector.getPattern());
var relativeFileNames = factory.find(path, moduleDetector.getPattern());
for (String relativeFileName : relativeFileNames) {
String relativePath = normalizePath(relativeFileName);
var relativePath = normalizePath(relativeFileName);
if (relativePath.startsWith(SLASH)) {
absoluteFileNames.add(relativePath);
}
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/edu/hm/hafner/analysis/OsgiModuleDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ public void collectProjects(final Map<String, String> mapping, final List<String
* @return the project name or an empty string if the name could not be resolved
*/
private String parseManifest(final String manifestFile) {
try (InputStream file = getFactory().open(manifestFile)) {
try (var file = getFactory().open(manifestFile)) {
var manifest = new Manifest(file);
var attributes = manifest.getMainAttributes();
var properties = readProperties(StringUtils.substringBefore(manifestFile, OSGI_BUNDLE));
String name = getLocalizedValue(attributes, properties, BUNDLE_NAME);
var name = getLocalizedValue(attributes, properties, BUNDLE_NAME);
if (StringUtils.isNotBlank(name)) {
return name;
}
Expand All @@ -78,7 +78,7 @@ private Properties readProperties(final String path) {

@SuppressWarnings("OverlyBroadCatchBlock")
private void readProperties(final String path, final Properties properties, final String fileName) {
try (InputStream file = getFactory().open(path + SLASH + fileName)) {
try (var file = getFactory().open(path + SLASH + fileName)) {
properties.load(file);
}
catch (IOException | InvalidPathException ignored) {
Expand All @@ -88,17 +88,17 @@ private void readProperties(final String path, final Properties properties, fina

private String getLocalizedValue(final Attributes attributes, final Properties properties,
final String bundleName) {
String value = attributes.getValue(bundleName);
var value = attributes.getValue(bundleName);
if (StringUtils.startsWith(StringUtils.trim(value), REPLACEMENT_CHAR)) {
return properties.getProperty(StringUtils.substringAfter(value, REPLACEMENT_CHAR));
}
return value;
}

private String getSymbolicName(final Attributes attributes, final Properties properties) {
String symbolicName = StringUtils.substringBefore(attributes.getValue(BUNDLE_SYMBOLIC_NAME), ";");
var symbolicName = StringUtils.substringBefore(attributes.getValue(BUNDLE_SYMBOLIC_NAME), ";");
if (StringUtils.isNotBlank(symbolicName)) {
String vendor = getLocalizedValue(attributes, properties, BUNDLE_VENDOR);
var vendor = getLocalizedValue(attributes, properties, BUNDLE_VENDOR);
if (StringUtils.isNotBlank(vendor)) {
return symbolicName + " (" + vendor + ")";
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/edu/hm/hafner/analysis/PackageDetectors.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.List;

import com.google.errorprone.annotations.MustBeClosed;
Expand Down Expand Up @@ -54,7 +54,7 @@ public String detectPackageName(final String fileName, final Charset charset) {
static class FileSystem {
@MustBeClosed
InputStream openFile(final String fileName) throws IOException, InvalidPathException {
return Files.newInputStream(Paths.get(fileName));
return Files.newInputStream(Path.of(fileName));
}
}
}
Loading

0 comments on commit 8111479

Please sign in to comment.