From 40c408eb63ea5a2a4056e371ff9ab508ddaf31f4 Mon Sep 17 00:00:00 2001 From: Ilya Rodionov Date: Mon, 19 Jun 2023 21:38:53 +0300 Subject: [PATCH] Code cleanup --- .../antlr4test/AssertErrorsErrorListener.java | 6 +- .../antlr4test/AssertErrorsException.java | 3 - .../com/khubla/antlr/antlr4test/FileUtil.java | 40 ++++------- .../antlr/antlr4test/GrammarInitializer.java | 2 +- .../antlr/antlr4test/GrammarTestMojo.java | 20 +++--- .../com/khubla/antlr/antlr4test/Scenario.java | 10 +-- .../antlr/antlr4test/ScenarioExecutor.java | 69 ++++++++----------- .../AssertErrorsErrorListenerTest.java | 6 +- .../antlr/antlr4test/TestGrammarTestMojo.java | 20 +++--- 9 files changed, 71 insertions(+), 105 deletions(-) diff --git a/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsErrorListener.java b/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsErrorListener.java index 999fe83..686ba7d 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsErrorListener.java +++ b/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsErrorListener.java @@ -43,8 +43,8 @@ public class AssertErrorsErrorListener extends BaseErrorListener { protected static final String LITERAL_BACKSLASH_N_PLACEHOLDER = "literal-backslash-n"; protected static final String LITERAL_BACKSLASH_N = "\\\\n"; protected List errorMessages = new ArrayList<>(); - private Scenario scenario = null; - private Log log = null; + private final Scenario scenario; + private final Log log; public AssertErrorsErrorListener(Scenario scenario, Log log) { this.scenario = scenario; @@ -53,7 +53,7 @@ public AssertErrorsErrorListener(Scenario scenario, Log log) { public void assertErrors(File errorMessagesFile, String encoding) throws AssertErrorsException { if (!errorMessages.isEmpty()) { - List expectedErrorMessages = null; + List expectedErrorMessages; String errorMessageFileName = null; if (errorMessagesFile != null) { errorMessageFileName = errorMessagesFile.getName(); diff --git a/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsException.java b/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsException.java index b6a988f..9257f7b 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsException.java +++ b/src/main/java/com/khubla/antlr/antlr4test/AssertErrorsException.java @@ -28,9 +28,6 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT package com.khubla.antlr.antlr4test; public class AssertErrorsException extends Exception { - /** - * - */ private static final long serialVersionUID = 1L; public AssertErrorsException(String message) { diff --git a/src/main/java/com/khubla/antlr/antlr4test/FileUtil.java b/src/main/java/com/khubla/antlr/antlr4test/FileUtil.java index 6230859..17efd98 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/FileUtil.java +++ b/src/main/java/com/khubla/antlr/antlr4test/FileUtil.java @@ -39,9 +39,8 @@ public class FileUtil { * * @param dir Directory * @return list of files - * @throws Exception from getAllFiles */ - public static List getAllFiles(String dir) throws Exception { + public static List getAllFiles(String dir) { return getAllFiles(dir, null); } @@ -53,17 +52,20 @@ public static List getAllFiles(String dir) throws Exception { * @return list of files */ public static List getAllFiles(String dir, String extension) { - final List ret = new ArrayList(); + final List ret = new ArrayList<>(); final File file = new File(dir); if (file.exists()) { final String[] list = file.list(); if (null != list) { - for (int i = 0; i < list.length; i++) { - final String fileName = dir + "/" + list[i]; + for (String s : list) { + final String fileName = dir + "/" + s; final File f2 = new File(fileName); if (!f2.isHidden()) { if (f2.isDirectory()) { - ret.addAll(getAllFiles(fileName, extension)); + List f2Files = getAllFiles(fileName, extension); + if (null != f2Files) { + ret.addAll(f2Files); + } } else { if (null != extension) { if (f2.getName().endsWith(extension)) { @@ -83,16 +85,10 @@ public static List getAllFiles(String dir, String extension) { } public static List getNonEmptyLines(File file, String encoding) throws IOException { - final List nonEmptyLines = new ArrayList(); - BufferedReader br = null; - InputStreamReader isr = null; - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - try { - isr = new InputStreamReader(fis, encoding); - try { - br = new BufferedReader(isr); + final List nonEmptyLines = new ArrayList<>(); + try (FileInputStream fis = new FileInputStream(file)) { + try (InputStreamReader isr = new InputStreamReader(fis, encoding)) { + try (BufferedReader br = new BufferedReader(isr)) { String line = br.readLine(); while (line != null) { if (!"".equals(line.trim())) { @@ -101,19 +97,7 @@ public static List getNonEmptyLines(File file, String encoding) throws I line = br.readLine(); } return nonEmptyLines; - } finally { - if (br != null) { - br.close(); - } } - } finally { - if (isr != null) { - isr.close(); - } - } - } finally { - if (fis != null) { - fis.close(); } } } diff --git a/src/main/java/com/khubla/antlr/antlr4test/GrammarInitializer.java b/src/main/java/com/khubla/antlr/antlr4test/GrammarInitializer.java index cdcea05..76ec845 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/GrammarInitializer.java +++ b/src/main/java/com/khubla/antlr/antlr4test/GrammarInitializer.java @@ -30,5 +30,5 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT import org.antlr.v4.runtime.*; public interface GrammarInitializer { - public void initialize(Lexer lexer, Parser parser); + void initialize(Lexer lexer, Parser parser); } diff --git a/src/main/java/com/khubla/antlr/antlr4test/GrammarTestMojo.java b/src/main/java/com/khubla/antlr/antlr4test/GrammarTestMojo.java index 5ccdbdc..1113a27 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/GrammarTestMojo.java +++ b/src/main/java/com/khubla/antlr/antlr4test/GrammarTestMojo.java @@ -28,7 +28,6 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT package com.khubla.antlr.antlr4test; import java.io.*; -import java.net.*; import java.util.*; import org.apache.maven.plugin.*; @@ -39,7 +38,7 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT /** * @author Tom Everett */ -@Mojo(name = "test", defaultPhase = LifecyclePhase.TEST, requiresProject = true, threadSafe = false) +@Mojo(name = "test", defaultPhase = LifecyclePhase.TEST) public class GrammarTestMojo extends AbstractMojo { /** * errors file @@ -98,7 +97,7 @@ public class GrammarTestMojo extends AbstractMojo { * testFileExtension */ @Parameter - private String testFileExtension = null; + private String testFileExtension; /** * basedir dir */ @@ -113,12 +112,12 @@ public class GrammarTestMojo extends AbstractMojo { * Full qualified class name to initialize grammar (Lexer and/or Parser) before test starts */ @Parameter - private String grammarInitializer = null; + private String grammarInitializer; /** * List of test scenarios to be executed. */ @Parameter - private List scenarios = null; + private List scenarios; /** * read outputDirectory from pom project.build.outputDirectory */ @@ -132,20 +131,18 @@ public class GrammarTestMojo extends AbstractMojo { /** * ctor - * - * @throws MalformedURLException exception for malformed url *eye roll* */ - public GrammarTestMojo() throws MalformedURLException { + public GrammarTestMojo() { } @Override - public void execute() throws MojoExecutionException, MojoFailureException { + public void execute() throws MojoExecutionException { try { /* * No scenario configuration has been given. Creates a default one. */ if (scenarios == null) { - scenarios = new ArrayList(); + scenarios = new ArrayList<>(); } if ((grammarName != null) && !"".equals(grammarName)) { // @@ -357,8 +354,7 @@ private void testScenarios() throws Exception { } if (scenario.isEnabled()) { ScenarioExecutor executor = new ScenarioExecutor(this, scenario, mojoLogger); - executor.testGrammars(); - executor = null; + executor.testExamples(); } else { mojoLogger.warn("Scenario " + scenario.getScenarioName() + " is disabled. Skipping."); } diff --git a/src/main/java/com/khubla/antlr/antlr4test/Scenario.java b/src/main/java/com/khubla/antlr/antlr4test/Scenario.java index 0e0e568..447283c 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/Scenario.java +++ b/src/main/java/com/khubla/antlr/antlr4test/Scenario.java @@ -101,16 +101,12 @@ public class Scenario { * Full qualified class name to initialize grammar (Lexer and/or Parser) before test starts */ @Parameter - private String grammarInitializer = null; + private String grammarInitializer; public File getBaseDir() { return baseDir; } - public boolean getBinary() { - return binary; - } - public CaseInsensitiveType getCaseInsensitiveType() { return caseInsensitiveType; } @@ -156,6 +152,10 @@ public String getTestFileExtension() { return testFileExtension; } + public boolean isBinary() { + return binary; + } + public boolean isEnabled() { return enabled; } diff --git a/src/main/java/com/khubla/antlr/antlr4test/ScenarioExecutor.java b/src/main/java/com/khubla/antlr/antlr4test/ScenarioExecutor.java index ccbb5fe..20331cf 100644 --- a/src/main/java/com/khubla/antlr/antlr4test/ScenarioExecutor.java +++ b/src/main/java/com/khubla/antlr/antlr4test/ScenarioExecutor.java @@ -43,9 +43,9 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT import com.khubla.antlr.antlr4test.filestream.*; public class ScenarioExecutor { - private Scenario scenario = null; - private Log log = null; - private GrammarTestMojo mojo = null; + private final Scenario scenario; + private final Log log; + private final GrammarTestMojo mojo; private final HashMap classLoaderMap = new HashMap<>(); public ScenarioExecutor(GrammarTestMojo mojo, Scenario scenario, Log log) { @@ -54,7 +54,7 @@ public ScenarioExecutor(GrammarTestMojo mojo, Scenario scenario, Log log) { this.log = log; } - private ClassLoader getClassLoader(String path) throws MalformedURLException, ClassNotFoundException { + private ClassLoader getClassLoader(String path) throws MalformedURLException { /* * create a ClassLoader child of Thread.currentThread().getContextClassLoader(). */ @@ -64,7 +64,7 @@ private ClassLoader getClassLoader(String path) throws MalformedURLException, Cl /** * build a ClassLoader that can find the files we need */ - private ClassLoader getClassLoader(String path, ClassLoader parent) throws MalformedURLException, ClassNotFoundException { + private ClassLoader getClassLoader(String path, ClassLoader parent) throws MalformedURLException { final URL antlrGeneratedURL = new File(path).toURI().toURL(); /* * check if ClassLoader for this URL was already created. @@ -80,9 +80,9 @@ private ClassLoader getClassLoader(String path, ClassLoader parent) throws Malfo } /** - * test a single grammar + * test a single example */ - private void testGrammar(Scenario scenario, File grammarFile) throws Exception { + private void testExample(Scenario scenario, File exampleFile) throws Exception { /* * figure out class names */ @@ -119,20 +119,20 @@ private void testGrammar(Scenario scenario, File grammarFile) throws Exception { */ final Constructor lexerConstructor = lexerClass.getConstructor(CharStream.class); final Constructor parserConstructor = parserClass.getConstructor(TokenStream.class); - log.info("Parsing :" + grammarFile.getAbsolutePath()); + log.info("Parsing :" + exampleFile.getAbsolutePath()); CharStream antlrCharStream; /* * case */ if (scenario.getCaseInsensitiveType() == CaseInsensitiveType.None) { - antlrCharStream = CharStreams.fromPath(grammarFile.toPath(), Charset.forName(scenario.getFileEncoding())); + antlrCharStream = CharStreams.fromPath(exampleFile.toPath(), Charset.forName(scenario.getFileEncoding())); } else { - antlrCharStream = new AntlrCaseInsensitiveFileStream(grammarFile.getAbsolutePath(), scenario.getFileEncoding(), scenario.getCaseInsensitiveType()); + antlrCharStream = new AntlrCaseInsensitiveFileStream(exampleFile.getAbsolutePath(), scenario.getFileEncoding(), scenario.getCaseInsensitiveType()); } /* * binary */ - if (true == scenario.getBinary()) { + if (scenario.isBinary()) { antlrCharStream = new BinaryCharStream(antlrCharStream); } /* @@ -171,7 +171,7 @@ private void testGrammar(Scenario scenario, File grammarFile) throws Exception { } final Method method = parserClass.getMethod(scenario.getEntryPoint()); ParserRuleContext parserRuleContext = (ParserRuleContext) method.invoke(parser); - assertErrorsErrorListener.assertErrors(new File(grammarFile.getAbsolutePath() + GrammarTestMojo.ERRORS_SUFFIX), scenario.getFileEncoding()); + assertErrorsErrorListener.assertErrors(new File(exampleFile.getAbsolutePath() + GrammarTestMojo.ERRORS_SUFFIX), scenario.getFileEncoding()); /* * show the tree */ @@ -183,35 +183,24 @@ private void testGrammar(Scenario scenario, File grammarFile) throws Exception { /* * check syntax */ - final File treeFile = new File(grammarFile.getAbsolutePath() + GrammarTestMojo.TREE_SUFFIX); + final File treeFile = new File(exampleFile.getAbsolutePath() + GrammarTestMojo.TREE_SUFFIX); if (treeFile.exists()) { final String lispTree = Trees.toStringTree(parserRuleContext, parser); - if (null != lispTree) { - final String treeFileData = FileUtils.fileRead(treeFile, scenario.getFileEncoding()); - if (null != treeFileData) { - if (0 != treeFileData.compareTo(lispTree)) { - final StringBuilder sb = new StringBuilder("Parse tree does not match '" + treeFile.getName() + "'. Differences: "); - for (final DiffMatchPatch.Diff diff : new DiffMatchPatch().diffMain(treeFileData, lispTree)) { - sb.append(diff.toString()); - sb.append(", "); - } - throw new Exception(sb.toString()); - } else { - log.info("Parse tree for '" + grammarFile.getName() + "' matches '" + treeFile.getName() + "'"); - } + final String treeFileData = FileUtils.fileRead(treeFile, scenario.getFileEncoding()); + if (0 != treeFileData.compareTo(lispTree)) { + final StringBuilder sb = new StringBuilder("Parse tree does not match '" + treeFile.getName() + "'. Differences: "); + for (final DiffMatchPatch.Diff diff : new DiffMatchPatch().diffMain(treeFileData, lispTree)) { + sb.append(diff.toString()); + sb.append(", "); } + throw new Exception(sb.toString()); + } else { + log.info("Parse tree for '" + exampleFile.getName() + "' matches '" + treeFile.getName() + "'"); } } - /* - * yup - */ - parser = null; - lexer = null; - parserRuleContext = null; - antlrCharStream = null; } - public void testGrammars() throws Exception { + public void testExamples() throws Exception { /* * iterate examples */ @@ -226,7 +215,7 @@ public void testGrammars() throws Exception { * file extension */ if ((scenario.getTestFileExtension() == null) || ((scenario.getTestFileExtension() != null) && (file.getName().endsWith(scenario.getTestFileExtension())))) { - testGrammar(scenario, file); + testExample(scenario, file); } } /* @@ -244,18 +233,18 @@ public void testGrammars() throws Exception { * @return hex bytes */ private String tokToHex(Token token) { - String ret = ""; + StringBuilder ret = new StringBuilder(); token.getInputStream().seek(0); boolean first = true; for (int i = token.getStartIndex(); i < (token.getStopIndex() + 1); i++) { - if (true == first) { + if (first) { first = false; } else { - ret += ","; + ret.append(","); } final int t = token.getInputStream().LA(i + 1); - ret += "0x" + String.format("%02X", (byte) t); + ret.append("0x").append(String.format("%02X", (byte) t)); } - return ret; + return ret.toString(); } } diff --git a/src/test/java/test/com/khubla/antlr/antlr4test/AssertErrorsErrorListenerTest.java b/src/test/java/test/com/khubla/antlr/antlr4test/AssertErrorsErrorListenerTest.java index a527388..3adfbb7 100644 --- a/src/test/java/test/com/khubla/antlr/antlr4test/AssertErrorsErrorListenerTest.java +++ b/src/test/java/test/com/khubla/antlr/antlr4test/AssertErrorsErrorListenerTest.java @@ -42,9 +42,9 @@ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * @author mario.schroeder */ public class AssertErrorsErrorListenerTest { - private Scenario scenario = null; - private Log log = null; - private AssertErrorsErrorListener classUnderTest = null; + private Scenario scenario; + private Log log; + private AssertErrorsErrorListener classUnderTest; @Before public void setUp() { diff --git a/src/test/java/test/com/khubla/antlr/antlr4test/TestGrammarTestMojo.java b/src/test/java/test/com/khubla/antlr/antlr4test/TestGrammarTestMojo.java index 242220b..e4d5223 100644 --- a/src/test/java/test/com/khubla/antlr/antlr4test/TestGrammarTestMojo.java +++ b/src/test/java/test/com/khubla/antlr/antlr4test/TestGrammarTestMojo.java @@ -84,7 +84,7 @@ protected void tearDown() throws Exception { /** * Basic test of binary */ - public void testBinary() throws Exception { + public void testBinary() { try { System.out.println("Testing '" + BINARY_POMFILE + "'"); final File pom = getTestFile(BINARY_POMFILE); @@ -128,21 +128,21 @@ private void testCaseInsensitiveExecution(String caseInsensitivePomXml) { /** * Basic test of case insensitive execution */ - public void testCaseInsensitiveLowerExecution() throws Exception { + public void testCaseInsensitiveLowerExecution() { testCaseInsensitiveExecution(CASEINSENSITIVE_lower_POMFILE); } /** * Basic test of case insensitive execution */ - public void testCaseInsensitiveUpperExecution() throws Exception { + public void testCaseInsensitiveUpperExecution() { testCaseInsensitiveExecution(CASEINSENSITIVE_UPPER_POMFILE); } /** * Basic test of execution */ - public void testGenericExecution() throws Exception { + public void testGenericExecution() { try { /* * pom @@ -168,7 +168,7 @@ public void testGenericExecution() throws Exception { /** * Basic test of instantiation */ - public void testGrammarInitializer() throws Exception { + public void testGrammarInitializer() { try { System.out.println("Testing '" + GRAMMAR_INIT_POMFILE + "'"); final File pom = getTestFile(GRAMMAR_INIT_POMFILE); @@ -191,7 +191,7 @@ public void testGrammarInitializer() throws Exception { /** * Basic test of instantiation */ - public void testInstatiation() throws Exception { + public void testInstatiation() { try { final File pom = getTestFile(GENERIC_POMFILE); assertNotNull(pom); @@ -199,9 +199,9 @@ public void testInstatiation() throws Exception { final GrammarTestMojo grammarTestMojo = (GrammarTestMojo) lookupMojo(TEST_GOAL, pom); assertNotNull(grammarTestMojo); assertTrue(grammarTestMojo.isVerbose()); - assertTrue(grammarTestMojo.getExampleFiles().compareTo("src/test/resources/examples") == 0); - assertTrue(grammarTestMojo.getEntryPoint().compareTo("equation") == 0); - assertTrue(grammarTestMojo.getTestFileExtension().compareTo(".txt") == 0); + assertEquals(0, grammarTestMojo.getExampleFiles().compareTo("src/test/resources/examples")); + assertEquals(0, grammarTestMojo.getEntryPoint().compareTo("equation")); + assertEquals(0, grammarTestMojo.getTestFileExtension().compareTo(".txt")); } catch (final Exception e) { e.printStackTrace(); Assert.fail("Unexpected exception " + e); @@ -211,7 +211,7 @@ public void testInstatiation() throws Exception { /** * Test scenario based configuration */ - public void testScenarioConfiguration() throws Exception { + public void testScenarioConfiguration() { try { /* * pom