From 5f2b9f3d45015fb451a5115b67077462737671d0 Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Sat, 21 Oct 2023 23:05:25 +0000 Subject: [PATCH] refactor: Common static analysis issues Use this link to re-run the recipe: https://app.moderne.io/recipes/org.openrewrite.staticanalysis.CommonStaticAnalysis?organizationId=T3BlblJld3JpdGU%3D Co-authored-by: Moderne --- .../analysis/InvocationMatcher.java | 6 +-- .../analysis/controlflow/ControlFlow.java | 37 +++++++++---------- .../ControlFlowIllegalStateException.java | 2 +- .../controlflow/ControlFlowJavaPrinter.java | 2 +- .../analysis/controlflow/ControlFlowNode.java | 13 +++---- .../ControlFlowSummaryDotVisualizer.java | 3 +- .../ControlFlowVisualizationVisitor.java | 6 ++- .../analysis/controlflow/Guard.java | 2 +- .../analysis/dataflow/ExternalFlowModels.java | 20 ++++------ .../search/FindFlowBetweenMethods.java | 2 +- .../org/openrewrite/analysis/trait/Top.java | 8 +++- .../trait/member/StaticInitializerMethod.java | 2 +- .../FindLocalFlowPathsStringTest.java | 6 +-- .../dataflow/ParameterDataflowTest.java | 2 +- .../ArchiveAnalyzer.java | 10 ++--- .../dataflow-functional-tests/FileUtils.java | 20 ++++------ .../JavaTypeGoat.java | 6 +-- .../dataflow-functional-tests/JobUtils.java | 2 +- .../MatchPatternsFileFilter.java | 3 +- .../SecurityUtils.java | 37 ++++++++++--------- .../SimpleFileServer.java | 2 +- .../TermuxDocumentsProvider.java | 24 ++++++++---- .../TestAssignmentToNull.java | 2 +- 23 files changed, 110 insertions(+), 107 deletions(-) diff --git a/src/main/java/org/openrewrite/analysis/InvocationMatcher.java b/src/main/java/org/openrewrite/analysis/InvocationMatcher.java index 43c096d61..b1bb14074 100644 --- a/src/main/java/org/openrewrite/analysis/InvocationMatcher.java +++ b/src/main/java/org/openrewrite/analysis/InvocationMatcher.java @@ -107,10 +107,8 @@ public boolean isSelect(Cursor cursor) { public boolean isAnyArgument(Cursor cursor) { return asExpression( cursor, - expression -> nearestMethodCall(cursor).map(call -> { - return call.getArguments().contains(expression) - && matcher.matches(call); // Do the matcher.matches(...) last as this can be expensive - }).orElse(false) + expression -> nearestMethodCall(cursor).map(call -> call.getArguments().contains(expression) + && matcher.matches(call)).orElse(false) ); } diff --git a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlow.java b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlow.java index 5649db80d..35581c18d 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlow.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlow.java @@ -234,11 +234,11 @@ public J.Block visitBlock(J.Block block, P p) { } @Override - public J.Synchronized visitSynchronized(J.Synchronized _sync, P p) { + public J.Synchronized visitSynchronized(J.Synchronized sync, P p) { addCursorToBasicBlock(); - visit(_sync.getLock(), p); - visit(_sync.getBody(), p); - return _sync; + visit(sync.getLock(), p); + visit(sync.getBody(), p); + return sync; } @Override @@ -353,20 +353,17 @@ public J.Case visitCase(J.Case _case, P p) { ControlFlowNode.ConditionNode conditionNode = currentAsBasicBlock().addConditionNodeTruthFirst(); current = Stream.concat(Stream.of(conditionNode), caseFlow.stream()).collect(Collectors.toSet()); caseFlow.clear(); - switch (_case.getType()) { - case Statement: - if (_case.getStatements().isEmpty()) { - // Visit a fake empty statement to ensure that the ConditionNode has a true successor - visit(new J.Empty(randomId(), Space.EMPTY, Markers.EMPTY), p); - } else { - visitStatementList(_case.getStatements(), p); - } - break; - case Rule: - visit(_case.getBody(), p); - breakFlow.add(currentAsBasicBlock()); - current = Collections.emptySet(); - break; + if (_case.getType() == J.Case.Type.Statement) { + if (_case.getStatements().isEmpty()) { + // Visit a fake empty statement to ensure that the ConditionNode has a true successor + visit(new J.Empty(randomId(), Space.EMPTY, Markers.EMPTY), p); + } else { + visitStatementList(_case.getStatements(), p); + } + } else if (_case.getType() == J.Case.Type.Rule) { + visit(_case.getBody(), p); + breakFlow.add(currentAsBasicBlock()); + current = Collections.emptySet(); } caseFlow.addAll(current); current = Collections.singleton(conditionNode); @@ -393,7 +390,7 @@ public J.Case visitCase(J.Case _case, P p) { private static Set allAsConditionNodesMissingTruthFirst(Set nodes) { return nodes.stream().map(controlFlowNode -> { if (controlFlowNode instanceof ControlFlowNode.ConditionNode) { - return ((ControlFlowNode.ConditionNode) controlFlowNode); + return (ControlFlowNode.ConditionNode) controlFlowNode; } else { return controlFlowNode.addConditionNodeTruthFirst(); } @@ -403,7 +400,7 @@ private static Set allAsConditionNodesMissingTrut private static Set allAsConditionNodesMissingFalseFirst(Set nodes) { return nodes.stream().map(controlFlowNode -> { if (controlFlowNode instanceof ControlFlowNode.ConditionNode) { - return ((ControlFlowNode.ConditionNode) controlFlowNode); + return (ControlFlowNode.ConditionNode) controlFlowNode; } else { return controlFlowNode.addConditionNodeFalseFirst(); } diff --git a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowIllegalStateException.java b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowIllegalStateException.java index b2978fdea..61dfacdcc 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowIllegalStateException.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowIllegalStateException.java @@ -43,7 +43,7 @@ static class Message { Set predecessors; Cursor cursor; - static class MessageBuilder { + static final class MessageBuilder { private final String message; // LinkedHashMap to preserve order of insertion1 private final LinkedHashMap nodes = new LinkedHashMap<>(); diff --git a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowJavaPrinter.java b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowJavaPrinter.java index 8580dc013..eff4c6efd 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowJavaPrinter.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowJavaPrinter.java @@ -325,7 +325,7 @@ public J visitEmpty(J.Empty empty, PrintOutputCapture

pPrintOutputCapture) { } static class ControlFlowPrintOutputCapture

extends PrintOutputCapture

{ - boolean enabled = false; + boolean enabled; public ControlFlowPrintOutputCapture(P p) { super(p); diff --git a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowNode.java b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowNode.java index 7074a21fb..b94ec91a5 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowNode.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowNode.java @@ -242,11 +242,10 @@ String toVisualizerString() { // Self loathing J.Case caseStatement = (J.Case) condition; String caseString = caseStatement.toString(); - switch (caseStatement.getType()) { - case Statement: - return caseString.substring(0, caseString.indexOf(":") + 1); - case Rule: - return caseString.substring(0, caseString.indexOf("->") + 2); + if (caseStatement.getType() == J.Case.Type.Statement) { + return caseString.substring(0, caseString.indexOf(":") + 1); + } else if (caseStatement.getType() == J.Case.Type.Rule) { + return caseString.substring(0, caseString.indexOf("->") + 2); } } return condition.toString(); @@ -424,7 +423,7 @@ static final class Start extends ControlFlowNode implements GraphTerminator { @Getter private final GraphType graphType; - private ControlFlowNode successor = null; + private ControlFlowNode successor; @Override protected void _addSuccessorInternal(ControlFlowNode successor) { @@ -470,7 +469,7 @@ public String toString() { static final class End extends ControlFlowNode implements GraphTerminator { @Getter private final GraphType graphType; - private ControlFlowNode successor = null; + private ControlFlowNode successor; @Override Set getSuccessors() { diff --git a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowSummaryDotVisualizer.java b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowSummaryDotVisualizer.java index d1cd373f6..12d43383d 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowSummaryDotVisualizer.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowSummaryDotVisualizer.java @@ -44,7 +44,8 @@ public String visualizeAsDotfile(String name, boolean darkMode, ControlFlowSumma .map(NodeToNodeText::new) .sorted() .collect(Collectors.toList()); - int vizSrc = -1, vizSink = -1; + int vizSrc = -1; + int vizSink = -1; for (int i = 0; i < nodeToNodeText.size(); i++) { NodeToNodeText toNodeText = nodeToNodeText.get(i); ControlFlowNode node = toNodeText.node; diff --git a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowVisualizationVisitor.java b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowVisualizationVisitor.java index 790751644..1d14193a4 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowVisualizationVisitor.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/ControlFlowVisualizationVisitor.java @@ -98,7 +98,7 @@ public J.Block visitBlock(J.Block block, P p) { private static class ControlFlowMarkingVisitor

extends JavaIsoVisitor

{ private final String label; private final Map nodeToBlock; - private int nodeNumber = 0; + private int nodeNumber; private final Map nodeNumbers = new HashMap<>(); @Override @@ -128,7 +128,9 @@ public Statement visitStatement(Statement statement, P p) { } else { return SearchResult.found(statement, "" + number + label); } - } else return statement; + } else { + return statement; + } } @Override diff --git a/src/main/java/org/openrewrite/analysis/controlflow/Guard.java b/src/main/java/org/openrewrite/analysis/controlflow/Guard.java index 5943f2278..96c0e34ad 100644 --- a/src/main/java/org/openrewrite/analysis/controlflow/Guard.java +++ b/src/main/java/org/openrewrite/analysis/controlflow/Guard.java @@ -161,7 +161,7 @@ private static Optional getTypeSafe(Cursor c, Expression e) { } } else if (e instanceof J.MethodInvocation) { J.MethodInvocation methodInvocation = (J.MethodInvocation) e; - if (methodInvocation.getSimpleName().equals("equals")) { + if ("equals".equals(methodInvocation.getSimpleName())) { return Optional.of(JavaType.Primitive.Boolean); } } diff --git a/src/main/java/org/openrewrite/analysis/dataflow/ExternalFlowModels.java b/src/main/java/org/openrewrite/analysis/dataflow/ExternalFlowModels.java index 962992154..673f8c83e 100644 --- a/src/main/java/org/openrewrite/analysis/dataflow/ExternalFlowModels.java +++ b/src/main/java/org/openrewrite/analysis/dataflow/ExternalFlowModels.java @@ -101,7 +101,7 @@ boolean isAdditionalTaintStep( } @AllArgsConstructor - final static class OptimizedFlowModels { + static final class OptimizedFlowModels { private final Map> value; private final Map> taint; @@ -243,32 +243,26 @@ private Map> optimize(Collection { - return new PredicateToFlowModels(forFlowFromArgumentIndexToReturn( + .map(entry -> new PredicateToFlowModels(forFlowFromArgumentIndexToReturn( entry.getKey(), entry.getValue() - ), entry.getValue()); - }); + ), entry.getValue())); Stream flowFromArgumentIndexToQualifierStream = flowFromArgumentIndexToQualifier .entrySet() .stream() - .map(entry -> { - return new PredicateToFlowModels(forFlowFromArgumentIndexToQualifier( + .map(entry -> new PredicateToFlowModels(forFlowFromArgumentIndexToQualifier( entry.getKey(), entry.getValue() - ), entry.getValue()); - }); + ), entry.getValue())); Stream flowFromArgumentIndexToArgumentIndexStream = flowFromArgumentIndexToArgumentIndex .entrySet() .stream() - .map(entry -> { - return new PredicateToFlowModels(forFlowFromArgumentIndexToArgumentIndex( + .map(entry -> new PredicateToFlowModels(forFlowFromArgumentIndexToArgumentIndex( entry.getKey(), entry.getValue() - ), entry.getValue()); - }); + ), entry.getValue())); Stream s1 = Stream.concat(flowFromArgumentIndexToReturnStream, flowFromArgumentIndexToQualifierStream); return Stream.concat(s1, flowFromArgumentIndexToArgumentIndexStream) diff --git a/src/main/java/org/openrewrite/analysis/search/FindFlowBetweenMethods.java b/src/main/java/org/openrewrite/analysis/search/FindFlowBetweenMethods.java index c6252fbaf..171a6143e 100644 --- a/src/main/java/org/openrewrite/analysis/search/FindFlowBetweenMethods.java +++ b/src/main/java/org/openrewrite/analysis/search/FindFlowBetweenMethods.java @@ -96,7 +96,7 @@ public GlobalDataFlow.Accumulator getInitialValue(ExecutionContext ctx) { String flow = this.flow == null ? "Data" : this.flow; - if (flow.equals("Taint")) { + if ("Taint".equals(flow)) { return GlobalDataFlow.accumulator(new TaintFlowSpec() { @Override diff --git a/src/main/java/org/openrewrite/analysis/trait/Top.java b/src/main/java/org/openrewrite/analysis/trait/Top.java index 0db17066d..fb72b5f3e 100644 --- a/src/main/java/org/openrewrite/analysis/trait/Top.java +++ b/src/main/java/org/openrewrite/analysis/trait/Top.java @@ -30,8 +30,12 @@ public interface Top { UUID getId(); static boolean equals(Top e1, @Nullable Object other) { - if (e1 == other) return true; - if (other == null || e1.getClass() != other.getClass()) return false; + if (e1 == other) { + return true; + } + if (other == null || e1.getClass() != other.getClass()) { + return false; + } Top e2 = (Top) other; return e1.getId().equals(e2.getId()); } diff --git a/src/main/java/org/openrewrite/analysis/trait/member/StaticInitializerMethod.java b/src/main/java/org/openrewrite/analysis/trait/member/StaticInitializerMethod.java index ed1bfbf95..af4c5bbbf 100644 --- a/src/main/java/org/openrewrite/analysis/trait/member/StaticInitializerMethod.java +++ b/src/main/java/org/openrewrite/analysis/trait/member/StaticInitializerMethod.java @@ -23,7 +23,7 @@ * A static initializer is a method that contains all static * field initializations and static initializer blocks. */ -public class StaticInitializerMethod extends InitializerMethodBase { +public final class StaticInitializerMethod extends InitializerMethodBase { private StaticInitializerMethod(Cursor cursor) { super(cursor); } diff --git a/src/test/java/org/openrewrite/analysis/dataflow/FindLocalFlowPathsStringTest.java b/src/test/java/org/openrewrite/analysis/dataflow/FindLocalFlowPathsStringTest.java index ec54dbc53..812db801c 100644 --- a/src/test/java/org/openrewrite/analysis/dataflow/FindLocalFlowPathsStringTest.java +++ b/src/test/java/org/openrewrite/analysis/dataflow/FindLocalFlowPathsStringTest.java @@ -57,8 +57,8 @@ public boolean isSource(DataFlowNode srcNode) { .map("42"::equals) .orSome(() -> srcNode .asExpr(MethodAccess.class) - .map(ma -> ma.getSimpleName() - .equals("source")) + .map(ma -> "source" + .equals(ma.getSimpleName())) .orSome(false)); } @@ -70,7 +70,7 @@ public boolean isSink(DataFlowNode sinkNode) { @Override public boolean isBarrierGuard(Guard guard, boolean branch) { if (guard.getExpression() instanceof J.MethodInvocation) { - return branch && ((J.MethodInvocation) guard.getExpression()).getName().getSimpleName().equals("guard"); + return branch && "guard".equals(((J.MethodInvocation) guard.getExpression()).getName().getSimpleName()); } return super.isBarrierGuard(guard, branch); } diff --git a/src/test/java/org/openrewrite/analysis/dataflow/ParameterDataflowTest.java b/src/test/java/org/openrewrite/analysis/dataflow/ParameterDataflowTest.java index bf4205a04..1e3acfb78 100644 --- a/src/test/java/org/openrewrite/analysis/dataflow/ParameterDataflowTest.java +++ b/src/test/java/org/openrewrite/analysis/dataflow/ParameterDataflowTest.java @@ -30,7 +30,7 @@ public void defaults(RecipeSpec spec) { public boolean isSource(DataFlowNode srcNode) { return srcNode .asParameter() - .map(p -> p.getName().equals("source")) + .map(p -> "source".equals(p.getName())) .orSome(false); } diff --git a/src/test/resources/dataflow-functional-tests/ArchiveAnalyzer.java b/src/test/resources/dataflow-functional-tests/ArchiveAnalyzer.java index 06fb86148..e48e1901e 100644 --- a/src/test/resources/dataflow-functional-tests/ArchiveAnalyzer.java +++ b/src/test/resources/dataflow-functional-tests/ArchiveAnalyzer.java @@ -84,7 +84,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { /** * The parent directory for the individual directories per archive. */ - private File tempFileLocation = null; + private File tempFileLocation; /** * The max scan depth that the analyzer will recursively extract nested * archives. @@ -93,7 +93,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { /** * The file filter used to filter supported files. */ - private FileFilter fileFilter = null; + private FileFilter fileFilter; /** * The set of things we can handle with Zip methods */ @@ -315,7 +315,7 @@ private void extractAndAnalyze(Dependency dependency, Engine engine, int scanDep extractAndAnalyze(d, engine, scanDepth + 1); } } else { - dependencySet.stream().filter((sub) -> sub.getFilePath().startsWith(tmpDir.getAbsolutePath())).forEach((sub) -> { + dependencySet.stream().filter(sub -> sub.getFilePath().startsWith(tmpDir.getAbsolutePath())).forEach(sub -> { final String displayPath = String.format("%s%s", dependency.getFilePath(), sub.getActualFilePath().substring(tmpDir.getAbsolutePath().length())); @@ -361,13 +361,13 @@ private void addDisguisedJarsToDependencies(Dependency dependency, Engine engine org.apache.commons.io.FileUtils.copyFile(dependency.getActualFile(), tmpLoc); final List dependencySet = findMoreDependencies(engine, tmpLoc); if (dependencySet != null && !dependencySet.isEmpty()) { - dependencySet.forEach((d) -> { + dependencySet.forEach(d -> { //fix the dependency's display name and path if (d.getActualFile().equals(tmpLoc)) { d.setFilePath(dependency.getFilePath()); d.setDisplayFileName(dependency.getFileName()); } else { - d.getRelatedDependencies().stream().filter((rel) -> rel.getActualFile().equals(tmpLoc)).forEach((rel) -> { + d.getRelatedDependencies().stream().filter(rel -> rel.getActualFile().equals(tmpLoc)).forEach(rel -> { rel.setFilePath(dependency.getFilePath()); rel.setDisplayFileName(dependency.getFileName()); }); diff --git a/src/test/resources/dataflow-functional-tests/FileUtils.java b/src/test/resources/dataflow-functional-tests/FileUtils.java index 9f492ab3f..74d1985d0 100644 --- a/src/test/resources/dataflow-functional-tests/FileUtils.java +++ b/src/test/resources/dataflow-functional-tests/FileUtils.java @@ -256,13 +256,13 @@ public static String byteCountToDisplaySize(long size) { String displaySize; if (size / ONE_GB > 0) { - displaySize = String.valueOf(size / ONE_GB) + " GB"; + displaySize = size / ONE_GB + " GB"; } else if (size / ONE_MB > 0) { - displaySize = String.valueOf(size / ONE_MB) + " MB"; + displaySize = size / ONE_MB + " MB"; } else if (size / ONE_KB > 0) { - displaySize = String.valueOf(size / ONE_KB) + " KB"; + displaySize = size / ONE_KB + " KB"; } else { - displaySize = String.valueOf(size) + " bytes"; + displaySize = size + " bytes"; } return displaySize; } @@ -376,7 +376,7 @@ public static Collection listFiles( } //Find files - Collection files = new java.util.LinkedList(); + Collection files = new java.util.LinkedList<>(); innerListFiles(files, directory, FileFilterUtils.or(effFileFilter, effDirFilter)); return files; @@ -615,7 +615,7 @@ public static File[] toFiles(URL[] urls) { for (int i = 0; i < urls.length; i++) { URL url = urls[i]; if (url != null) { - if (url.getProtocol().equals("file") == false) { + if ("file".equals(url.getProtocol()) == false) { throw new IllegalArgumentException( "URL could not be converted to a File: " + url); } @@ -1046,7 +1046,7 @@ public static void copyDirectory(File srcDir, File destDir, if (canonicalDestDir.startsWith(srcDir.getCanonicalPath())) { File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (srcFiles != null && srcFiles.length > 0) { - exclusionList = new ArrayList(srcFiles.length); + exclusionList = new ArrayList<>(srcFiles.length); for (File srcFile : srcFiles) { File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); @@ -2206,10 +2206,6 @@ public static boolean isSymlink(File file) throws IOException { fileInCanonicalDir = new File(canonicalDir, file.getName()); } - if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) { - return false; - } else { - return true; - } + return !(fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())); } } diff --git a/src/test/resources/dataflow-functional-tests/JavaTypeGoat.java b/src/test/resources/dataflow-functional-tests/JavaTypeGoat.java index 8912f5757..6dfcce9f3 100644 --- a/src/test/resources/dataflow-functional-tests/JavaTypeGoat.java +++ b/src/test/resources/dataflow-functional-tests/JavaTypeGoat.java @@ -23,10 +23,10 @@ @AnnotationWithSourceRetention public abstract class JavaTypeGoat & C> { - public static final PT parameterizedField = new PT() { + public static final PT parameterizedField = new PT<>() { }; - public static abstract class InheritedJavaTypeGoat & C> extends JavaTypeGoat { + public abstract static class InheritedJavaTypeGoat & C> extends JavaTypeGoat { public InheritedJavaTypeGoat() { super(); } @@ -49,7 +49,7 @@ public enum EnumTypeB { public abstract class ExtendsJavaTypeGoat extends JavaTypeGoat { } - public static abstract class Extension> {} + public abstract static class Extension> {} public static class TypeA {} public static class TypeB {} diff --git a/src/test/resources/dataflow-functional-tests/JobUtils.java b/src/test/resources/dataflow-functional-tests/JobUtils.java index aca1f2ad1..e07ebf4a3 100644 --- a/src/test/resources/dataflow-functional-tests/JobUtils.java +++ b/src/test/resources/dataflow-functional-tests/JobUtils.java @@ -63,7 +63,7 @@ private static void zip(File fileToZip, String fileName, ZipOutputStream zipOut, for (File childFile : children) { String childFileName = childFile.getName(); // TODO improve ? - if (childFileName.equals("target") || childFileName.equals("build")) { + if ("target".equals(childFileName) || "build".equals(childFileName)) { continue; } if (level != 0) { diff --git a/src/test/resources/dataflow-functional-tests/MatchPatternsFileFilter.java b/src/test/resources/dataflow-functional-tests/MatchPatternsFileFilter.java index d752f394f..215bbcc95 100644 --- a/src/test/resources/dataflow-functional-tests/MatchPatternsFileFilter.java +++ b/src/test/resources/dataflow-functional-tests/MatchPatternsFileFilter.java @@ -129,8 +129,9 @@ String relativePath(File file) throws IOException { } static List processPatterns(List patterns) { - if (patterns == null) + if (patterns == null) { return null; + } List processed = new ArrayList<>(); for (String pattern : patterns) { processed.add(processPattern(pattern)); diff --git a/src/test/resources/dataflow-functional-tests/SecurityUtils.java b/src/test/resources/dataflow-functional-tests/SecurityUtils.java index 086f409e8..9b49b7670 100644 --- a/src/test/resources/dataflow-functional-tests/SecurityUtils.java +++ b/src/test/resources/dataflow-functional-tests/SecurityUtils.java @@ -28,20 +28,24 @@ * and file path validation. */ public final class SecurityUtils { - private static Logger log = LoggerFactory.getLogger(SecurityUtils.class); - - private static Set SCHEMES = new HashSet() {{ - add("http"); - add("https"); - add("HTTP"); - add("HTTPS"); - }}; + private static final Logger log = LoggerFactory.getLogger(SecurityUtils.class); + + private static final Set SCHEMES; + static { + SCHEMES = new HashSet<>(); + SCHEMES.add("http"); + SCHEMES.add("https"); + SCHEMES.add("HTTP"); + SCHEMES.add("HTTPS"); + } - private static Set PORTS = new HashSet() {{ - add(443); - add(80); - add(3000); // we allow port 3000 for SAM local - }}; + private static final Set PORTS; + static { + PORTS = new HashSet<>(); + PORTS.add(443); + PORTS.add(80); + PORTS.add(3000); + } public static boolean isValidPort(String port) { if (port == null) { @@ -65,10 +69,7 @@ public static boolean isValidHost(String host, String apiId, String region) { return false; } if (host.endsWith(".amazonaws.com")) { - String defaultHost = new StringBuilder().append(apiId) - .append(".execute-api.") - .append(region) - .append(".amazonaws.com").toString(); + String defaultHost = apiId + ".execute-api." + region + ".amazonaws.com"; return host.equals(defaultHost); } else { return LambdaContainerHandler.getContainerConfig().getCustomDomainNames().contains(host); @@ -216,7 +217,7 @@ public static String getValidFilePath(final String inputPath, boolean isWrite) { throw new IllegalArgumentException("File path not allowed: " + encode(canonicalPath)); } - return (inputPath.startsWith("file://") ? "file://" + canonicalPath : canonicalPath); + return inputPath.startsWith("file://") ? "file://" + canonicalPath : canonicalPath; } catch (IOException e) { log.error("Invalid file path: {}", encode(testInputPath)); throw new IllegalArgumentException("Invalid file path", e); diff --git a/src/test/resources/dataflow-functional-tests/SimpleFileServer.java b/src/test/resources/dataflow-functional-tests/SimpleFileServer.java index 4fa96c2bf..c76e97dd8 100644 --- a/src/test/resources/dataflow-functional-tests/SimpleFileServer.java +++ b/src/test/resources/dataflow-functional-tests/SimpleFileServer.java @@ -71,7 +71,7 @@ public class SimpleFileServer extends AbstractTestServer { TcpConfig.register(); } - private static DefinitionsProvider DEFAULTS = new DefinitionsProvider() { + private static final DefinitionsProvider DEFAULTS = new DefinitionsProvider() { @Override public void applyDefinitions(Configuration config) { diff --git a/src/test/resources/dataflow-functional-tests/TermuxDocumentsProvider.java b/src/test/resources/dataflow-functional-tests/TermuxDocumentsProvider.java index b061425ac..4d5af8a31 100644 --- a/src/test/resources/dataflow-functional-tests/TermuxDocumentsProvider.java +++ b/src/test/resources/dataflow-functional-tests/TermuxDocumentsProvider.java @@ -179,8 +179,8 @@ public Cursor querySearchDocuments(String rootId, String query, String[] project final LinkedList pending = new LinkedList<>(); pending.add(parent); - final int MAX_SEARCH_RESULTS = 50; - while (!pending.isEmpty() && result.getCount() < MAX_SEARCH_RESULTS) { + final int maxSearchResults = 50; + while (!pending.isEmpty() && result.getCount() < maxSearchResults) { final File file = pending.removeFirst(); // Avoid directories outside the HOME directory linked with symlinks (to avoid e.g. search // through the whole SD card). @@ -224,7 +224,9 @@ private static String getDocIdForFile(File file) { */ private static File getFileForDocId(String docId) throws FileNotFoundException { final File f = new File(docId); - if (!f.exists()) throw new FileNotFoundException(f.getAbsolutePath() + " not found"); + if (!f.exists()) { + throw new FileNotFoundException(f.getAbsolutePath() + " not found"); + } return f; } @@ -237,7 +239,9 @@ private static String getMimeType(File file) { if (lastDot >= 0) { final String extension = name.substring(lastDot + 1).toLowerCase(); final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - if (mime != null) return mime; + if (mime != null) { + return mime; + } } return "application/octet-stream"; } @@ -260,15 +264,21 @@ private void includeFile(MatrixCursor result, String docId, File file) int flags = 0; if (file.isDirectory()) { - if (file.canWrite()) flags |= Document.FLAG_DIR_SUPPORTS_CREATE; + if (file.canWrite()) { + flags |= Document.FLAG_DIR_SUPPORTS_CREATE; + } } else if (file.canWrite()) { flags |= Document.FLAG_SUPPORTS_WRITE; } - if (file.getParentFile().canWrite()) flags |= Document.FLAG_SUPPORTS_DELETE; + if (file.getParentFile().canWrite()) { + flags |= Document.FLAG_SUPPORTS_DELETE; + } final String displayName = file.getName(); final String mimeType = getMimeType(file); - if (mimeType.startsWith("image/")) flags |= Document.FLAG_SUPPORTS_THUMBNAIL; + if (mimeType.startsWith("image/")) { + flags |= Document.FLAG_SUPPORTS_THUMBNAIL; + } final MatrixCursor.RowBuilder row = result.newRow(); row.add(Document.COLUMN_DOCUMENT_ID, docId); diff --git a/src/test/resources/dataflow-functional-tests/TestAssignmentToNull.java b/src/test/resources/dataflow-functional-tests/TestAssignmentToNull.java index ce6e384e3..5cce38dc3 100644 --- a/src/test/resources/dataflow-functional-tests/TestAssignmentToNull.java +++ b/src/test/resources/dataflow-functional-tests/TestAssignmentToNull.java @@ -26,7 +26,7 @@ void test2(File srcDir, File destDir, FileFilter filter) { if (canonicalDestDir.startsWith(srcDir.getCanonicalPath())) { File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (srcFiles != null && srcFiles.length > 0) { - exclusionList = new ArrayList(srcFiles.length); + exclusionList = new ArrayList<>(srcFiles.length); for (File srcFile : srcFiles) { File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath());