diff --git a/pom.xml b/pom.xml index f2f9655..9d2d6ab 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 - mojo-parent org.codehaus.mojo + mojo-parent 76 @@ -48,17 +46,11 @@ under the License. ${mavenVersion} - - ${maven-site-plugin.version} - 3.2.5 - false - - scm:git:https://github.com/mojohaus/javacc-maven-plugin.git scm:git:ssh://git@github.com/mojohaus/javacc-maven-plugin.git - https://github.com/mojohaus/javacc-maven-plugin HEAD + https://github.com/mojohaus/javacc-maven-plugin @@ -71,6 +63,13 @@ under the License. https://github.com/mojohaus/javacc-maven-plugin/actions + + 11 + ${maven-site-plugin.version} + 3.2.5 + false + + org.apache.maven @@ -128,8 +127,8 @@ under the License. 3.2.0 - plexus-container-default org.codehaus.plexus + plexus-container-default @@ -139,8 +138,8 @@ under the License. 1.12.0 - plexus-container-default org.codehaus.plexus + plexus-container-default @@ -150,8 +149,8 @@ under the License. 1.11.1 - plexus-container-default org.codehaus.plexus + plexus-container-default @@ -189,4 +188,21 @@ under the License. + + + java11+ + + [11,) + + + + + com.diffplug.spotless + spotless-maven-plugin + + + + + + diff --git a/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java b/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java index 8e54bc9..8f65e03 100644 --- a/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -37,13 +37,11 @@ /** * Provides common services for all mojos that compile JavaCC grammar files. - * + * * @author jruiz@exist.com * @author jesse jesse.mcconnell@gmail.com */ -public abstract class AbstractJavaCCMojo - extends AbstractMojo -{ +public abstract class AbstractJavaCCMojo extends AbstractMojo { /** * The current Maven project. @@ -130,7 +128,7 @@ public abstract class AbstractJavaCCMojo /** * Setting it to false causes errors due to parse errors to be reported in somewhat less detail. * Default value is true. - * + * */ @Parameter(property = "javacc.errorReporting") private Boolean errorReporting; @@ -139,7 +137,7 @@ public abstract class AbstractJavaCCMojo * When set to true, the generated parser uses an input stream object that processes Java Unicode * escapes (\uxxxx) before sending characters to the token manager. Default * value is false. - * + * */ @Parameter(property = "javacc.javaUnicodeEscape") private Boolean javaUnicodeEscape; @@ -209,7 +207,7 @@ public abstract class AbstractJavaCCMojo /** * When set to true, the generated token manager will include a field called parser * that references the instantiating parser instance. Default value is false. - * + * */ @Parameter(property = "javacc.tokenManagerUsesParser") private Boolean tokenManagerUsesParser; @@ -259,7 +257,7 @@ public abstract class AbstractJavaCCMojo /** * A flag whether to keep line and column information along with a token. Default value is true. - * + * */ @Parameter(property = "javacc.keepLineColumn") private Boolean keepLineColumn; @@ -275,7 +273,7 @@ public abstract class AbstractJavaCCMojo /** * The file encoding to use for reading the grammar files. - * + * * @since 2.6 */ @Parameter(property = "javacc.grammarEncoding", defaultValue = "${project.build.sourceEncoding}") @@ -283,47 +281,44 @@ public abstract class AbstractJavaCCMojo /** * Gets the file encoding of the grammar files. - * + * * @return The file encoding of the grammar files or null if the user did not specify this mojo * parameter. */ - protected String getGrammarEncoding() - { + protected String getGrammarEncoding() { return this.grammarEncoding; } /** * Gets the Java version for which to generate source code. - * + * * @return The Java version for which to generate source code, will be null if the user did not specify * this mojo parameter. */ - protected String getJdkVersion() - { + protected String getJdkVersion() { return this.jdkVersion; } /** * Gets the flag whether to generate static parser. - * + * * @return The flag whether to generate static parser, will be null if the user did not specify this * mojo parameter. */ - protected Boolean getIsStatic() - { + protected Boolean getIsStatic() { return this.isStatic; } /** * Gets the absolute path to the directory where the grammar files are located. - * + * * @return The absolute path to the directory where the grammar files are located, never null. */ protected abstract File getSourceDirectory(); /** * Gets a set of Ant-like inclusion patterns used to select files from the source directory for processing. - * + * * @return A set of Ant-like inclusion patterns used to select files from the source directory for processing, can * be null if all files should be included. */ @@ -331,7 +326,7 @@ protected Boolean getIsStatic() /** * Gets a set of Ant-like exclusion patterns used to unselect files from the source directory for processing. - * + * * @return A set of Ant-like inclusion patterns used to unselect files from the source directory for processing, can * be null if no files should be excluded. */ @@ -339,7 +334,7 @@ protected Boolean getIsStatic() /** * Gets the absolute path to the directory where the generated Java files for the parser will be stored. - * + * * @return The absolute path to the directory where the generated Java files for the parser will be stored, never * null. */ @@ -348,7 +343,7 @@ protected Boolean getIsStatic() /** * Gets the granularity in milliseconds of the last modification date for testing whether a source needs * recompilation. - * + * * @return The granularity in milliseconds of the last modification date for testiintng whether a source needs * recompilation. */ @@ -356,59 +351,49 @@ protected Boolean getIsStatic() /** * Gets all the output directories to register with the project for compilation. - * + * * @return The compile source roots to register with the project, never null. */ protected abstract File[] getCompileSourceRoots(); /** * Gets the package into which the generated parser files should be stored. - * + * * @return The package into which the generated parser files should be stored, can be null to use the * package declaration from the grammar file. */ // TODO: Once the parameter "packageName" from the javacc mojo has been deleted, remove this method, too. - protected String getParserPackage() - { + protected String getParserPackage() { return null; } /** * Execute the tool. - * + * * @throws MojoExecutionException If the invocation of the tool failed. * @throws MojoFailureException If the tool reported a non-zero exit code. */ - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { GrammarInfo[] grammarInfos = scanForGrammars(); - if ( grammarInfos == null ) - { - getLog().info( "Skipping non-existing source directory: " + getSourceDirectory() ); + if (grammarInfos == null) { + getLog().info("Skipping non-existing source directory: " + getSourceDirectory()); return; - } - else if (grammarInfos.length == 0) - { - getLog().info( "Skipping - all parsers are up to date" ); - } - else - { + } else if (grammarInfos.length == 0) { + getLog().info("Skipping - all parsers are up to date"); + } else { determineNonGeneratedSourceRoots(); - if ( StringUtils.isEmpty( grammarEncoding ) ) - { - getLog().warn( - "File encoding for grammars has not been configured" - + ", using platform default encoding, i.e. build is platform dependent!" ); + if (StringUtils.isEmpty(grammarEncoding)) { + getLog().warn("File encoding for grammars has not been configured" + + ", using platform default encoding, i.e. build is platform dependent!"); } for (GrammarInfo grammarInfo : grammarInfos) { processGrammar(grammarInfo); } - getLog().info( "Processed " + grammarInfos.length + " grammar" + ( grammarInfos.length != 1 ? "s" : "" ) ); + getLog().info("Processed " + grammarInfos.length + " grammar" + (grammarInfos.length != 1 ? "s" : "")); } for (File compileSourceRoot : getCompileSourceRoots()) { @@ -418,77 +403,65 @@ else if (grammarInfos.length == 0) /** * Passes the specified grammar file through the tool. - * + * * @param grammarInfo The grammar info describing the grammar file to process, must not be null. * @throws MojoExecutionException If the invocation of the tool failed. * @throws MojoFailureException If the tool reported a non-zero exit code. */ - protected abstract void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException; + protected abstract void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException; /** * Scans the configured source directory for grammar files which need processing. - * + * * @return An array of grammar infos describing the found grammar files or null if the source * directory does not exist. * @throws MojoExecutionException If the source directory could not be scanned. */ - private GrammarInfo[] scanForGrammars() - throws MojoExecutionException - { - if ( !getSourceDirectory().isDirectory() ) - { + private GrammarInfo[] scanForGrammars() throws MojoExecutionException { + if (!getSourceDirectory().isDirectory()) { return null; } GrammarInfo[] grammarInfos; - getLog().debug( "Scanning for grammars: " + getSourceDirectory() ); - try - { + getLog().debug("Scanning for grammars: " + getSourceDirectory()); + try { GrammarDirectoryScanner scanner = new GrammarDirectoryScanner(); - scanner.setSourceDirectory( getSourceDirectory() ); - scanner.setIncludes( getIncludes() ); - scanner.setExcludes( getExcludes() ); - scanner.setOutputDirectory( getOutputDirectory() ); - scanner.setParserPackage( getParserPackage() ); - scanner.setStaleMillis( getStaleMillis() ); + scanner.setSourceDirectory(getSourceDirectory()); + scanner.setIncludes(getIncludes()); + scanner.setExcludes(getExcludes()); + scanner.setOutputDirectory(getOutputDirectory()); + scanner.setParserPackage(getParserPackage()); + scanner.setStaleMillis(getStaleMillis()); scanner.scan(); grammarInfos = scanner.getIncludedGrammars(); + } catch (Exception e) { + throw new MojoExecutionException("Failed to scan for grammars: " + getSourceDirectory(), e); } - catch ( Exception e ) - { - throw new MojoExecutionException( "Failed to scan for grammars: " + getSourceDirectory(), e ); - } - getLog().debug( "Found grammars: " + Arrays.asList( grammarInfos ) ); + getLog().debug("Found grammars: " + Arrays.asList(grammarInfos)); return grammarInfos; } /** * Gets a temporary directory within the project's build directory. - * + * * @return The path to the temporary directory, never null. */ - protected File getTempDirectory() - { - return new File( this.project.getBuild().getDirectory(), "javacc-" + System.currentTimeMillis() ); + protected File getTempDirectory() { + return new File(this.project.getBuild().getDirectory(), "javacc-" + System.currentTimeMillis()); } /** * Deletes the specified temporary directory. - * + * * @param tempDirectory The directory to delete, must not be null. */ - protected void deleteTempDirectory( File tempDirectory ) - { - try - { - FileUtils.deleteDirectory( tempDirectory ); - } - catch ( IOException e ) - { - getLog().warn( "Failed to delete temporary directory: " + tempDirectory, e ); + protected void deleteTempDirectory(File tempDirectory) { + try { + FileUtils.deleteDirectory(tempDirectory); + } catch (IOException e) { + getLog().warn("Failed to delete temporary directory: " + tempDirectory, e); } } @@ -497,7 +470,7 @@ protected void deleteTempDirectory( File tempDirectory ) * only copied to the compile source root if it doesn't already exist in another compile source root. This prevents * duplicate class errors during compilation in case the user provided customized files in * src/main/java or similar. - * + * * @param packageName The name of the destination package for the output files, must not be null. * @param sourceRoot The (absolute) path to the compile source root into which the output files should eventually be * copied, must not be null. @@ -508,12 +481,10 @@ protected void deleteTempDirectory( File tempDirectory ) * leading "!" may be used to negate the pattern. * @throws MojoExecutionException If the output files could not be copied. */ - protected void copyGrammarOutput( File sourceRoot, String packageName, File tempDirectory, String updatePattern ) - throws MojoExecutionException - { - try - { - List tempFiles = FileUtils.getFiles( tempDirectory, "*.java", null ); + protected void copyGrammarOutput(File sourceRoot, String packageName, File tempDirectory, String updatePattern) + throws MojoExecutionException { + try { + List tempFiles = FileUtils.getFiles(tempDirectory, "*.java", null); for (File tempFile : tempFiles) { String outputPath = ""; if (packageName.length() > 0) { @@ -538,17 +509,17 @@ protected void copyGrammarOutput( File sourceRoot, String packageName, File temp try { FileUtils.copyFile(tempFile, outputFile); } catch (IOException e) { - throw new MojoExecutionException("Failed to copy generated source file to output directory:" - + tempFile + " -> " + outputFile, e); + throw new MojoExecutionException( + "Failed to copy generated source file to output directory:" + tempFile + " -> " + + outputFile, + e); } } else { getLog().debug("Skipping customized file: " + outputPath); } } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Failed to copy generated source files", e ); + } catch (IOException e) { + throw new MojoExecutionException("Failed to copy generated source files", e); } } @@ -556,17 +527,13 @@ protected void copyGrammarOutput( File sourceRoot, String packageName, File temp * Determines those compile source roots of the project that do not reside below the project's build directories. * These compile source roots are assumed to contain hand-crafted sources that must not be overwritten with * generated files. In most cases, this is simply "${project.build.sourceDirectory}". - * + * * @throws MojoExecutionException If the compile source rotos could not be determined. */ - private void determineNonGeneratedSourceRoots() - throws MojoExecutionException - { + private void determineNonGeneratedSourceRoots() throws MojoExecutionException { this.nonGeneratedSourceRoots = new LinkedHashSet<>(); - try - { - String targetPrefix = - new File( this.project.getBuild().getDirectory() ).getCanonicalPath() + File.separator; + try { + String targetPrefix = new File(this.project.getBuild().getDirectory()).getCanonicalPath() + File.separator; List sourceRoots = this.project.getCompileSourceRoots(); for (String root : sourceRoots) { File sourceRoot = new File(root); @@ -581,22 +548,19 @@ private void determineNonGeneratedSourceRoots() getLog().debug("Generated compile source root: " + sourceRoot); } } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Failed to determine non-generated source roots", e ); + } catch (IOException e) { + throw new MojoExecutionException("Failed to determine non-generated source roots", e); } } /** * Determines whether the specified source file is already present in any of the compile source roots registered * with the current Maven project. - * + * * @param filename The source filename to check, relative to a source root, must not be null. * @return The (absolute) path to the existing source file if any, null otherwise. */ - private File findSourceFile( String filename ) - { + private File findSourceFile(String filename) { return this.nonGeneratedSourceRoots.stream() .map(sourceRoot -> new File(sourceRoot, filename)) .filter(File::exists) @@ -606,27 +570,24 @@ private File findSourceFile( String filename ) /** * Determines whether the specified directory denotes a compile source root of the current project. - * + * * @param directory The directory to check, must not be null. * @return true if the specified directory is a compile source root of the project, false * otherwise. */ - protected boolean isSourceRoot( File directory ) - { - return this.nonGeneratedSourceRoots.contains( directory ); + protected boolean isSourceRoot(File directory) { + return this.nonGeneratedSourceRoots.contains(directory); } /** * Registers the specified directory as a compile source root for the current project. - * + * * @param directory The absolute path to the source root, must not be null. */ - private void addSourceRoot( File directory ) - { - if ( this.project != null ) - { - getLog().debug( "Adding compile source root: " + directory ); - this.project.addCompileSourceRoot( directory.getAbsolutePath() ); + private void addSourceRoot(File directory) { + if (this.project != null) { + getLog().debug("Adding compile source root: " + directory); + this.project.addCompileSourceRoot(directory.getAbsolutePath()); } } @@ -634,40 +595,38 @@ private void addSourceRoot( File directory ) * Creates a new facade to invoke JavaCC. Most options for the invocation are derived from the current values of the * corresponding mojo parameters. The caller is responsible to set the input file and output directory on the * returned facade. - * + * * @return The facade for the tool invocation, never null. */ - protected JavaCC newJavaCC() - { + protected JavaCC newJavaCC() { JavaCC javacc = new JavaCC(); - javacc.setLog( getLog() ); - javacc.setGrammarEncoding( this.grammarEncoding ); - javacc.setJdkVersion( this.jdkVersion ); - javacc.setStatic( this.isStatic ); - javacc.setBuildParser( this.buildParser ); - javacc.setBuildTokenManager( this.buildTokenManager ); - javacc.setCacheTokens( this.cacheTokens ); - javacc.setChoiceAmbiguityCheck( this.choiceAmbiguityCheck ); - javacc.setCommonTokenAction( this.commonTokenAction ); - javacc.setDebugLookAhead( this.debugLookAhead ); - javacc.setDebugParser( this.debugParser ); - javacc.setDebugTokenManager( this.debugTokenManager ); - javacc.setErrorReporting( this.errorReporting ); - javacc.setForceLaCheck( this.forceLaCheck ); - javacc.setIgnoreCase( this.ignoreCase ); - javacc.setJavaUnicodeEscape( this.javaUnicodeEscape ); - javacc.setKeepLineColumn( this.keepLineColumn ); - javacc.setLookAhead( this.lookAhead ); - javacc.setOtherAmbiguityCheck( this.otherAmbiguityCheck ); - javacc.setSanityCheck( this.sanityCheck ); - javacc.setTokenManagerUsesParser( this.tokenManagerUsesParser ); - javacc.setTokenExtends( this.tokenExtends ); - javacc.setTokenFactory( this.tokenFactory ); - javacc.setUnicodeInput( this.unicodeInput ); - javacc.setUserCharStream( this.userCharStream ); - javacc.setUserTokenManager( this.userTokenManager ); - javacc.setSupportClassVisibilityPublic( this.supportClassVisibilityPublic ); + javacc.setLog(getLog()); + javacc.setGrammarEncoding(this.grammarEncoding); + javacc.setJdkVersion(this.jdkVersion); + javacc.setStatic(this.isStatic); + javacc.setBuildParser(this.buildParser); + javacc.setBuildTokenManager(this.buildTokenManager); + javacc.setCacheTokens(this.cacheTokens); + javacc.setChoiceAmbiguityCheck(this.choiceAmbiguityCheck); + javacc.setCommonTokenAction(this.commonTokenAction); + javacc.setDebugLookAhead(this.debugLookAhead); + javacc.setDebugParser(this.debugParser); + javacc.setDebugTokenManager(this.debugTokenManager); + javacc.setErrorReporting(this.errorReporting); + javacc.setForceLaCheck(this.forceLaCheck); + javacc.setIgnoreCase(this.ignoreCase); + javacc.setJavaUnicodeEscape(this.javaUnicodeEscape); + javacc.setKeepLineColumn(this.keepLineColumn); + javacc.setLookAhead(this.lookAhead); + javacc.setOtherAmbiguityCheck(this.otherAmbiguityCheck); + javacc.setSanityCheck(this.sanityCheck); + javacc.setTokenManagerUsesParser(this.tokenManagerUsesParser); + javacc.setTokenExtends(this.tokenExtends); + javacc.setTokenFactory(this.tokenFactory); + javacc.setUnicodeInput(this.unicodeInput); + javacc.setUserCharStream(this.userCharStream); + javacc.setUserTokenManager(this.userTokenManager); + javacc.setSupportClassVisibilityPublic(this.supportClassVisibilityPublic); return javacc; } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/AbstractPreprocessorMojo.java b/src/main/java/org/codehaus/mojo/javacc/AbstractPreprocessorMojo.java index cf1b2f5..c555ceb 100644 --- a/src/main/java/org/codehaus/mojo/javacc/AbstractPreprocessorMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/AbstractPreprocessorMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -31,12 +31,10 @@ /** * Provides common services for all mojos that preprocess JavaCC grammar files. - * + * * @author Benjamin Bentmann */ -public abstract class AbstractPreprocessorMojo - extends AbstractMojo -{ +public abstract class AbstractPreprocessorMojo extends AbstractMojo { /** * The current Maven project. @@ -47,14 +45,14 @@ public abstract class AbstractPreprocessorMojo /** * Gets the absolute path to the directory where the grammar files are located. - * + * * @return The absolute path to the directory where the grammar files are located, never null. */ protected abstract File getSourceDirectory(); /** * Gets a set of Ant-like inclusion patterns used to select files from the source directory for processing. - * + * * @return A set of Ant-like inclusion patterns used to select files from the source directory for processing, can * be null if all files should be included. */ @@ -62,7 +60,7 @@ public abstract class AbstractPreprocessorMojo /** * Gets a set of Ant-like exclusion patterns used to unselect files from the source directory for processing. - * + * * @return A set of Ant-like inclusion patterns used to unselect files from the source directory for processing, can * be null if no files should be excluded. */ @@ -70,7 +68,7 @@ public abstract class AbstractPreprocessorMojo /** * Gets the absolute path to the directory where the generated Java files for the parser will be stored. - * + * * @return The absolute path to the directory where the generated Java files for the parser will be stored, never * null. */ @@ -79,7 +77,7 @@ public abstract class AbstractPreprocessorMojo /** * Gets the absolute path to the directory where the processed input files will be stored for later detection of * stale sources. - * + * * @return The absolute path to the directory where the processed input files will be stored for later detection of * stale sources, never null. */ @@ -88,7 +86,7 @@ public abstract class AbstractPreprocessorMojo /** * Gets the granularity in milliseconds of the last modification date for testing whether a source needs * recompilation. - * + * * @return The granularity in milliseconds of the last modification date for testing whether a source needs * recompilation. */ @@ -96,37 +94,29 @@ public abstract class AbstractPreprocessorMojo /** * Execute the tool. - * + * * @throws MojoExecutionException If the invocation of the tool failed. * @throws MojoFailureException If the tool reported a non-zero exit code. */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - getLog().warn( "This goal has been deprecated. Please update your plugin configuration." ); + public void execute() throws MojoExecutionException, MojoFailureException { + getLog().warn("This goal has been deprecated. Please update your plugin configuration."); GrammarInfo[] grammarInfos = scanForGrammars(); - if ( grammarInfos == null ) - { - getLog().info( "Skipping non-existing source directory: " + getSourceDirectory() ); + if (grammarInfos == null) { + getLog().info("Skipping non-existing source directory: " + getSourceDirectory()); return; - } - else if (grammarInfos.length == 0) - { - getLog().info( "Skipping - all parsers are up to date" ); - } - else - { - if ( !getTimestampDirectory().exists() ) - { + } else if (grammarInfos.length == 0) { + getLog().info("Skipping - all parsers are up to date"); + } else { + if (!getTimestampDirectory().exists()) { getTimestampDirectory().mkdirs(); } for (GrammarInfo grammarInfo : grammarInfos) { processGrammar(grammarInfo); } - getLog().info( "Processed " + grammarInfos.length + " grammar" + ( grammarInfos.length != 1 ? "s" : "" ) ); + getLog().info("Processed " + grammarInfos.length + " grammar" + (grammarInfos.length != 1 ? "s" : "")); } addCompileSourceRoot(); @@ -134,81 +124,67 @@ else if (grammarInfos.length == 0) /** * Passes the specified grammar file through the tool. - * + * * @param grammarInfo The grammar info describing the grammar file to process, must not be null. * @throws MojoExecutionException If the invocation of the tool failed. * @throws MojoFailureException If the tool reported a non-zero exit code. */ - protected abstract void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException; + protected abstract void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException; /** * Scans the configured source directory for grammar files which need processing. - * + * * @return An array of grammar infos describing the found grammar files or null if the source * directory does not exist. * @throws MojoExecutionException If the source directory could not be scanned. */ - private GrammarInfo[] scanForGrammars() - throws MojoExecutionException - { - if ( !getSourceDirectory().isDirectory() ) - { + private GrammarInfo[] scanForGrammars() throws MojoExecutionException { + if (!getSourceDirectory().isDirectory()) { return null; } GrammarInfo[] grammarInfos; - getLog().debug( "Scanning for grammars: " + getSourceDirectory() ); - try - { + getLog().debug("Scanning for grammars: " + getSourceDirectory()); + try { GrammarDirectoryScanner scanner = new LegacyGrammarDirectoryScanner(); - scanner.setSourceDirectory( getSourceDirectory() ); - scanner.setIncludes( getIncludes() ); - scanner.setExcludes( getExcludes() ); - scanner.setOutputDirectory( getTimestampDirectory() ); - scanner.setStaleMillis( getStaleMillis() ); + scanner.setSourceDirectory(getSourceDirectory()); + scanner.setIncludes(getIncludes()); + scanner.setExcludes(getExcludes()); + scanner.setOutputDirectory(getTimestampDirectory()); + scanner.setStaleMillis(getStaleMillis()); scanner.scan(); grammarInfos = scanner.getIncludedGrammars(); + } catch (Exception e) { + throw new MojoExecutionException("Failed to scan for grammars: " + getSourceDirectory(), e); } - catch ( Exception e ) - { - throw new MojoExecutionException( "Failed to scan for grammars: " + getSourceDirectory(), e ); - } - getLog().debug( "Found grammars: " + Arrays.asList( grammarInfos ) ); + getLog().debug("Found grammars: " + Arrays.asList(grammarInfos)); return grammarInfos; } /** * Creates the timestamp file for the specified grammar file. - * + * * @param grammarInfo The grammar info describing the grammar file to process, must not be null. */ - protected void createTimestamp( GrammarInfo grammarInfo ) - { + protected void createTimestamp(GrammarInfo grammarInfo) { File jjFile = grammarInfo.getGrammarFile(); - File timestampFile = new File( getTimestampDirectory(), grammarInfo.getRelativeGrammarFile() ); - try - { - FileUtils.copyFile( jjFile, timestampFile ); - } - catch ( Exception e ) - { - getLog().warn( "Failed to create copy for timestamp check: " + jjFile, e ); + File timestampFile = new File(getTimestampDirectory(), grammarInfo.getRelativeGrammarFile()); + try { + FileUtils.copyFile(jjFile, timestampFile); + } catch (Exception e) { + getLog().warn("Failed to create copy for timestamp check: " + jjFile, e); } } /** * Registers the configured output directory as a compile source root for the current project. */ - protected void addCompileSourceRoot() - { - if ( this.project != null ) - { - getLog().debug( "Adding compile source root: " + getOutputDirectory() ); - this.project.addCompileSourceRoot( getOutputDirectory().getAbsolutePath() ); + protected void addCompileSourceRoot() { + if (this.project != null) { + getLog().debug("Adding compile source root: " + getOutputDirectory()); + this.project.addCompileSourceRoot(getOutputDirectory().getAbsolutePath()); } } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/ForkedJvm.java b/src/main/java/org/codehaus/mojo/javacc/ForkedJvm.java index 8df0860..0a1c70d 100644 --- a/src/main/java/org/codehaus/mojo/javacc/ForkedJvm.java +++ b/src/main/java/org/codehaus/mojo/javacc/ForkedJvm.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -37,8 +37,7 @@ * @see java - The Java Application * Launcher */ -class ForkedJvm -{ +class ForkedJvm { /** * The consumer for System.out messages. @@ -78,141 +77,122 @@ class ForkedJvm /** * Creates a new configuration to fork a JVM. */ - public ForkedJvm() - { + public ForkedJvm() { this.executable = getDefaultExecutable(); } /** * Gets the absolute path to the JVM executable. - * + * * @return The absolute path to the JVM executable. */ - private static String getDefaultExecutable() - { - return System.getProperty( "java.home" ) + File.separator + "bin" + File.separator + "java"; + private static String getDefaultExecutable() { + return System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; } /** * Sets the working directory for the forked JVM. - * + * * @param directory The working directory for the forked JVM, may be null to inherit the working * directory of the current JVM. */ - public void setWorkingDirectory( File directory ) - { + public void setWorkingDirectory(File directory) { this.workingDirectory = directory; } /** * Sets the stream consumer used to handle messages from System.out. - * + * * @param consumer The stream consumer, may be null to discard the output. */ - public void setSystemOut( StreamConsumer consumer ) - { + public void setSystemOut(StreamConsumer consumer) { this.systemOut = consumer; } /** * Sets the stream consumer used to handle messages from System.err. - * + * * @param consumer The stream consumer, may be null to discard the output. */ - public void setSystemErr( StreamConsumer consumer ) - { + public void setSystemErr(StreamConsumer consumer) { this.systemErr = consumer; } /** * Adds the specified path to the class path of the forked JVM. - * + * * @param path The path to add, may be null. */ - public void addClassPathEntry( String path ) - { - if ( path != null ) - { - this.classPathEntries.add( path ); + public void addClassPathEntry(String path) { + if (path != null) { + this.classPathEntries.add(path); } } /** * Adds the specified path to the class path of the forked JVM. - * + * * @param path The path to add, may be null. */ - public void addClassPathEntry( File path ) - { - if ( path != null ) - { - this.classPathEntries.add( path.getAbsolutePath() ); + public void addClassPathEntry(File path) { + if (path != null) { + this.classPathEntries.add(path.getAbsolutePath()); } } /** * Adds the source JAR of the specified class/interface to the class path of the forked JVM. - * + * * @param type The class/interface to add, may be null. */ - public void addClassPathEntry( Class type ) - { - addClassPathEntry( getClassSource( type ) ); + public void addClassPathEntry(Class type) { + addClassPathEntry(getClassSource(type)); } /** * Gets the JAR file or directory that contains the specified class. - * + * * @param type The class/interface to find, may be null. * @return The absolute path to the class source location or null if unknown. */ - private static File getClassSource( Class type ) - { - if ( type != null ) - { - String classResource = type.getName().replace( '.', '/' ) + ".class"; - return getResourceSource( classResource, type.getClassLoader() ); + private static File getClassSource(Class type) { + if (type != null) { + String classResource = type.getName().replace('.', '/') + ".class"; + return getResourceSource(classResource, type.getClassLoader()); } return null; } /** * Gets the JAR file or directory that contains the specified class. - * + * * @param className The qualified name of the class/interface to find, may be null. * @return The absolute path to the class source location or null if unknown. */ - private static File getClassSource( String className ) - { - if ( className != null ) - { - String classResource = className.replace( '.', '/' ) + ".class"; - return getResourceSource( classResource, Thread.currentThread().getContextClassLoader() ); + private static File getClassSource(String className) { + if (className != null) { + String classResource = className.replace('.', '/') + ".class"; + return getResourceSource(classResource, Thread.currentThread().getContextClassLoader()); } return null; } /** * Gets the JAR file or directory that contains the specified resource. - * + * * @param resource The absolute name of the resource to find, may be null. * @param loader The class loader to use for searching the resource, may be null. * @return The absolute path to the resource location or null if unknown. */ - private static File getResourceSource( String resource, ClassLoader loader ) - { - if ( resource != null ) - { + private static File getResourceSource(String resource, ClassLoader loader) { + if (resource != null) { URL url; - if ( loader != null ) - { - url = loader.getResource( resource ); + if (loader != null) { + url = loader.getResource(resource); + } else { + url = ClassLoader.getSystemResource(resource); } - else - { - url = ClassLoader.getSystemResource( resource ); - } - return UrlUtils.getResourceRoot( url, resource ); + return UrlUtils.getResourceRoot(url, resource); } return null; } @@ -220,72 +200,63 @@ private static File getResourceSource( String resource, ClassLoader loader ) /** * Sets the qualified name of the class on which to invoke the main() method. The source of the * specified class will automatically be added to the class path of the forked JVM. - * + * * @param name The qualified name of the class on which to invoke the main() method. */ - public void setMainClass( String name ) - { + public void setMainClass(String name) { this.mainClass = name; - addClassPathEntry( getClassSource( name ) ); + addClassPathEntry(getClassSource(name)); } /** * Sets the class on which to invoke the main() method. The source of the specified class will * automatically be added to the class path of the forked JVM. - * + * * @param type The class on which to invoke the main() method, may be null. */ - public void setMainClass( Class type ) - { - this.mainClass = ( type != null ) ? type.getName() : null; - addClassPathEntry( type ); + public void setMainClass(Class type) { + this.mainClass = (type != null) ? type.getName() : null; + addClassPathEntry(type); } /** * Gets the command line arguments for the main() method. - * + * * @return The command line arguments for the main() method. */ - private String[] getArguments() - { + private String[] getArguments() { return this.cmdLineArgs.toArray(new String[0]); } /** * Adds the specified argument to the command line for the main() method. - * + * * @param argument The argument to add, may be null. */ - public void addArgument( String argument ) - { - if ( argument != null ) - { - this.cmdLineArgs.add( argument ); + public void addArgument(String argument) { + if (argument != null) { + this.cmdLineArgs.add(argument); } } /** * Adds the specified file path to the command line for the main() method. - * + * * @param argument The argument to add, may be null. */ - public void addArgument( File argument ) - { - if ( argument != null ) - { - this.cmdLineArgs.add( argument.getAbsolutePath() ); + public void addArgument(File argument) { + if (argument != null) { + this.cmdLineArgs.add(argument.getAbsolutePath()); } } /** * Adds the specified arguments to the command line for the main() method. - * + * * @param arguments The arguments to add, may be null. */ - public void addArguments( String[] arguments ) - { - if ( arguments != null ) - { + public void addArguments(String[] arguments) { + if (arguments != null) { for (String argument : arguments) { addArgument(argument); } @@ -294,11 +265,10 @@ public void addArguments( String[] arguments ) /** * Creates the command line for the new JVM based on the current configuration. - * + * * @return The command line used to fork the JVM, never null. */ - private Commandline createCommandLine() - { + private Commandline createCommandLine() { /* * NOTE: This method is designed to work with plexus-utils:1.1 which is used by all Maven versions before 2.0.6 * regardless of our plugin dependency. Therefore, we use setWorkingDirectory(String) rather than @@ -307,49 +277,42 @@ private Commandline createCommandLine() Commandline cli = new Commandline(); - cli.setExecutable( this.executable ); + cli.setExecutable(this.executable); - if ( this.workingDirectory != null ) - { - cli.setWorkingDirectory( this.workingDirectory.getAbsolutePath() ); + if (this.workingDirectory != null) { + cli.setWorkingDirectory(this.workingDirectory.getAbsolutePath()); } String classPath = String.join(File.pathSeparator, classPathEntries); - if (classPath.length() > 0) - { - cli.addArguments( new String[] { "-cp", classPath } ); + if (classPath.length() > 0) { + cli.addArguments(new String[] {"-cp", classPath}); } - if ( this.mainClass != null && this.mainClass.length() > 0 ) - { - cli.addArguments( new String[] { this.mainClass } ); + if (this.mainClass != null && this.mainClass.length() > 0) { + cli.addArguments(new String[] {this.mainClass}); } - cli.addArguments( getArguments() ); + cli.addArguments(getArguments()); return cli; } /** * Forks a JVM using the previously set parameters. - * + * * @return The exit code of the forked JVM. * @throws Exception If the JVM could not be forked. */ - public int run() - throws Exception - { - return CommandLineUtils.executeCommandLine( createCommandLine(), this.systemOut, this.systemErr ); + public int run() throws Exception { + return CommandLineUtils.executeCommandLine(createCommandLine(), this.systemOut, this.systemErr); } /** * Gets a string representation of the command line arguments. - * + * * @return A string representation of the command line arguments. */ - public String toString() - { - return String.valueOf( createCommandLine() ); + public String toString() { + return String.valueOf(createCommandLine()); } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/GrammarDirectoryScanner.java b/src/main/java/org/codehaus/mojo/javacc/GrammarDirectoryScanner.java index 28eb82c..2703322 100644 --- a/src/main/java/org/codehaus/mojo/javacc/GrammarDirectoryScanner.java +++ b/src/main/java/org/codehaus/mojo/javacc/GrammarDirectoryScanner.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -28,12 +28,11 @@ /** * Scans source directories for JavaCC grammar files. - * + * * @author Benjamin Bentmann * @version $Id$ */ -class GrammarDirectoryScanner -{ +class GrammarDirectoryScanner { /** * The directory scanner used to scan the source directory for files. @@ -67,95 +66,84 @@ class GrammarDirectoryScanner /** * Creates a new grammar directory scanner. */ - public GrammarDirectoryScanner() - { + public GrammarDirectoryScanner() { this.scanner = new DirectoryScanner(); - this.scanner.setFollowSymlinks( true ); + this.scanner.setFollowSymlinks(true); this.includedGrammars = new ArrayList<>(); } /** * Sets the absolute path to the source directory to scan for grammar files. This directory must exist or the * scanner will report an error. - * + * * @param directory The absolute path to the source directory to scan, must not be null. */ - public void setSourceDirectory( File directory ) - { - if ( !directory.isAbsolute() ) - { - throw new IllegalArgumentException( "source directory is not absolute: " + directory ); + public void setSourceDirectory(File directory) { + if (!directory.isAbsolute()) { + throw new IllegalArgumentException("source directory is not absolute: " + directory); } - this.scanner.setBasedir( directory ); + this.scanner.setBasedir(directory); } /** * Sets the package name for the generated parser. - * + * * @param packageName The package name for the generated parser, may be null to use the package * declaration from the grammar file. */ - public void setParserPackage( String packageName ) - { + public void setParserPackage(String packageName) { this.parserPackage = packageName; } /** * Sets the Ant-like inclusion patterns. - * + * * @param includes The set of Ant-like inclusion patterns, may be null to include all files. */ - public void setIncludes( String[] includes ) - { - this.scanner.setIncludes( includes ); + public void setIncludes(String[] includes) { + this.scanner.setIncludes(includes); } /** * Sets the Ant-like exclusion patterns. - * + * * @param excludes The set of Ant-like exclusion patterns, may be null to exclude no files. */ - public void setExcludes( String[] excludes ) - { - this.scanner.setExcludes( excludes ); + public void setExcludes(String[] excludes) { + this.scanner.setExcludes(excludes); this.scanner.addDefaultExcludes(); } /** * Sets the absolute path to the output directory used to detect stale target files. - * + * * @param directory The absolute path to the output directory used to detect stale target files by timestamp * checking, may be null if no stale detection should be performed. */ - public void setOutputDirectory( File directory ) - { - if ( directory != null && !directory.isAbsolute() ) - { - throw new IllegalArgumentException( "output directory is not absolute: " + directory ); + public void setOutputDirectory(File directory) { + if (directory != null && !directory.isAbsolute()) { + throw new IllegalArgumentException("output directory is not absolute: " + directory); } this.outputDirectory = directory; } /** * Sets the granularity in milliseconds of the last modification date for stale file detection. - * + * * @param milliseconds The granularity in milliseconds of the last modification date for testing whether a grammar * file needs recompilation because its corresponding target file is stale. */ - public void setStaleMillis( int milliseconds ) - { + public void setStaleMillis(int milliseconds) { this.staleMillis = milliseconds; } /** * Scans the source directory for grammar files that match at least one inclusion pattern but no exclusion pattern, * optionally performing timestamp checking to exclude grammars whose corresponding parser files are up to date. - * + * * @throws IOException If a grammar file could not be analyzed for metadata. */ - public void scan() - throws IOException - { + public void scan() throws IOException { this.includedGrammars.clear(); this.scanner.scan(); @@ -180,7 +168,7 @@ public void scan() /** * Determines the output files corresponding to the specified grammar file. - * + * * @param targetDirectory The absolute path to the output directory for the target files, must not be * null. * @param grammarFile The path to the grammar file, relative to the scanned source directory, must not be @@ -188,21 +176,18 @@ public void scan() * @param grammarInfo The grammar info describing the grammar file, must not be null * @return A file array with target files, never null. */ - protected File[] getTargetFiles( File targetDirectory, String grammarFile, GrammarInfo grammarInfo ) - { - File parserFile = new File( targetDirectory, grammarInfo.getParserFile() ); - return new File[] { parserFile }; + protected File[] getTargetFiles(File targetDirectory, String grammarFile, GrammarInfo grammarInfo) { + File parserFile = new File(targetDirectory, grammarInfo.getParserFile()); + return new File[] {parserFile}; } /** * Gets the grammar files that were included by the scanner during the last invocation of {@link #scan()}. - * + * * @return An array of grammar infos describing the included grammar files, will be empty if no files were included * but is never null. */ - public GrammarInfo[] getIncludedGrammars() - { + public GrammarInfo[] getIncludedGrammars() { return this.includedGrammars.toArray(new GrammarInfo[0]); } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/GrammarInfo.java b/src/main/java/org/codehaus/mojo/javacc/GrammarInfo.java index 4b4f8ed..7fcb299 100644 --- a/src/main/java/org/codehaus/mojo/javacc/GrammarInfo.java +++ b/src/main/java/org/codehaus/mojo/javacc/GrammarInfo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -29,11 +29,10 @@ /** * This bean holds some output related information about a JavaCC grammar file. It assists in determining the exact * output location for the generated parser file. - * + * * @author Benjamin Bentmann */ -class GrammarInfo -{ +class GrammarInfo { /** * The absolute path to the base directory in which the grammar file resides. @@ -67,21 +66,19 @@ class GrammarInfo /** * Creates a new info from the specified grammar file. - * + * * @param sourceDir The absolute path to the base directory in which the grammar file resides, must not be * null. * @param inputFile The path to the grammar file (relative to the source directory), must not be null. * @throws IOException If reading the grammar file failed. */ - public GrammarInfo( File sourceDir, String inputFile ) - throws IOException - { - this( sourceDir, inputFile, null ); + public GrammarInfo(File sourceDir, String inputFile) throws IOException { + this(sourceDir, inputFile, null); } /** * Creates a new info from the specified grammar file. - * + * * @param sourceDir The absolute path to the base directory in which the grammar file resides, must not be * null. * @param inputFile The path to the grammar file (relative to the source directory), must not be null. @@ -89,94 +86,73 @@ public GrammarInfo( File sourceDir, String inputFile ) * declaration from the grammar file. * @throws IOException If reading the grammar file failed. */ - public GrammarInfo( File sourceDir, String inputFile, String packageName ) - throws IOException - { - if ( !sourceDir.isAbsolute() ) - { - throw new IllegalArgumentException( "source directory is not absolute: " + sourceDir ); + public GrammarInfo(File sourceDir, String inputFile, String packageName) throws IOException { + if (!sourceDir.isAbsolute()) { + throw new IllegalArgumentException("source directory is not absolute: " + sourceDir); } this.sourceDirectory = sourceDir; - File inFile = new File( inputFile ); - if ( !inFile.isAbsolute() ) - { + File inFile = new File(inputFile); + if (!inFile.isAbsolute()) { this.grammarFile = inFile.getPath(); - } - else if ( inFile.getPath().startsWith( sourceDir.getPath() ) ) - { - this.grammarFile = inFile.getPath().substring( sourceDir.getPath().length() + 1 ); - } - else - { - throw new IllegalArgumentException( "input file is not relative to source directory:" + inputFile ); + } else if (inFile.getPath().startsWith(sourceDir.getPath())) { + this.grammarFile = inFile.getPath().substring(sourceDir.getPath().length() + 1); + } else { + throw new IllegalArgumentException("input file is not relative to source directory:" + inputFile); } // NOTE: JavaCC uses the platform default encoding to read files, so must we - String grammar = FileUtils.fileRead( getGrammarFile() ); + String grammar = FileUtils.fileRead(getGrammarFile()); // TODO: Once the parameter "packageName" from the javacc mojo has been deleted, remove our parameter, too. - if ( packageName == null ) - { - this.parserPackage = findPackageName( grammar ); - } - else - { + if (packageName == null) { + this.parserPackage = findPackageName(grammar); + } else { this.parserPackage = packageName; } - this.parserDirectory = this.parserPackage.replace( '.', File.separatorChar ); + this.parserDirectory = this.parserPackage.replace('.', File.separatorChar); - String name = findParserName( grammar ); - if (name.length() == 0) - { - this.parserName = FileUtils.removeExtension( inFile.getName() ); - } - else - { + String name = findParserName(grammar); + if (name.length() == 0) { + this.parserName = FileUtils.removeExtension(inFile.getName()); + } else { this.parserName = name; } - if ( this.parserDirectory.length() > 0 ) - { - this.parserFile = new File( this.parserDirectory, this.parserName + ".java" ).getPath(); - } - else - { + if (this.parserDirectory.length() > 0) { + this.parserFile = new File(this.parserDirectory, this.parserName + ".java").getPath(); + } else { this.parserFile = this.parserName + ".java"; } } /** * Extracts the declared package name from the specified grammar file. - * + * * @param grammar The contents of the grammar file, must not be null. * @return The declared package name or an empty string if not found. */ - private String findPackageName( String grammar ) - { + private String findPackageName(String grammar) { final String packageDeclaration = "package\\s+([^\\s.;]+(\\.[^\\s.;]+)*)\\s*;"; - Matcher matcher = Pattern.compile( packageDeclaration ).matcher( grammar ); - if ( matcher.find() ) - { - return matcher.group( 1 ); + Matcher matcher = Pattern.compile(packageDeclaration).matcher(grammar); + if (matcher.find()) { + return matcher.group(1); } return ""; } /** * Extracts the simple parser name from the specified grammar file. - * + * * @param grammar The contents of the grammar file, must not be null. * @return The parser name or an empty string if not found. */ - private String findParserName( String grammar ) - { + private String findParserName(String grammar) { final String parserBegin = "PARSER_BEGIN\\s*\\(\\s*([^\\s\\)]+)\\s*\\)"; - Matcher matcher = Pattern.compile( parserBegin ).matcher( grammar ); - if ( matcher.find() ) - { - return matcher.group( 1 ); + Matcher matcher = Pattern.compile(parserBegin).matcher(grammar); + if (matcher.find()) { + return matcher.group(1); } return ""; } @@ -184,31 +160,28 @@ private String findParserName( String grammar ) /** * Gets the absolute path to the base directory in which the grammar file resides. Note that this is not necessarily * the parent directory of the grammar file. - * + * * @return The absolute path to the base directory in which the grammar file resides, never null. */ - public File getSourceDirectory() - { + public File getSourceDirectory() { return this.sourceDirectory; } /** * Gets the absolute path to the grammar file. - * + * * @return The absolute path to the grammar file, never null. */ - public File getGrammarFile() - { - return new File( this.sourceDirectory, this.grammarFile ); + public File getGrammarFile() { + return new File(this.sourceDirectory, this.grammarFile); } /** * Gets the path to the grammar file (relative to its source directory). - * + * * @return The path to the grammar file (relative to its source directory), never null. */ - public String getRelativeGrammarFile() - { + public String getRelativeGrammarFile() { return this.grammarFile; } @@ -217,19 +190,16 @@ public String getRelativeGrammarFile() * reference the parser package, the input string may use the prefix "*". For example, if the package for the parser * is "org.apache" and the input string is "*.node", the resolved package is "org.apache.node". The period after the * asterisk is significant, i.e. in the previous example the input string "*node" would resolve to "org.apachenode". - * + * * @param packageName The package name to resolve, may be null. * @return The resolved package name or null if the input string was null. */ - public String resolvePackageName( String packageName ) - { + public String resolvePackageName(String packageName) { String resolvedPackageName = packageName; - if ( resolvedPackageName != null && resolvedPackageName.startsWith( "*" ) ) - { - resolvedPackageName = getParserPackage() + resolvedPackageName.substring( 1 ); - if ( resolvedPackageName.startsWith( "." ) ) - { - resolvedPackageName = resolvedPackageName.substring( 1 ); + if (resolvedPackageName != null && resolvedPackageName.startsWith("*")) { + resolvedPackageName = getParserPackage() + resolvedPackageName.substring(1); + if (resolvedPackageName.startsWith(".")) { + resolvedPackageName = resolvedPackageName.substring(1); } } return resolvedPackageName; @@ -237,55 +207,49 @@ public String resolvePackageName( String packageName ) /** * Gets the declared package for the generated parser (e.g. "org.apache"). - * + * * @return The declared package for the generated parser (e.g. "org.apache") or an empty string if no package * declaration was found, never null. */ - public String getParserPackage() - { + public String getParserPackage() { return this.parserPackage; } /** * Gets the path to the directory of the parser package (relative to a source root directory, e.g. "org/apache"). - * + * * @return The path to the directory of the parser package (relative to a source root directory, e.g. "org/apache") * or an empty string if no package declaration was found, never null. */ - public String getParserDirectory() - { + public String getParserDirectory() { return this.parserDirectory; } /** * Gets the simple name of the generated parser (e.g. "MyParser") - * + * * @return The simple name of the generated parser (e.g. "MyParser"), never null. */ - public String getParserName() - { + public String getParserName() { return this.parserName; } /** * Gets the path to the parser file (relative to a source root directory, e.g. "org/apache/MyParser.java"). - * + * * @return The path to the parser file (relative to a source root directory, e.g. "org/apache/MyParser.java"), never * null. */ - public String getParserFile() - { + public String getParserFile() { return this.parserFile; } /** * Gets a string representation of this bean. This value is for debugging purposes only. - * + * * @return A string representation of this bean. */ - public String toString() - { + public String toString() { return getGrammarFile() + " -> " + getParserFile(); } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JJDoc.java b/src/main/java/org/codehaus/mojo/javacc/JJDoc.java index 4d35c23..dc9dd96 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JJDoc.java +++ b/src/main/java/org/codehaus/mojo/javacc/JJDoc.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -29,13 +29,11 @@ /** * Provides a facade for the mojos to invoke JJDoc. - * + * * @author Paul Gier, Benjamin Bentmann * @see JJDoc Reference */ -class JJDoc - extends ToolFacade -{ +class JJDoc extends ToolFacade { /** * The input grammar. @@ -74,151 +72,130 @@ class JJDoc /** * Sets the absolute path to the grammar file to pass into JJDoc for documentation. - * + * * @param value The absolute path to the grammar file to pass into JJDoc for documentation. */ - public void setInputFile( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setInputFile(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.inputFile = value; } /** * Sets the absolute path to the output file. - * + * * @param value The absolute path to the HTML/text file to generate. */ - public void setOutputFile( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setOutputFile(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.outputFile = value; } /** * Sets the option GRAMMAR_ENCODING. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setGrammarEncoding( String value ) - { + public void setGrammarEncoding(String value) { this.grammarEncoding = value; } /** * Sets the option CSS, i.e the hypertext reference to a CSS file for the generated HTML output. - * + * * @param value The option value, may be null to use the default style. */ - public void setCssHref( String value ) - { + public void setCssHref(String value) { this.cssHref = value; } /** * Sets the option TEXT. - * + * * @param value The option value, may be null to use the default value. */ - public void setText( Boolean value ) - { + public void setText(Boolean value) { this.text = value; } /** * Sets the option BNF. - * + * * @param value The option value, may be null to use the default value. */ - public void setBnf( Boolean value ) - { + public void setBnf(Boolean value) { this.bnf = value; } /** * Sets the option value ONE_TABLE. - * + * * @param value The option value, may be null to use the default value. */ - public void setOneTable( Boolean value ) - { + public void setOneTable(Boolean value) { this.oneTable = value; } /** * {@inheritDoc} */ - protected int execute() - throws Exception - { + protected int execute() throws Exception { String[] args = generateArguments(); - File outputDirectory = ( this.outputFile != null ) ? this.outputFile.getParentFile() : null; - if ( outputDirectory != null && !outputDirectory.exists() ) - { + File outputDirectory = (this.outputFile != null) ? this.outputFile.getParentFile() : null; + if (outputDirectory != null && !outputDirectory.exists()) { outputDirectory.mkdirs(); } // fork jjdoc because of calls to System.exit() ForkedJvm jvm = new ForkedJvm(); - jvm.setMainClass( org.javacc.jjdoc.JJDocMain.class ); - jvm.addArguments( args ); - jvm.setSystemOut( new MojoLogStreamConsumer( false ) ); - jvm.setSystemErr( new MojoLogStreamConsumer( true ) ); - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Forking: " + jvm ); + jvm.setMainClass(org.javacc.jjdoc.JJDocMain.class); + jvm.addArguments(args); + jvm.setSystemOut(new MojoLogStreamConsumer(false)); + jvm.setSystemErr(new MojoLogStreamConsumer(true)); + if (getLog().isDebugEnabled()) { + getLog().debug("Forking: " + jvm); } return jvm.run(); } /** * Assembles the command line arguments for the invocation of JJDoc according to the configuration. - * + * * @return A string array that represents the arguments to use for JJDoc. */ - private String[] generateArguments() - { + private String[] generateArguments() { List argsList = new ArrayList<>(); - if ( StringUtils.isNotEmpty( this.grammarEncoding ) ) - { - argsList.add( "-GRAMMAR_ENCODING=" + this.grammarEncoding ); + if (StringUtils.isNotEmpty(this.grammarEncoding)) { + argsList.add("-GRAMMAR_ENCODING=" + this.grammarEncoding); } - if ( this.text != null ) - { - argsList.add( "-TEXT=" + this.text ); + if (this.text != null) { + argsList.add("-TEXT=" + this.text); } - if ( this.bnf != null ) - { - argsList.add( "-BNF=" + this.bnf ); + if (this.bnf != null) { + argsList.add("-BNF=" + this.bnf); } - if ( this.oneTable != null ) - { - argsList.add( "-ONE_TABLE=" + this.oneTable ); + if (this.oneTable != null) { + argsList.add("-ONE_TABLE=" + this.oneTable); } - if ( this.outputFile != null ) - { - argsList.add( "-OUTPUT_FILE=" + this.outputFile.getAbsolutePath() ); + if (this.outputFile != null) { + argsList.add("-OUTPUT_FILE=" + this.outputFile.getAbsolutePath()); } - if ( StringUtils.isNotEmpty( this.cssHref ) ) - { - argsList.add( "-CSS=" + this.cssHref ); + if (StringUtils.isNotEmpty(this.cssHref)) { + argsList.add("-CSS=" + this.cssHref); } - if ( this.inputFile != null ) - { - argsList.add( this.inputFile.getAbsolutePath() ); + if (this.inputFile != null) { + argsList.add(this.inputFile.getAbsolutePath()); } return argsList.toArray(new String[0]); @@ -226,20 +203,17 @@ private String[] generateArguments() /** * Gets a string representation of the command line arguments. - * + * * @return A string representation of the command line arguments. */ - public String toString() - { - return Arrays.asList( generateArguments() ).toString(); + public String toString() { + return Arrays.asList(generateArguments()).toString(); } /** * Consume and log command line output from the JJDoc process. */ - class MojoLogStreamConsumer - implements StreamConsumer - { + class MojoLogStreamConsumer implements StreamConsumer { /** * The line prefix used by JJDoc to report errors. @@ -258,38 +232,28 @@ class MojoLogStreamConsumer /** * Single param constructor. - * + * * @param error If set to true, all consumed lines will be logged at the error level. */ - public MojoLogStreamConsumer( boolean error ) - { + public MojoLogStreamConsumer(boolean error) { this.err = error; } /** * Consume a line of text. - * + * * @param line The line to consume. */ - public void consumeLine( String line ) - { - if ( line.startsWith( ERROR_PREFIX ) ) - { - getLog().error( line.substring( ERROR_PREFIX.length() ) ); - } - else if ( line.startsWith( WARN_PREFIX ) ) - { - getLog().warn( line.substring( WARN_PREFIX.length() ) ); - } - else if ( this.err ) - { - getLog().error( line ); - } - else - { - getLog().debug( line ); + public void consumeLine(String line) { + if (line.startsWith(ERROR_PREFIX)) { + getLog().error(line.substring(ERROR_PREFIX.length())); + } else if (line.startsWith(WARN_PREFIX)) { + getLog().warn(line.substring(WARN_PREFIX.length())); + } else if (this.err) { + getLog().error(line); + } else { + getLog().debug(line); } } } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JJDocMojo.java b/src/main/java/org/codehaus/mojo/javacc/JJDocMojo.java index 8b611ff..a8e463f 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JJDocMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/JJDocMojo.java @@ -1,516 +1,474 @@ -package org.codehaus.mojo.javacc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.ResourceBundle; -import java.util.Set; - -import org.apache.maven.doxia.sink.Sink; -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.reporting.AbstractMavenReport; -import org.apache.maven.reporting.MavenReportException; - -/** - * JJDoc takes a JavaCC parser specification and produces - * documentation for the BNF grammar. This mojo will search the source directory for all *.jj files and - * run JJDoc once for each file it finds. Each of these output files, along with an index.html file will - * be placed in the site directory (target/site/jjdoc), and a link will be created in the "Project - * Reports" menu of the generated site. - * - * @since 2.3 - * @author Paul Gier - * @see JJDoc Documentation - */ -@Mojo(name = "jjdoc") -@Execute(phase = LifecyclePhase.GENERATE_SOURCES) -public class JJDocMojo - extends AbstractMavenReport -{ - - // ---------------------------------------------------------------------- - // Mojo Parameters - // ---------------------------------------------------------------------- - - /** - * The directories where the JavaCC grammar files (*.jj) are located. By default, the directories - * ${basedir}/src/main/javacc, ${project.build.directory}/generated-sources/jjtree - * and ${project.build.directory}/generated-sources/jtb are scanned for grammar files to document. - * - */ - @Parameter - private File[] sourceDirectories; - - /** - * The default source directory for hand-crafted grammar files. - * - */ - @Parameter(defaultValue = "${basedir}/src/main/javacc") - private File defaultGrammarDirectoryJavaCC; - - /** - * The default source directory for grammar files generated by JJTree. - * - */ - @Parameter(defaultValue = "${project.build.directory}/generated-sources/jjtree") - private File defaultGrammarDirectoryJJTree; - - /** - * The default source directory for grammar files generated by JTB. - * - */ - @Parameter(defaultValue = "${project.build.directory}/generated-sources/jtb") - private File defaultGrammarDirectoryJTB; - - /** - * The relative path of the JJDoc reports in the output directory. This path will be appended to the output - * directory. - * - */ - @Parameter(defaultValue = "jjdoc") - private String jjdocDirectory; - - /** - * The destination directory where JJDoc saves the generated documentation files. Note that this parameter is only - * relevant if the goal is run from the command line or from the default build lifecycle. If the goal is run - * indirectly as part of a site generation, the output directory configured in the Maven Site Plugin is used - * instead. - * - */ - @Parameter(defaultValue = "${project.reporting.outputDirectory}", property = "javacc.outputDirectory") - private File outputDirectory; - - /** - * The file encoding to use for reading the grammar files. - * - * @since 2.6 - */ - @Parameter(defaultValue = "${project.build.sourceEncoding}", property = "javacc.grammarEncoding") - private String grammarEncoding; - - /** - * The hypertext reference to an optional CSS file for the generated HTML documents. If specified, this CSS file - * will be included via a <link> element in the HTML documents. Otherwise, the default style will - * be used. - * - * @since 2.5 - */ - @Parameter(property = "javacc.cssHref") - private String cssHref; - - /** - * A flag to specify the output format for the generated documentation. If set to true, JJDoc will - * generate a plain text description of the BNF. Some formatting is done via tab characters, but the intention is to - * leave it as plain as possible. Specifying false causes JJDoc to generate a hyperlinked HTML document - * unless the parameter {@link #bnf} has been set to true. Default value is false. - * - */ - @Parameter(property = "javacc.text") - private Boolean text; - - /** - * A flag whether to generate a plain text document with the unformatted BNF. Note that setting this option to - * true is only effective if the parameter {@link #text} is false. Default value is - * false. - * - * @since 2.6 - */ - @Parameter(property = "javacc.bnf") - private Boolean bnf; - - /** - * This option controls the structure of the generated HTML output. If set to true, a single HTML - * table for the entire BNF is generated. Setting it to false will produce one table for every - * production in the grammar. - * - */ - @Parameter(property = "javacc.oneTable", defaultValue = "true") - private boolean oneTable; - - /** - * Get the output directory of the report if run directly from the command line. - * - * @see org.apache.maven.reporting.AbstractMavenReport#getOutputDirectory() - * @return The report output directory. - */ - protected String getOutputDirectory() - { - return this.outputDirectory.getAbsolutePath(); - } - - /** - * Get the output directory of the JJDoc files, i.e. the sub directory in the report output directory as specified - * by the {@link #jjdocDirectory} parameter. - * - * @return The report output directory of the JJDoc files. - */ - private File getJJDocOutputDirectory() - { - return new File( getReportOutputDirectory(), this.jjdocDirectory ); - } - - /** - * Get the source directories that should be scanned for grammar files. - * - * @return The source directories that should be scanned for grammar files, never null. - */ - private File[] getSourceDirectories() - { - Set directories = new LinkedHashSet<>(); - if ( this.sourceDirectories != null && this.sourceDirectories.length > 0 ) - { - directories.addAll( Arrays.asList( this.sourceDirectories ) ); - } - else - { - if ( this.defaultGrammarDirectoryJavaCC != null ) - { - directories.add( this.defaultGrammarDirectoryJavaCC ); - } - if ( this.defaultGrammarDirectoryJJTree != null ) - { - directories.add( this.defaultGrammarDirectoryJJTree ); - } - if ( this.defaultGrammarDirectoryJTB != null ) - { - directories.add( this.defaultGrammarDirectoryJTB ); - } - } - return directories.toArray(new File[0]); - } - - // ---------------------------------------------------------------------- - // public methods - // ---------------------------------------------------------------------- - - /** - * @see org.apache.maven.reporting.MavenReport#getName(java.util.Locale) - * @param locale The locale to use for this report. - * @return The name of this report. - */ - public String getName( Locale locale ) - { - return getBundle( locale ).getString( "report.jjdoc.name" ); - } - - /** - * @see org.apache.maven.reporting.MavenReport#getDescription(java.util.Locale) - * @param locale The locale to use for this report. - * @return The description of this report. - */ - public String getDescription( Locale locale ) - { - return getBundle( locale ).getString( "report.jjdoc.short.description" ); - } - - /** - * @see org.apache.maven.reporting.MavenReport#getOutputName() - * @return The name of the main report file. - */ - public String getOutputName() - { - return this.jjdocDirectory + "/index"; - } - - /** - * @see org.apache.maven.reporting.MavenReport#canGenerateReport() - * @return true if the configured source directories are not empty, false otherwise. - */ - public boolean canGenerateReport() - { - return Arrays.stream(getSourceDirectories()) - .map(File::list) - .anyMatch(files -> files != null && files.length > 0); - } - - /** - * Run the actual report. - * - * @param locale The locale to use for this report. - * @throws MavenReportException If the report generation failed. - */ - public void executeReport( Locale locale ) - throws MavenReportException - { - generate(getSink(), locale); - } - - /** - * The JJDoc output file will have a .html or .txt extension depending on the value of - * the parameters {@link #text} and {@link #bnf}. - * - * @return The file extension (including the leading period) to be used for the JJDoc output files. - */ - private String getOutputFileExtension() - { - if ( Boolean.TRUE.equals( this.text ) || Boolean.TRUE.equals( this.bnf ) ) - { - return ".txt"; - } - else - { - return ".html"; - } - } - - /** - * Create the header and title for the HTML report page. - * - * @param bundle The resource bundle with the text. - * @param sink The sink for writing to the main report file. - */ - private void createReportHeader( ResourceBundle bundle, Sink sink ) - { - sink.head(); - sink.title(); - sink.text( bundle.getString( "report.jjdoc.title" ) ); - sink.title_(); - sink.head_(); - - sink.body(); - - sink.section1(); - sink.sectionTitle1(); - sink.text( bundle.getString( "report.jjdoc.title" ) ); - sink.sectionTitle1_(); - sink.text( bundle.getString( "report.jjdoc.description" ) ); - sink.section1_(); - - sink.lineBreak(); - sink.table(); - sink.tableRow(); - sink.tableHeaderCell(); - sink.text( bundle.getString( "report.jjdoc.table.heading" ) ); - sink.tableHeaderCell_(); - sink.tableRow_(); - } - - /** - * Create a table row containing a link to the JJDoc report for a grammar file. - * - * @param sink The sink to write the report - * @param sourceDirectory The source directory of the grammar file. - * @param grammarFile The JavaCC grammar file. - * @param linkPath The path to the JJDoc output. - */ - private void createReportLink( Sink sink, File sourceDirectory, File grammarFile, String linkPath ) - { - sink.tableRow(); - sink.tableCell(); - if ( linkPath.startsWith( "/" ) ) - { - linkPath = linkPath.substring( 1 ); - } - sink.link( linkPath ); - String grammarFileRelativePath = sourceDirectory.toURI().relativize( grammarFile.toURI() ).toString(); - if ( grammarFileRelativePath.startsWith( "/" ) ) - { - grammarFileRelativePath = grammarFileRelativePath.substring( 1 ); - } - sink.text( grammarFileRelativePath ); - sink.link_(); - sink.tableCell_(); - sink.tableRow_(); - } - - /** - * Create the HTML footer for the report page. - * - * @param sink The sink to write the HTML report page. - */ - private void createReportFooter( Sink sink ) - { - sink.table_(); - sink.body_(); - } - - /** - * Creates a new facade to invoke JJDoc. Most options for the invocation are derived from the current values of the - * corresponding mojo parameters. The caller is responsible to set the input file and output file on the returned - * facade. - * - * @return The facade for the tool invocation, never null. - */ - private JJDoc newJJDoc() - { - JJDoc jjdoc = new JJDoc(); - jjdoc.setLog( getLog() ); - jjdoc.setGrammarEncoding( this.grammarEncoding ); - jjdoc.setCssHref( this.cssHref ); - jjdoc.setText( this.text ); - jjdoc.setBnf( this.bnf ); - jjdoc.setOneTable(this.oneTable); - return jjdoc; - } - - /** - * Searches the specified source directory to find grammar files that can be documented. - * - * @param sourceDirectory The source directory to scan for grammar files. - * @return An array of grammar infos describing the found grammar files or null if the source - * directory does not exist. - * @throws MavenReportException If there is a problem while scanning for .jj files. - */ - private GrammarInfo[] scanForGrammars( File sourceDirectory ) - throws MavenReportException - { - if ( !sourceDirectory.isDirectory() ) - { - return null; - } - - GrammarInfo[] grammarInfos; - - getLog().debug( "Scanning for grammars: " + sourceDirectory ); - try - { - String[] includes = { "**/*.jj", "**/*.JJ", "**/*.jjt", "**/*.JJT", "**/*.jtb", "**/*.JTB" }; - GrammarDirectoryScanner scanner = new GrammarDirectoryScanner(); - scanner.setSourceDirectory( sourceDirectory ); - scanner.setIncludes( includes ); - scanner.scan(); - grammarInfos = scanner.getIncludedGrammars(); - } - catch ( Exception e ) - { - throw new MavenReportException( "Failed to scan for grammars: " + sourceDirectory, e ); - } - getLog().debug( "Found grammars: " + Arrays.asList( grammarInfos ) ); - - return grammarInfos; - } - - /** - * Get the resource bundle for the report text. - * - * @param locale The locale to use for this report. - * @return The resource bundle. - */ - private ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "jjdoc-report", locale, getClass().getClassLoader() ); - } - - /** - * Compares grammar infos using their relative grammar file paths as the sort key. - */ - private static class GrammarInfoComparator - implements Comparator - { - - /** - * The singleton instance of this comparator. - */ - private static final GrammarInfoComparator INSTANCE = new GrammarInfoComparator(); - - /** - * Gets the singleton instance of this class. - * - * @return The singleton instance of this class. - */ - public static GrammarInfoComparator getInstance() - { - return INSTANCE; - } - - /** - * Compares the path of two grammar files lexicographically. - * - * @param o1 The first grammar info. - * @param o2 The second grammar info. - * @return A negative integer if the first grammar is considered "smaller", a positive integer if it is - * considered "greater" and zero otherwise. - */ - public int compare( GrammarInfo o1, GrammarInfo o2 ) - { - int rel; - - String[] paths1 = o1.getRelativeGrammarFile().split( "\\" + File.separatorChar ); - - String[] paths2 = o2.getRelativeGrammarFile().split( "\\" + File.separatorChar ); - - int dirs = Math.min( paths1.length, paths2.length ) - 1; - for ( int i = 0; i < dirs; i++ ) - { - rel = paths1[i].compareToIgnoreCase( paths2[i] ); - if ( rel != 0 ) - { - return rel; - } - } - - rel = paths1.length - paths2.length; - if ( rel != 0 ) - { - return rel; - } - - return paths1[paths1.length - 1].compareToIgnoreCase( paths2[paths1.length - 1] ); - } - - } - - public void generate(Sink sink, Locale locale) throws MavenReportException { - createReportHeader( getBundle( locale ), sink ); - - File[] sourceDirs = getSourceDirectories(); - for (File sourceDir : sourceDirs) { - GrammarInfo[] grammarInfos = scanForGrammars(sourceDir); - - if (grammarInfos == null) { - getLog().debug("Skipping non-existing source directory: " + sourceDir); - } else { - Arrays.sort(grammarInfos, GrammarInfoComparator.getInstance()); - for (GrammarInfo grammarInfo : grammarInfos) { - File grammarFile = grammarInfo.getGrammarFile(); - - String relativeOutputFileName = grammarInfo.getRelativeGrammarFile(); - relativeOutputFileName = - relativeOutputFileName.replaceAll("(?i)\\.(jj|jjt|jtb)$", getOutputFileExtension()); - - File jjdocOutputFile = new File(getJJDocOutputDirectory(), relativeOutputFileName); - - JJDoc jjdoc = newJJDoc(); - jjdoc.setInputFile(grammarFile); - jjdoc.setOutputFile(jjdocOutputFile); - try { - jjdoc.run(); - } catch (Exception e) { - throw new MavenReportException("Failed to create BNF documentation: " + grammarFile, e); - } - - createReportLink(sink, sourceDir, grammarFile, relativeOutputFileName); - } - } - } - - createReportFooter( sink ); - sink.flush(); - sink.close(); - } - -} +package org.codehaus.mojo.javacc; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.File; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.ResourceBundle; +import java.util.Set; + +import org.apache.maven.doxia.sink.Sink; +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.reporting.AbstractMavenReport; +import org.apache.maven.reporting.MavenReportException; + +/** + * JJDoc takes a JavaCC parser specification and produces + * documentation for the BNF grammar. This mojo will search the source directory for all *.jj files and + * run JJDoc once for each file it finds. Each of these output files, along with an index.html file will + * be placed in the site directory (target/site/jjdoc), and a link will be created in the "Project + * Reports" menu of the generated site. + * + * @since 2.3 + * @author Paul Gier + * @see JJDoc Documentation + */ +@Mojo(name = "jjdoc") +@Execute(phase = LifecyclePhase.GENERATE_SOURCES) +public class JJDocMojo extends AbstractMavenReport { + + // ---------------------------------------------------------------------- + // Mojo Parameters + // ---------------------------------------------------------------------- + + /** + * The directories where the JavaCC grammar files (*.jj) are located. By default, the directories + * ${basedir}/src/main/javacc, ${project.build.directory}/generated-sources/jjtree + * and ${project.build.directory}/generated-sources/jtb are scanned for grammar files to document. + * + */ + @Parameter + private File[] sourceDirectories; + + /** + * The default source directory for hand-crafted grammar files. + * + */ + @Parameter(defaultValue = "${basedir}/src/main/javacc") + private File defaultGrammarDirectoryJavaCC; + + /** + * The default source directory for grammar files generated by JJTree. + * + */ + @Parameter(defaultValue = "${project.build.directory}/generated-sources/jjtree") + private File defaultGrammarDirectoryJJTree; + + /** + * The default source directory for grammar files generated by JTB. + * + */ + @Parameter(defaultValue = "${project.build.directory}/generated-sources/jtb") + private File defaultGrammarDirectoryJTB; + + /** + * The relative path of the JJDoc reports in the output directory. This path will be appended to the output + * directory. + * + */ + @Parameter(defaultValue = "jjdoc") + private String jjdocDirectory; + + /** + * The destination directory where JJDoc saves the generated documentation files. Note that this parameter is only + * relevant if the goal is run from the command line or from the default build lifecycle. If the goal is run + * indirectly as part of a site generation, the output directory configured in the Maven Site Plugin is used + * instead. + * + */ + @Parameter(defaultValue = "${project.reporting.outputDirectory}", property = "javacc.outputDirectory") + private File outputDirectory; + + /** + * The file encoding to use for reading the grammar files. + * + * @since 2.6 + */ + @Parameter(defaultValue = "${project.build.sourceEncoding}", property = "javacc.grammarEncoding") + private String grammarEncoding; + + /** + * The hypertext reference to an optional CSS file for the generated HTML documents. If specified, this CSS file + * will be included via a <link> element in the HTML documents. Otherwise, the default style will + * be used. + * + * @since 2.5 + */ + @Parameter(property = "javacc.cssHref") + private String cssHref; + + /** + * A flag to specify the output format for the generated documentation. If set to true, JJDoc will + * generate a plain text description of the BNF. Some formatting is done via tab characters, but the intention is to + * leave it as plain as possible. Specifying false causes JJDoc to generate a hyperlinked HTML document + * unless the parameter {@link #bnf} has been set to true. Default value is false. + * + */ + @Parameter(property = "javacc.text") + private Boolean text; + + /** + * A flag whether to generate a plain text document with the unformatted BNF. Note that setting this option to + * true is only effective if the parameter {@link #text} is false. Default value is + * false. + * + * @since 2.6 + */ + @Parameter(property = "javacc.bnf") + private Boolean bnf; + + /** + * This option controls the structure of the generated HTML output. If set to true, a single HTML + * table for the entire BNF is generated. Setting it to false will produce one table for every + * production in the grammar. + * + */ + @Parameter(property = "javacc.oneTable", defaultValue = "true") + private boolean oneTable; + + /** + * Get the output directory of the report if run directly from the command line. + * + * @see org.apache.maven.reporting.AbstractMavenReport#getOutputDirectory() + * @return The report output directory. + */ + protected String getOutputDirectory() { + return this.outputDirectory.getAbsolutePath(); + } + + /** + * Get the output directory of the JJDoc files, i.e. the sub directory in the report output directory as specified + * by the {@link #jjdocDirectory} parameter. + * + * @return The report output directory of the JJDoc files. + */ + private File getJJDocOutputDirectory() { + return new File(getReportOutputDirectory(), this.jjdocDirectory); + } + + /** + * Get the source directories that should be scanned for grammar files. + * + * @return The source directories that should be scanned for grammar files, never null. + */ + private File[] getSourceDirectories() { + Set directories = new LinkedHashSet<>(); + if (this.sourceDirectories != null && this.sourceDirectories.length > 0) { + directories.addAll(Arrays.asList(this.sourceDirectories)); + } else { + if (this.defaultGrammarDirectoryJavaCC != null) { + directories.add(this.defaultGrammarDirectoryJavaCC); + } + if (this.defaultGrammarDirectoryJJTree != null) { + directories.add(this.defaultGrammarDirectoryJJTree); + } + if (this.defaultGrammarDirectoryJTB != null) { + directories.add(this.defaultGrammarDirectoryJTB); + } + } + return directories.toArray(new File[0]); + } + + // ---------------------------------------------------------------------- + // public methods + // ---------------------------------------------------------------------- + + /** + * @see org.apache.maven.reporting.MavenReport#getName(java.util.Locale) + * @param locale The locale to use for this report. + * @return The name of this report. + */ + public String getName(Locale locale) { + return getBundle(locale).getString("report.jjdoc.name"); + } + + /** + * @see org.apache.maven.reporting.MavenReport#getDescription(java.util.Locale) + * @param locale The locale to use for this report. + * @return The description of this report. + */ + public String getDescription(Locale locale) { + return getBundle(locale).getString("report.jjdoc.short.description"); + } + + /** + * @see org.apache.maven.reporting.MavenReport#getOutputName() + * @return The name of the main report file. + */ + public String getOutputName() { + return this.jjdocDirectory + "/index"; + } + + /** + * @see org.apache.maven.reporting.MavenReport#canGenerateReport() + * @return true if the configured source directories are not empty, false otherwise. + */ + public boolean canGenerateReport() { + return Arrays.stream(getSourceDirectories()) + .map(File::list) + .anyMatch(files -> files != null && files.length > 0); + } + + /** + * Run the actual report. + * + * @param locale The locale to use for this report. + * @throws MavenReportException If the report generation failed. + */ + public void executeReport(Locale locale) throws MavenReportException { + generate(getSink(), locale); + } + + /** + * The JJDoc output file will have a .html or .txt extension depending on the value of + * the parameters {@link #text} and {@link #bnf}. + * + * @return The file extension (including the leading period) to be used for the JJDoc output files. + */ + private String getOutputFileExtension() { + if (Boolean.TRUE.equals(this.text) || Boolean.TRUE.equals(this.bnf)) { + return ".txt"; + } else { + return ".html"; + } + } + + /** + * Create the header and title for the HTML report page. + * + * @param bundle The resource bundle with the text. + * @param sink The sink for writing to the main report file. + */ + private void createReportHeader(ResourceBundle bundle, Sink sink) { + sink.head(); + sink.title(); + sink.text(bundle.getString("report.jjdoc.title")); + sink.title_(); + sink.head_(); + + sink.body(); + + sink.section1(); + sink.sectionTitle1(); + sink.text(bundle.getString("report.jjdoc.title")); + sink.sectionTitle1_(); + sink.text(bundle.getString("report.jjdoc.description")); + sink.section1_(); + + sink.lineBreak(); + sink.table(); + sink.tableRow(); + sink.tableHeaderCell(); + sink.text(bundle.getString("report.jjdoc.table.heading")); + sink.tableHeaderCell_(); + sink.tableRow_(); + } + + /** + * Create a table row containing a link to the JJDoc report for a grammar file. + * + * @param sink The sink to write the report + * @param sourceDirectory The source directory of the grammar file. + * @param grammarFile The JavaCC grammar file. + * @param linkPath The path to the JJDoc output. + */ + private void createReportLink(Sink sink, File sourceDirectory, File grammarFile, String linkPath) { + sink.tableRow(); + sink.tableCell(); + if (linkPath.startsWith("/")) { + linkPath = linkPath.substring(1); + } + sink.link(linkPath); + String grammarFileRelativePath = + sourceDirectory.toURI().relativize(grammarFile.toURI()).toString(); + if (grammarFileRelativePath.startsWith("/")) { + grammarFileRelativePath = grammarFileRelativePath.substring(1); + } + sink.text(grammarFileRelativePath); + sink.link_(); + sink.tableCell_(); + sink.tableRow_(); + } + + /** + * Create the HTML footer for the report page. + * + * @param sink The sink to write the HTML report page. + */ + private void createReportFooter(Sink sink) { + sink.table_(); + sink.body_(); + } + + /** + * Creates a new facade to invoke JJDoc. Most options for the invocation are derived from the current values of the + * corresponding mojo parameters. The caller is responsible to set the input file and output file on the returned + * facade. + * + * @return The facade for the tool invocation, never null. + */ + private JJDoc newJJDoc() { + JJDoc jjdoc = new JJDoc(); + jjdoc.setLog(getLog()); + jjdoc.setGrammarEncoding(this.grammarEncoding); + jjdoc.setCssHref(this.cssHref); + jjdoc.setText(this.text); + jjdoc.setBnf(this.bnf); + jjdoc.setOneTable(this.oneTable); + return jjdoc; + } + + /** + * Searches the specified source directory to find grammar files that can be documented. + * + * @param sourceDirectory The source directory to scan for grammar files. + * @return An array of grammar infos describing the found grammar files or null if the source + * directory does not exist. + * @throws MavenReportException If there is a problem while scanning for .jj files. + */ + private GrammarInfo[] scanForGrammars(File sourceDirectory) throws MavenReportException { + if (!sourceDirectory.isDirectory()) { + return null; + } + + GrammarInfo[] grammarInfos; + + getLog().debug("Scanning for grammars: " + sourceDirectory); + try { + String[] includes = {"**/*.jj", "**/*.JJ", "**/*.jjt", "**/*.JJT", "**/*.jtb", "**/*.JTB"}; + GrammarDirectoryScanner scanner = new GrammarDirectoryScanner(); + scanner.setSourceDirectory(sourceDirectory); + scanner.setIncludes(includes); + scanner.scan(); + grammarInfos = scanner.getIncludedGrammars(); + } catch (Exception e) { + throw new MavenReportException("Failed to scan for grammars: " + sourceDirectory, e); + } + getLog().debug("Found grammars: " + Arrays.asList(grammarInfos)); + + return grammarInfos; + } + + /** + * Get the resource bundle for the report text. + * + * @param locale The locale to use for this report. + * @return The resource bundle. + */ + private ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle("jjdoc-report", locale, getClass().getClassLoader()); + } + + /** + * Compares grammar infos using their relative grammar file paths as the sort key. + */ + private static class GrammarInfoComparator implements Comparator { + + /** + * The singleton instance of this comparator. + */ + private static final GrammarInfoComparator INSTANCE = new GrammarInfoComparator(); + + /** + * Gets the singleton instance of this class. + * + * @return The singleton instance of this class. + */ + public static GrammarInfoComparator getInstance() { + return INSTANCE; + } + + /** + * Compares the path of two grammar files lexicographically. + * + * @param o1 The first grammar info. + * @param o2 The second grammar info. + * @return A negative integer if the first grammar is considered "smaller", a positive integer if it is + * considered "greater" and zero otherwise. + */ + public int compare(GrammarInfo o1, GrammarInfo o2) { + int rel; + + String[] paths1 = o1.getRelativeGrammarFile().split("\\" + File.separatorChar); + + String[] paths2 = o2.getRelativeGrammarFile().split("\\" + File.separatorChar); + + int dirs = Math.min(paths1.length, paths2.length) - 1; + for (int i = 0; i < dirs; i++) { + rel = paths1[i].compareToIgnoreCase(paths2[i]); + if (rel != 0) { + return rel; + } + } + + rel = paths1.length - paths2.length; + if (rel != 0) { + return rel; + } + + return paths1[paths1.length - 1].compareToIgnoreCase(paths2[paths1.length - 1]); + } + } + + public void generate(Sink sink, Locale locale) throws MavenReportException { + createReportHeader(getBundle(locale), sink); + + File[] sourceDirs = getSourceDirectories(); + for (File sourceDir : sourceDirs) { + GrammarInfo[] grammarInfos = scanForGrammars(sourceDir); + + if (grammarInfos == null) { + getLog().debug("Skipping non-existing source directory: " + sourceDir); + } else { + Arrays.sort(grammarInfos, GrammarInfoComparator.getInstance()); + for (GrammarInfo grammarInfo : grammarInfos) { + File grammarFile = grammarInfo.getGrammarFile(); + + String relativeOutputFileName = grammarInfo.getRelativeGrammarFile(); + relativeOutputFileName = + relativeOutputFileName.replaceAll("(?i)\\.(jj|jjt|jtb)$", getOutputFileExtension()); + + File jjdocOutputFile = new File(getJJDocOutputDirectory(), relativeOutputFileName); + + JJDoc jjdoc = newJJDoc(); + jjdoc.setInputFile(grammarFile); + jjdoc.setOutputFile(jjdocOutputFile); + try { + jjdoc.run(); + } catch (Exception e) { + throw new MavenReportException("Failed to create BNF documentation: " + grammarFile, e); + } + + createReportLink(sink, sourceDir, grammarFile, relativeOutputFileName); + } + } + } + + createReportFooter(sink); + sink.flush(); + sink.close(); + } +} diff --git a/src/main/java/org/codehaus/mojo/javacc/JJTree.java b/src/main/java/org/codehaus/mojo/javacc/JJTree.java index b29d1a9..d06c574 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JJTree.java +++ b/src/main/java/org/codehaus/mojo/javacc/JJTree.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -29,14 +29,12 @@ /** * Provides a facade for the mojos to invoke JJTree. - * + * * @author Benjamin Bentmann * @version $Id$ * @see JJTree Reference */ -class JJTree - extends ToolFacade -{ +class JJTree extends ToolFacade { /** * The input grammar. @@ -135,341 +133,295 @@ class JJTree /** * Sets the absolute path to the grammar file to pass into JJTree for preprocessing. - * + * * @param value The absolute path to the grammar file to pass into JJTree for preprocessing. */ - public void setInputFile( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setInputFile(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.inputFile = value; } /** * Sets the absolute path to the output directory. - * + * * @param value The absolute path to the output directory for the generated grammar file. If this directory does not * exist yet, it is created. Note that this path should already include the desired package hierarchy * because JJTree will not append the required sub directories automatically. */ - public void setOutputDirectory( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setOutputDirectory(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.outputDirectory = value; } /** * Gets the absolute path to the enhanced grammar file generated by JJTree. - * + * * @return The absolute path to the enhanced grammar file generated by JJTree or null if either the * input file or the output directory have not been set. */ - public File getOutputFile() - { + public File getOutputFile() { File outputFile = null; - if ( this.outputDirectory != null && this.inputFile != null ) - { - String fileName = FileUtils.removeExtension( this.inputFile.getName() ) + ".jj"; - outputFile = new File( this.outputDirectory, fileName ); + if (this.outputDirectory != null && this.inputFile != null) { + String fileName = FileUtils.removeExtension(this.inputFile.getName()) + ".jj"; + outputFile = new File(this.outputDirectory, fileName); } return outputFile; } /** * Sets the option GRAMMAR_ENCODING. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setGrammarEncoding( String value ) - { + public void setGrammarEncoding(String value) { this.grammarEncoding = value; } /** * Sets the option JDK_VERSION. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setJdkVersion( String value ) - { + public void setJdkVersion(String value) { this.jdkVersion = value; } /** * Sets the option STATIC. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setStatic( Boolean value ) - { + public void setStatic(Boolean value) { this.isStatic = value; } /** * Sets the option value BUILD_NODE_FILES. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setBuildNodeFiles( Boolean value ) - { + public void setBuildNodeFiles(Boolean value) { this.buildNodeFiles = value; } /** * Sets the option value MULTI. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setMulti( Boolean value ) - { + public void setMulti(Boolean value) { this.multi = value; } /** * Sets the option value NODE_DEFAULT_VOID. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodeDefaultVoid( Boolean value ) - { + public void setNodeDefaultVoid(Boolean value) { this.nodeDefaultVoid = value; } /** * Sets the option value NODE_CLASS. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodeClass( String value ) - { + public void setNodeClass(String value) { this.nodeClass = value; } /** * Sets the option value NODE_FACTORY. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodeFactory( String value ) - { + public void setNodeFactory(String value) { this.nodeFactory = value; } /** * Sets the option value NODE_PACKAGE. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodePackage( String value ) - { + public void setNodePackage(String value) { this.nodePackage = value; } /** * Sets the option value NODE_PREFIX. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodePrefix( String value ) - { + public void setNodePrefix(String value) { this.nodePrefix = value; } /** * Sets the option value NODE_SCOPE_HOOK. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodeScopeHook( Boolean value ) - { + public void setNodeScopeHook(Boolean value) { this.nodeScopeHook = value; } /** * Sets the option value NODE_USES_PARSER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setNodeUsesParser( Boolean value ) - { + public void setNodeUsesParser(Boolean value) { this.nodeUsesParser = value; } /** * Sets the option value TRACK_TOKENS. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setTrackTokens( Boolean value ) - { + public void setTrackTokens(Boolean value) { this.trackTokens = value; } /** * Sets the option value VISITOR. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setVisitor( Boolean value ) - { + public void setVisitor(Boolean value) { this.visitor = value; } /** * Sets the option value VISITOR_DATA_TYPE. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setVisitorDataType( String value ) - { + public void setVisitorDataType(String value) { this.visitorDataType = value; } /** * Sets the option value VISITOR_RETURN_TYPE. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setVisitorReturnType( String value ) - { + public void setVisitorReturnType(String value) { this.visitorReturnType = value; } /** * Sets the option value VISITOR_EXCEPTION. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setVisitorException( String value ) - { + public void setVisitorException(String value) { this.visitorException = value; } /** * {@inheritDoc} */ - protected int execute() - throws Exception - { + protected int execute() throws Exception { String[] args = generateArguments(); - if ( this.outputDirectory != null && !this.outputDirectory.exists() ) - { + if (this.outputDirectory != null && !this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } - return new org.javacc.jjtree.JJTree().main( args ); + return new org.javacc.jjtree.JJTree().main(args); } /** *

Assembles the command line arguments for the invocation of JJTree according to the configuration.

* Note: To prevent conflicts with JavaCC options that might be set directly in the grammar file, * only those parameters that have been explicitly set are passed on the command line. - * + * * @return A string array that represents the arguments to use for JJTree. */ - private String[] generateArguments() - { + private String[] generateArguments() { List argsList = new ArrayList<>(); - if ( StringUtils.isNotEmpty( this.grammarEncoding ) ) - { - argsList.add( "-GRAMMAR_ENCODING=" + this.grammarEncoding ); + if (StringUtils.isNotEmpty(this.grammarEncoding)) { + argsList.add("-GRAMMAR_ENCODING=" + this.grammarEncoding); } - if ( StringUtils.isNotEmpty( jdkVersion ) ) - { - argsList.add( "-JDK_VERSION=" + this.jdkVersion ); + if (StringUtils.isNotEmpty(jdkVersion)) { + argsList.add("-JDK_VERSION=" + this.jdkVersion); } - if ( this.buildNodeFiles != null ) - { - argsList.add( "-BUILD_NODE_FILES=" + this.buildNodeFiles ); + if (this.buildNodeFiles != null) { + argsList.add("-BUILD_NODE_FILES=" + this.buildNodeFiles); } - if ( this.multi != null ) - { - argsList.add( "-MULTI=" + this.multi ); + if (this.multi != null) { + argsList.add("-MULTI=" + this.multi); } - if ( this.nodeDefaultVoid != null ) - { - argsList.add( "-NODE_DEFAULT_VOID=" + this.nodeDefaultVoid ); + if (this.nodeDefaultVoid != null) { + argsList.add("-NODE_DEFAULT_VOID=" + this.nodeDefaultVoid); } - if ( StringUtils.isNotEmpty( this.nodeClass ) ) - { - argsList.add( "-NODE_CLASS=" + this.nodeClass ); + if (StringUtils.isNotEmpty(this.nodeClass)) { + argsList.add("-NODE_CLASS=" + this.nodeClass); } - if ( StringUtils.isNotEmpty( this.nodeFactory ) ) - { - argsList.add( "-NODE_FACTORY=" + this.nodeFactory ); + if (StringUtils.isNotEmpty(this.nodeFactory)) { + argsList.add("-NODE_FACTORY=" + this.nodeFactory); } - if ( StringUtils.isNotEmpty( this.nodePackage ) ) - { - argsList.add( "-NODE_PACKAGE=" + this.nodePackage ); + if (StringUtils.isNotEmpty(this.nodePackage)) { + argsList.add("-NODE_PACKAGE=" + this.nodePackage); } - if ( StringUtils.isNotEmpty( this.nodePrefix ) ) - { - argsList.add( "-NODE_PREFIX=" + this.nodePrefix ); + if (StringUtils.isNotEmpty(this.nodePrefix)) { + argsList.add("-NODE_PREFIX=" + this.nodePrefix); } - if ( this.nodeScopeHook != null ) - { - argsList.add( "-NODE_SCOPE_HOOK=" + this.nodeScopeHook ); + if (this.nodeScopeHook != null) { + argsList.add("-NODE_SCOPE_HOOK=" + this.nodeScopeHook); } - if ( this.nodeUsesParser != null ) - { - argsList.add( "-NODE_USES_PARSER=" + this.nodeUsesParser ); + if (this.nodeUsesParser != null) { + argsList.add("-NODE_USES_PARSER=" + this.nodeUsesParser); } - if ( this.isStatic != null ) - { - argsList.add( "-STATIC=" + this.isStatic ); + if (this.isStatic != null) { + argsList.add("-STATIC=" + this.isStatic); } - if ( this.trackTokens != null ) - { - argsList.add( "-TRACK_TOKENS=" + this.trackTokens ); + if (this.trackTokens != null) { + argsList.add("-TRACK_TOKENS=" + this.trackTokens); } - if ( this.visitor != null ) - { - argsList.add( "-VISITOR=" + this.visitor ); + if (this.visitor != null) { + argsList.add("-VISITOR=" + this.visitor); } - if ( StringUtils.isNotEmpty( this.visitorDataType ) ) - { - argsList.add( "-VISITOR_DATA_TYPE=" + this.visitorDataType ); + if (StringUtils.isNotEmpty(this.visitorDataType)) { + argsList.add("-VISITOR_DATA_TYPE=" + this.visitorDataType); } - if ( StringUtils.isNotEmpty( this.visitorReturnType ) ) - { - argsList.add( "-VISITOR_RETURN_TYPE=" + this.visitorReturnType ); + if (StringUtils.isNotEmpty(this.visitorReturnType)) { + argsList.add("-VISITOR_RETURN_TYPE=" + this.visitorReturnType); } - if ( StringUtils.isNotEmpty( this.visitorException ) ) - { - argsList.add( "-VISITOR_EXCEPTION=" + this.visitorException ); + if (StringUtils.isNotEmpty(this.visitorException)) { + argsList.add("-VISITOR_EXCEPTION=" + this.visitorException); } - if ( this.outputDirectory != null ) - { - argsList.add( "-OUTPUT_DIRECTORY=" + this.outputDirectory.getAbsolutePath() ); + if (this.outputDirectory != null) { + argsList.add("-OUTPUT_DIRECTORY=" + this.outputDirectory.getAbsolutePath()); } - if ( this.inputFile != null ) - { - argsList.add( this.inputFile.getAbsolutePath() ); + if (this.inputFile != null) { + argsList.add(this.inputFile.getAbsolutePath()); } return argsList.toArray(new String[0]); @@ -477,12 +429,10 @@ private String[] generateArguments() /** * Gets a string representation of the command line arguments. - * + * * @return A string representation of the command line arguments. */ - public String toString() - { - return Arrays.asList( generateArguments() ).toString(); + public String toString() { + return Arrays.asList(generateArguments()).toString(); } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JJTreeJavaCCMojo.java b/src/main/java/org/codehaus/mojo/javacc/JJTreeJavaCCMojo.java index 214fbd9..57919e6 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JJTreeJavaCCMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/JJTreeJavaCCMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -30,15 +30,13 @@ /** * Preprocesses decorated grammar files (*.jjt) with JJTree and passes the output to JavaCC in order to * finally generate a parser with parse tree actions. - * + * * @since 2.4 * @author Benjamin Bentmann * */ @Mojo(name = "jjtree-javacc", defaultPhase = LifecyclePhase.GENERATE_SOURCES) -public class JJTreeJavaCCMojo - extends AbstractJavaCCMojo -{ +public class JJTreeJavaCCMojo extends AbstractJavaCCMojo { /** * A flag whether to generate sample implementations for SimpleNode and any other nodes used in the @@ -51,7 +49,7 @@ public class JJTreeJavaCCMojo /** * A flag whether to generate a multi mode parse tree or a single mode parse tree. Default value is * false. - * + * */ @Parameter(property = "javacc.multi") private Boolean multi; @@ -78,7 +76,7 @@ public class JJTreeJavaCCMojo * The name of a custom factory class used to create Node objects. This class must have a method with * the signature public static Node jjtCreate(int id). By default, the class SimpleNode * will be used as the factory class. - * + * */ @Parameter(property = "javacc.nodeFactory") private String nodeFactory; @@ -121,7 +119,7 @@ public class JJTreeJavaCCMojo * A flag whether to insert the methods jjtGetFirstToken(), jjtSetFirstToken(), * getLastToken() and jjtSetLastToken() into the class SimpleNode. Default * value is false. - * + * * @since 2.5 */ @Parameter(property = "javacc.trackTokens") @@ -177,7 +175,9 @@ public class JJTreeJavaCCMojo * compiling and packaging. * */ - @Parameter(property = "javacc.interimDirectory", defaultValue = "${project.build.directory}/generated-sources/jjtree") + @Parameter( + property = "javacc.interimDirectory", + defaultValue = "${project.build.directory}/generated-sources/jjtree") private File interimDirectory; /** @@ -186,7 +186,9 @@ public class JJTreeJavaCCMojo * compiling and packaging. * */ - @Parameter(property = "javacc.outputDirectory", defaultValue = "${project.build.directory}/generated-sources/javacc") + @Parameter( + property = "javacc.outputDirectory", + defaultValue = "${project.build.directory}/generated-sources/javacc") private File outputDirectory; /** @@ -217,147 +219,138 @@ public class JJTreeJavaCCMojo /** * {@inheritDoc} */ - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return this.sourceDirectory; } /** * {@inheritDoc} */ - protected String[] getIncludes() - { - if ( this.includes != null ) - { + protected String[] getIncludes() { + if (this.includes != null) { return this.includes; - } - else - { - return new String[] { "**/*.jj", "**/*.JJ", "**/*.jjt", "**/*.JJT" }; + } else { + return new String[] {"**/*.jj", "**/*.JJ", "**/*.jjt", "**/*.JJT"}; } } /** * {@inheritDoc} */ - protected String[] getExcludes() - { + protected String[] getExcludes() { return this.excludes; } /** * {@inheritDoc} */ - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return this.outputDirectory; } /** * {@inheritDoc} */ - protected int getStaleMillis() - { + protected int getStaleMillis() { return this.staleMillis; } /** * Gets the absolute path to the directory where the interim output from JJTree will be stored. - * + * * @return The absolute path to the directory where the interim output from JJTree will be stored. */ - private File getInterimDirectory() - { + private File getInterimDirectory() { return this.interimDirectory; } /** * {@inheritDoc} */ - protected File[] getCompileSourceRoots() - { - return new File[] { getOutputDirectory(), getInterimDirectory() }; + protected File[] getCompileSourceRoots() { + return new File[] {getOutputDirectory(), getInterimDirectory()}; } /** * {@inheritDoc} */ - protected void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException - { + protected void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException { File jjtFile = grammarInfo.getGrammarFile(); File jjtDirectory = jjtFile.getParentFile(); File tempDirectory = getTempDirectory(); // setup output directory of grammar file (*.jj) and node files (*.java) generated by JJTree - File jjDirectory = new File( tempDirectory, "node" ); + File jjDirectory = new File(tempDirectory, "node"); // setup output directory of parser file (*.java) generated by JavaCC - File parserDirectory = new File( tempDirectory, "parser" ); + File parserDirectory = new File(tempDirectory, "parser"); // setup output directory of tree node files (*.java) generated by JJTree - String nodePackageName = grammarInfo.resolvePackageName( this.nodePackage ); + String nodePackageName = grammarInfo.resolvePackageName(this.nodePackage); // generate final grammar file JJTree jjtree = newJJTree(); - jjtree.setInputFile( jjtFile ); - jjtree.setOutputDirectory( jjDirectory ); - jjtree.setNodePackage( nodePackageName ); + jjtree.setInputFile(jjtFile); + jjtree.setOutputDirectory(jjDirectory); + jjtree.setNodePackage(nodePackageName); jjtree.run(); // generate parser files JavaCC javacc = newJavaCC(); - javacc.setInputFile( jjtree.getOutputFile() ); - javacc.setOutputDirectory( parserDirectory ); + javacc.setInputFile(jjtree.getOutputFile()); + javacc.setOutputDirectory(parserDirectory); javacc.run(); // copy output from JJTree - copyGrammarOutput( getInterimDirectory(), ( nodePackageName != null ) ? nodePackageName - : grammarInfo.getParserPackage(), jjDirectory, grammarInfo.getParserName() + "TreeConstants*" ); + copyGrammarOutput( + getInterimDirectory(), + (nodePackageName != null) ? nodePackageName : grammarInfo.getParserPackage(), + jjDirectory, + grammarInfo.getParserName() + "TreeConstants*"); // copy parser files from JavaCC - copyGrammarOutput( getOutputDirectory(), grammarInfo.getParserPackage(), parserDirectory, - grammarInfo.getParserName() + "*" ); + copyGrammarOutput( + getOutputDirectory(), + grammarInfo.getParserPackage(), + parserDirectory, + grammarInfo.getParserName() + "*"); // copy source files which are next to grammar unless the grammar resides in an ordinary source root // (legacy support for custom sources) - if ( !isSourceRoot( grammarInfo.getSourceDirectory() ) ) - { - copyGrammarOutput( getOutputDirectory(), grammarInfo.getParserPackage(), jjtDirectory, "*" ); + if (!isSourceRoot(grammarInfo.getSourceDirectory())) { + copyGrammarOutput(getOutputDirectory(), grammarInfo.getParserPackage(), jjtDirectory, "*"); } - deleteTempDirectory( tempDirectory ); + deleteTempDirectory(tempDirectory); } /** * Creates a new facade to invoke JJTree. Most options for the invocation are derived from the current values of the * corresponding mojo parameters. The caller is responsible to set the input file, output directory and package on * the returned facade. - * + * * @return The facade for the tool invocation, never null. */ - protected JJTree newJJTree() - { + protected JJTree newJJTree() { JJTree jjtree = new JJTree(); - jjtree.setLog( getLog() ); - jjtree.setGrammarEncoding( getGrammarEncoding() ); - jjtree.setJdkVersion( getJdkVersion() ); - jjtree.setStatic( getIsStatic() ); - jjtree.setBuildNodeFiles( this.buildNodeFiles ); - jjtree.setMulti( this.multi ); - jjtree.setNodeDefaultVoid( this.nodeDefaultVoid ); - jjtree.setNodeClass( this.nodeClass ); - jjtree.setNodeFactory( this.nodeFactory ); - jjtree.setNodePrefix( this.nodePrefix ); - jjtree.setNodeScopeHook( this.nodeScopeHook ); - jjtree.setNodeUsesParser( this.nodeUsesParser ); - jjtree.setTrackTokens( this.trackTokens ); - jjtree.setVisitor( this.visitor ); - jjtree.setVisitorDataType( this.visitorDataType ); - jjtree.setVisitorReturnType( this.visitorReturnType ); - jjtree.setVisitorException( this.visitorException ); + jjtree.setLog(getLog()); + jjtree.setGrammarEncoding(getGrammarEncoding()); + jjtree.setJdkVersion(getJdkVersion()); + jjtree.setStatic(getIsStatic()); + jjtree.setBuildNodeFiles(this.buildNodeFiles); + jjtree.setMulti(this.multi); + jjtree.setNodeDefaultVoid(this.nodeDefaultVoid); + jjtree.setNodeClass(this.nodeClass); + jjtree.setNodeFactory(this.nodeFactory); + jjtree.setNodePrefix(this.nodePrefix); + jjtree.setNodeScopeHook(this.nodeScopeHook); + jjtree.setNodeUsesParser(this.nodeUsesParser); + jjtree.setTrackTokens(this.trackTokens); + jjtree.setVisitor(this.visitor); + jjtree.setVisitorDataType(this.visitorDataType); + jjtree.setVisitorReturnType(this.visitorReturnType); + jjtree.setVisitorException(this.visitorException); return jjtree; } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JJTreeMojo.java b/src/main/java/org/codehaus/mojo/javacc/JJTreeMojo.java index 7d763bc..36691ae 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JJTreeMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/JJTreeMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -37,9 +37,7 @@ * @author jesse jesse.mcconnell@gmail.com */ @Mojo(name = "jjtree", defaultPhase = LifecyclePhase.GENERATE_SOURCES) -public class JJTreeMojo - extends AbstractPreprocessorMojo -{ +public class JJTreeMojo extends AbstractPreprocessorMojo { /** * The Java version for which to generate source code. Default value is 1.4. @@ -52,7 +50,7 @@ public class JJTreeMojo /** * A flag whether to generate sample implementations for SimpleNode and any other nodes used in the * grammar. Default value is true. - * + * */ @Parameter(property = "javacc.buildNodeFiles") private Boolean buildNodeFiles; @@ -105,7 +103,7 @@ public class JJTreeMojo /** * The prefix used to construct node class names from node identifiers in multi mode. Default value is * AST. - * + * */ @Parameter(property = "javacc.nodePrefix") private String nodePrefix; @@ -190,14 +188,18 @@ public class JJTreeMojo * Directory where the output Java files for the node classes and the JavaCC grammar file will be located. * */ - @Parameter(property = "javacc.outputDirectory", defaultValue = "${project.build.directory}/generated-sources/jjtree") + @Parameter( + property = "javacc.outputDirectory", + defaultValue = "${project.build.directory}/generated-sources/jjtree") private File outputDirectory; /** * The directory to store the processed input files for later detection of stale sources. * */ - @Parameter(property = "javacc.timestampDirectory", defaultValue = "${project.build.directory}/generated-sources/jjtree-timestamp") + @Parameter( + property = "javacc.timestampDirectory", + defaultValue = "${project.build.directory}/generated-sources/jjtree-timestamp") private File timestampDirectory; /** @@ -226,116 +228,101 @@ public class JJTreeMojo /** * {@inheritDoc} */ - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return this.sourceDirectory; } /** * {@inheritDoc} */ - protected String[] getIncludes() - { - if ( this.includes != null ) - { + protected String[] getIncludes() { + if (this.includes != null) { return this.includes; - } - else - { - return new String[] { "**/*.jjt", "**/*.JJT" }; + } else { + return new String[] {"**/*.jjt", "**/*.JJT"}; } } /** * {@inheritDoc} */ - protected String[] getExcludes() - { + protected String[] getExcludes() { return this.excludes; } /** * {@inheritDoc} */ - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return this.outputDirectory; } /** * {@inheritDoc} */ - protected File getTimestampDirectory() - { + protected File getTimestampDirectory() { return this.timestampDirectory; } /** * {@inheritDoc} */ - protected int getStaleMillis() - { + protected int getStaleMillis() { return this.staleMillis; } /** * {@inheritDoc} */ - protected void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException - { + protected void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException { File jjtFile = grammarInfo.getGrammarFile(); // determine target directory for tree node files - String nodePackageName = grammarInfo.resolvePackageName( this.nodePackage ); + String nodePackageName = grammarInfo.resolvePackageName(this.nodePackage); File nodeDirectory; - if ( nodePackageName != null ) - { - nodeDirectory = new File( nodePackageName.replace( '.', File.separatorChar ) ); - } - else - { - nodeDirectory = new File( grammarInfo.getParserDirectory() ); + if (nodePackageName != null) { + nodeDirectory = new File(nodePackageName.replace('.', File.separatorChar)); + } else { + nodeDirectory = new File(grammarInfo.getParserDirectory()); } - nodeDirectory = new File( getOutputDirectory(), nodeDirectory.getPath() ); + nodeDirectory = new File(getOutputDirectory(), nodeDirectory.getPath()); // generate final grammar file and node files JJTree jjtree = newJJTree(); - jjtree.setInputFile( jjtFile ); - jjtree.setOutputDirectory( nodeDirectory ); - jjtree.setNodePackage( nodePackageName ); + jjtree.setInputFile(jjtFile); + jjtree.setOutputDirectory(nodeDirectory); + jjtree.setNodePackage(nodePackageName); jjtree.run(); // create timestamp file - createTimestamp( grammarInfo ); + createTimestamp(grammarInfo); } /** * Creates a new facade to invoke JJTree. Most options for the invocation are derived from the current values of the * corresponding mojo parameters. The caller is responsible to set the input file, output directory and package on * the returned facade. - * + * * @return The facade for the tool invocation, never null. */ - protected JJTree newJJTree() - { + protected JJTree newJJTree() { JJTree jjtree = new JJTree(); - jjtree.setLog( getLog() ); - jjtree.setJdkVersion( this.jdkVersion ); - jjtree.setStatic( this.isStatic ); - jjtree.setBuildNodeFiles( this.buildNodeFiles ); - jjtree.setMulti( this.multi ); - jjtree.setNodeDefaultVoid( this.nodeDefaultVoid ); - jjtree.setNodeClass( this.nodeClass ); - jjtree.setNodeFactory( this.nodeFactory ); - jjtree.setNodePrefix( this.nodePrefix ); - jjtree.setNodeScopeHook( this.nodeScopeHook ); - jjtree.setNodeUsesParser( this.nodeUsesParser ); - jjtree.setTrackTokens( this.trackTokens ); - jjtree.setVisitor( this.visitor ); - jjtree.setVisitorDataType( this.visitorDataType ); - jjtree.setVisitorReturnType( this.visitorReturnType ); - jjtree.setVisitorException( this.visitorException ); + jjtree.setLog(getLog()); + jjtree.setJdkVersion(this.jdkVersion); + jjtree.setStatic(this.isStatic); + jjtree.setBuildNodeFiles(this.buildNodeFiles); + jjtree.setMulti(this.multi); + jjtree.setNodeDefaultVoid(this.nodeDefaultVoid); + jjtree.setNodeClass(this.nodeClass); + jjtree.setNodeFactory(this.nodeFactory); + jjtree.setNodePrefix(this.nodePrefix); + jjtree.setNodeScopeHook(this.nodeScopeHook); + jjtree.setNodeUsesParser(this.nodeUsesParser); + jjtree.setTrackTokens(this.trackTokens); + jjtree.setVisitor(this.visitor); + jjtree.setVisitorDataType(this.visitorDataType); + jjtree.setVisitorReturnType(this.visitorReturnType); + jjtree.setVisitorException(this.visitorException); return jjtree; } @@ -343,9 +330,7 @@ protected JJTree newJJTree() * Prevents registration of our output or a following invocation of the javacc mojo will cause duplicate sources * which in turn will make compilation fail. */ - protected void addCompileSourceRoot() - { + protected void addCompileSourceRoot() { // do nothing } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JTB.java b/src/main/java/org/codehaus/mojo/javacc/JTB.java index cca22ae..b988cd4 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JTB.java +++ b/src/main/java/org/codehaus/mojo/javacc/JTB.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -31,14 +31,12 @@ /** * Provides a facade for the mojos to invoke JTB. - * + * * @author Benjamin Bentmann * @version $Id$ * @see Java Tree Builder */ -class JTB - extends ToolFacade -{ +class JTB extends ToolFacade { /** * The default package name for syntax tree files. @@ -127,297 +125,252 @@ class JTB /** * Sets the absolute path to the grammar file to pass into JTB for preprocessing. - * + * * @param value The absolute path to the grammar file to pass into JTB for preprocessing. */ - public void setInputFile( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setInputFile(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.inputFile = value; } /** * Sets the absolute path to the output directory for the generated grammar file. - * + * * @param value The absolute path to the output directory for the generated grammar file. If this directory does not * exist yet, it is created. Note that this path should already include the desired package hierarchy * because JTB will not append the required sub directories automatically. */ - public void setOutputDirectory( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setOutputDirectory(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.outputDirectory = value; } /** * Gets the absolute path to the enhanced grammar file generated by JTB. - * + * * @return The absolute path to the enhanced grammar file generated by JTB or null if either the * input file or the output directory have not been set. */ - public File getOutputFile() - { + public File getOutputFile() { File outputFile = null; - if ( this.outputDirectory != null && this.inputFile != null ) - { - String fileName = FileUtils.removeExtension( this.inputFile.getName() ) + ".jj"; - outputFile = new File( this.outputDirectory, fileName ); + if (this.outputDirectory != null && this.inputFile != null) { + String fileName = FileUtils.removeExtension(this.inputFile.getName()) + ".jj"; + outputFile = new File(this.outputDirectory, fileName); } return outputFile; } /** * Sets the absolute path to the output directory for the syntax tree files. - * + * * @param value The absolute path to the output directory for the generated syntax tree files, may be * null to use a sub directory in the output directory of the grammar file. If this * directory does not exist yet, it is created. Note that this path should already include the desired * package hierarchy because JTB will not append the required sub directories automatically. */ - public void setNodeDirectory( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setNodeDirectory(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.nodeDirectory = value; } /** * Gets the absolute path to the output directory for the syntax tree files. - * + * * @return The absolute path to the output directory for the syntax tree files, only null if neither * {@link #outputDirectory} nor {@link #nodeDirectory} have been set. */ - private File getEffectiveNodeDirectory() - { - if ( this.nodeDirectory != null ) - { + private File getEffectiveNodeDirectory() { + if (this.nodeDirectory != null) { return this.nodeDirectory; - } - else if ( this.outputDirectory != null ) - { - return new File( this.outputDirectory, getLastPackageName( getEffectiveNodePackageName() ) ); + } else if (this.outputDirectory != null) { + return new File(this.outputDirectory, getLastPackageName(getEffectiveNodePackageName())); } return null; } /** * Sets the absolute path to the output directory for the visitor files. - * + * * @param value The absolute path to the output directory for the generated visitor files, may be null * to use a sub directory in the output directory of the grammar file. If this directory does not exist * yet, it is created. Note that this path should already include the desired package hierarchy because * JTB will not append the required sub directories automatically. */ - public void setVisitorDirectory( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setVisitorDirectory(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.visitorDirectory = value; } /** * Gets the absolute path to the output directory for the visitor files. - * + * * @return The absolute path to the output directory for the visitor, only null if neither * {@link #outputDirectory} nor {@link #visitorDirectory} have been set. */ - private File getEffectiveVisitorDirectory() - { - if ( this.visitorDirectory != null ) - { + private File getEffectiveVisitorDirectory() { + if (this.visitorDirectory != null) { return this.visitorDirectory; - } - else if ( this.outputDirectory != null ) - { - return new File( this.outputDirectory, getLastPackageName( getEffectiveVisitorPackageName() ) ); + } else if (this.outputDirectory != null) { + return new File(this.outputDirectory, getLastPackageName(getEffectiveVisitorPackageName())); } return null; } /** * Sets the option "-p". Will overwrite the options "-np" and "-vp" if specified. - * + * * @param value The option value, may be null. */ - public void setPackageName( String value ) - { + public void setPackageName(String value) { this.packageName = value; } /** * Sets the option "-np". - * + * * @param value The option value, may be null. */ - public void setNodePackageName( String value ) - { + public void setNodePackageName(String value) { this.nodePackageName = value; } /** * Gets the effective package name for the syntax tree files. - * + * * @return The effective package name for the syntax tree files, never null. */ - private String getEffectiveNodePackageName() - { - if ( this.packageName != null ) - { + private String getEffectiveNodePackageName() { + if (this.packageName != null) { return (this.packageName.length() == 0) ? SYNTAX_TREE : this.packageName + '.' + SYNTAX_TREE; - } - else if ( this.nodePackageName != null ) - { + } else if (this.nodePackageName != null) { return this.nodePackageName; - } - else - { + } else { return SYNTAX_TREE; } } /** * Sets the option "-vp". - * + * * @param value The option value, may be null. */ - public void setVisitorPackageName( String value ) - { + public void setVisitorPackageName(String value) { this.visitorPackageName = value; } /** * Gets the effective package name for the visitor files. - * + * * @return The effective package name for the visitor files, never null. */ - private String getEffectiveVisitorPackageName() - { - if ( this.packageName != null ) - { + private String getEffectiveVisitorPackageName() { + if (this.packageName != null) { return (this.packageName.length() == 0) ? VISITOR : this.packageName + '.' + VISITOR; - } - else if ( this.visitorPackageName != null ) - { + } else if (this.visitorPackageName != null) { return this.visitorPackageName; - } - else - { + } else { return VISITOR; } } /** * Sets the option "-e". - * + * * @param value The option value, may be null. */ - public void setSupressErrorChecking( Boolean value ) - { + public void setSupressErrorChecking(Boolean value) { this.supressErrorChecking = value; } /** * Sets the option "-jd". - * + * * @param value The option value, may be null. */ - public void setJavadocFriendlyComments( Boolean value ) - { + public void setJavadocFriendlyComments(Boolean value) { this.javadocFriendlyComments = value; } /** * Sets the option "-f". - * + * * @param value The option value, may be null. */ - public void setDescriptiveFieldNames( Boolean value ) - { + public void setDescriptiveFieldNames(Boolean value) { this.descriptiveFieldNames = value; } /** * Sets the option "-ns". - * + * * @param value The option value, may be null. */ - public void setNodeParentClass( String value ) - { + public void setNodeParentClass(String value) { this.nodeParentClass = value; } /** * Sets the option "-pp". - * + * * @param value The option value, may be null. */ - public void setParentPointers( Boolean value ) - { + public void setParentPointers(Boolean value) { this.parentPointers = value; } /** * Sets the option "-tk". - * + * * @param value The option value, may be null. */ - public void setSpecialTokens( Boolean value ) - { + public void setSpecialTokens(Boolean value) { this.specialTokens = value; } /** * Sets the toolkit option "-scheme". - * + * * @param value The option value, may be null. */ - public void setScheme( Boolean value ) - { + public void setScheme(Boolean value) { this.scheme = value; } /** * Sets the toolkit option "-printer". - * + * * @param value The option value, may be null. */ - public void setPrinter( Boolean value ) - { + public void setPrinter(Boolean value) { this.printer = value; } /** * {@inheritDoc} */ - protected int execute() - throws Exception - { + protected int execute() throws Exception { String[] args = generateArguments(); - if ( this.outputDirectory != null && !this.outputDirectory.exists() ) - { + if (this.outputDirectory != null && !this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } // fork JTB because of its lack to re-initialize its static parser ForkedJvm jvm = new ForkedJvm(); - jvm.setMainClass( "EDU.purdue.jtb.JTB" ); - jvm.addArguments( args ); - jvm.setSystemOut( new MojoLogStreamConsumer( false ) ); - jvm.setSystemErr( new MojoLogStreamConsumer( true ) ); - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Forking: " + jvm ); + jvm.setMainClass("EDU.purdue.jtb.JTB"); + jvm.addArguments(args); + jvm.setSystemOut(new MojoLogStreamConsumer(false)); + jvm.setSystemErr(new MojoLogStreamConsumer(true)); + if (getLog().isDebugEnabled()) { + getLog().debug("Forking: " + jvm); } int exitcode = jvm.run(); @@ -428,70 +381,59 @@ protected int execute() /** * Assembles the command line arguments for the invocation of JTB according to the configuration. - * + * * @return A string array that represents the command line arguments to use for JTB. */ - private String[] generateArguments() - { + private String[] generateArguments() { List argsList = new ArrayList<>(); - argsList.add( "-np" ); - argsList.add( getEffectiveNodePackageName() ); + argsList.add("-np"); + argsList.add(getEffectiveNodePackageName()); - argsList.add( "-vp" ); - argsList.add( getEffectiveVisitorPackageName() ); + argsList.add("-vp"); + argsList.add(getEffectiveVisitorPackageName()); - if ( this.supressErrorChecking != null && this.supressErrorChecking) - { - argsList.add( "-e" ); + if (this.supressErrorChecking != null && this.supressErrorChecking) { + argsList.add("-e"); } - if ( this.javadocFriendlyComments != null && this.javadocFriendlyComments) - { - argsList.add( "-jd" ); + if (this.javadocFriendlyComments != null && this.javadocFriendlyComments) { + argsList.add("-jd"); } - if ( this.descriptiveFieldNames != null && this.descriptiveFieldNames) - { - argsList.add( "-f" ); + if (this.descriptiveFieldNames != null && this.descriptiveFieldNames) { + argsList.add("-f"); } - if ( this.nodeParentClass != null ) - { - argsList.add( "-ns" ); - argsList.add( this.nodeParentClass ); + if (this.nodeParentClass != null) { + argsList.add("-ns"); + argsList.add(this.nodeParentClass); } - if ( this.parentPointers != null && this.parentPointers) - { - argsList.add( "-pp" ); + if (this.parentPointers != null && this.parentPointers) { + argsList.add("-pp"); } - if ( this.specialTokens != null && this.specialTokens) - { - argsList.add( "-tk" ); + if (this.specialTokens != null && this.specialTokens) { + argsList.add("-tk"); } - if ( this.scheme != null && this.scheme) - { - argsList.add( "-scheme" ); + if (this.scheme != null && this.scheme) { + argsList.add("-scheme"); } - if ( this.printer != null && this.printer) - { - argsList.add( "-printer" ); + if (this.printer != null && this.printer) { + argsList.add("-printer"); } File outputFile = getOutputFile(); - if ( outputFile != null ) - { - argsList.add( "-o" ); - argsList.add( outputFile.getAbsolutePath() ); + if (outputFile != null) { + argsList.add("-o"); + argsList.add(outputFile.getAbsolutePath()); } - if ( this.inputFile != null ) - { - argsList.add( this.inputFile.getAbsolutePath() ); + if (this.inputFile != null) { + argsList.add(this.inputFile.getAbsolutePath()); } return argsList.toArray(new String[0]); @@ -500,15 +442,13 @@ private String[] generateArguments() /** * Gets the last identifier from the specified package name. For example, returns "apache" upon input of * "org.apache". JTB uses this approach to derive the output directories for the visitor and syntax tree files. - * + * * @param name The package name from which to retrieve the last sub package, may be null. * @return The name of the last sub package or null if the input was null */ - private String getLastPackageName( String name ) - { - if ( name != null ) - { - return name.substring( name.lastIndexOf( '.' ) + 1 ); + private String getLastPackageName(String name) { + if (name != null) { + return name.substring(name.lastIndexOf('.') + 1); } return null; } @@ -517,19 +457,17 @@ private String getLastPackageName( String name ) * Moves the previously generated Java files to their proper target directories. JTB simply assumes that the current * working directory represents the parent package of the configured node/visitor packages which does not meet our * needs. - * + * * @throws IOException If the move failed. */ - private void moveJavaFiles() - throws IOException - { - File nodeSrcDir = new File( getLastPackageName( getEffectiveNodePackageName() ) ).getAbsoluteFile(); + private void moveJavaFiles() throws IOException { + File nodeSrcDir = new File(getLastPackageName(getEffectiveNodePackageName())).getAbsoluteFile(); File nodeDstDir = getEffectiveNodeDirectory(); - moveDirectory( nodeSrcDir, nodeDstDir ); + moveDirectory(nodeSrcDir, nodeDstDir); - File visitorSrcDir = new File( getLastPackageName( getEffectiveVisitorPackageName() ) ).getAbsoluteFile(); + File visitorSrcDir = new File(getLastPackageName(getEffectiveVisitorPackageName())).getAbsoluteFile(); File visitorDstDir = getEffectiveVisitorDirectory(); - moveDirectory( visitorSrcDir, visitorDstDir ); + moveDirectory(visitorSrcDir, visitorDstDir); } /** @@ -538,23 +476,20 @@ private void moveJavaFiles() * copying of sub directories is not supported.

This method must be used instead of * {@link java.io.File#renameTo(java.io.File)} which would fail if the target directory already existed (at least on * Windows). - * + * * @param sourceDir The absolute path to the source directory, must not be null. * @param targetDir The absolute path to the target directory, must not be null. * @throws IOException If the move failed. */ - private void moveDirectory( File sourceDir, File targetDir ) - throws IOException - { - getLog().debug( "Moving JTB output files: " + sourceDir + " -> " + targetDir ); + private void moveDirectory(File sourceDir, File targetDir) throws IOException { + getLog().debug("Moving JTB output files: " + sourceDir + " -> " + targetDir); /* * NOTE: The source directory might be the current working directory if JTB was told to output into the default * package. The current working directory might be quite anything and will likely contain sub directories not * created by JTB. Therefore, we do a defensive move and only delete the expected Java source files. */ File[] sourceFiles = sourceDir.listFiles(); - if ( sourceFiles == null ) - { + if (sourceFiles == null) { return; } for (File sourceFile : sourceFiles) { @@ -569,35 +504,28 @@ private void moveDirectory( File sourceDir, File targetDir ) } } } - if (Objects.requireNonNull(sourceDir.list()).length == 0) - { - if ( !sourceDir.delete() ) - { - getLog().error( "Failed to delete original JTB output directory: " + sourceDir ); + if (Objects.requireNonNull(sourceDir.list()).length == 0) { + if (!sourceDir.delete()) { + getLog().error("Failed to delete original JTB output directory: " + sourceDir); } - } - else - { - getLog().debug( "Keeping non empty JTB output directory: " + sourceDir ); + } else { + getLog().debug("Keeping non empty JTB output directory: " + sourceDir); } } /** * Gets a string representation of the command line arguments. - * + * * @return A string representation of the command line arguments. */ - public String toString() - { - return Arrays.asList( generateArguments() ).toString(); + public String toString() { + return Arrays.asList(generateArguments()).toString(); } /** * Consume and log command line output from the JJDoc process. */ - class MojoLogStreamConsumer - implements StreamConsumer - { + class MojoLogStreamConsumer implements StreamConsumer { /** * The line prefix used by JTB to report infos. @@ -611,38 +539,28 @@ class MojoLogStreamConsumer /** * Single param constructor. - * + * * @param error If set to true, all consumed lines will be logged at the error level. */ - public MojoLogStreamConsumer( boolean error ) - { + public MojoLogStreamConsumer(boolean error) { this.err = error; } /** * Consume a line of text. - * + * * @param line The line to consume. */ - public void consumeLine( String line ) - { - if ( line.startsWith( "JTB version" ) ) - { - getLog().debug( line ); - } - else if ( line.startsWith( INFO_PREFIX ) ) - { - getLog().debug( line.substring( INFO_PREFIX.length() ) ); - } - else if ( this.err && line.length() > 0 ) - { - getLog().error( line ); - } - else - { - getLog().debug( line ); + public void consumeLine(String line) { + if (line.startsWith("JTB version")) { + getLog().debug(line); + } else if (line.startsWith(INFO_PREFIX)) { + getLog().debug(line.substring(INFO_PREFIX.length())); + } else if (this.err && line.length() > 0) { + getLog().error(line); + } else { + getLog().debug(line); } } } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JTBJavaCCMojo.java b/src/main/java/org/codehaus/mojo/javacc/JTBJavaCCMojo.java index 7ab324a..80888f2 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JTBJavaCCMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/JTBJavaCCMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -32,14 +32,12 @@ * finally generate a parser with parse tree actions.

Note: JTB requires Java 1.5 or higher. This goal will not work with earlier * versions of the JRE. - * + * * @since 2.4 * @author Benjamin Bentmann */ @Mojo(name = "jtb-javacc", defaultPhase = LifecyclePhase.GENERATE_SOURCES) -public class JTBJavaCCMojo - extends AbstractJavaCCMojo -{ +public class JTBJavaCCMojo extends AbstractJavaCCMojo { /** * This option is short for nodePackageName = <packageName>.syntaxtree and @@ -158,7 +156,9 @@ public class JTBJavaCCMojo * compiling and packaging. * */ - @Parameter(property = "javacc.outputDirectory", defaultValue = "${project.build.directory}/generated-sources/javacc") + @Parameter( + property = "javacc.outputDirectory", + defaultValue = "${project.build.directory}/generated-sources/javacc") private File outputDirectory; /** @@ -189,165 +189,143 @@ public class JTBJavaCCMojo /** * {@inheritDoc} */ - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return this.sourceDirectory; } /** * {@inheritDoc} */ - protected String[] getIncludes() - { - if ( this.includes != null ) - { + protected String[] getIncludes() { + if (this.includes != null) { return this.includes; - } - else - { - return new String[] { "**/*.jj", "**/*.JJ", "**/*.jtb", "**/*.JTB" }; + } else { + return new String[] {"**/*.jj", "**/*.JJ", "**/*.jtb", "**/*.JTB"}; } } /** * {@inheritDoc} */ - protected String[] getExcludes() - { + protected String[] getExcludes() { return this.excludes; } /** * {@inheritDoc} */ - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return this.outputDirectory; } /** * {@inheritDoc} */ - protected int getStaleMillis() - { + protected int getStaleMillis() { return this.staleMillis; } /** * Gets the absolute path to the directory where the interim output from JTB will be stored. - * + * * @return The absolute path to the directory where the interim output from JTB will be stored. */ - private File getInterimDirectory() - { + private File getInterimDirectory() { return this.interimDirectory; } /** * {@inheritDoc} */ - protected File[] getCompileSourceRoots() - { - return new File[] { getOutputDirectory(), getInterimDirectory() }; + protected File[] getCompileSourceRoots() { + return new File[] {getOutputDirectory(), getInterimDirectory()}; } /** * {@inheritDoc} */ - protected void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException - { + protected void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException { File jtbFile = grammarInfo.getGrammarFile(); File jtbDirectory = jtbFile.getParentFile(); File tempDirectory = getTempDirectory(); // setup output directory of tree node files (*.java) generated by JTB - String nodePackage = grammarInfo.resolvePackageName( getNodePackageName() ); - File nodeDirectory = new File( tempDirectory, "node" ); + String nodePackage = grammarInfo.resolvePackageName(getNodePackageName()); + File nodeDirectory = new File(tempDirectory, "node"); // setup output directory of visitor files (*.java) generated by JTB - String visitorPackage = grammarInfo.resolvePackageName( getVisitorPackageName() ); - File visitorDirectory = new File( tempDirectory, "visitor" ); + String visitorPackage = grammarInfo.resolvePackageName(getVisitorPackageName()); + File visitorDirectory = new File(tempDirectory, "visitor"); // setup output directory of parser file (*.java) generated by JavaCC - File parserDirectory = new File( tempDirectory, "parser" ); + File parserDirectory = new File(tempDirectory, "parser"); // generate final grammar file and the node/visitor files JTB jtb = newJTB(); - jtb.setInputFile( jtbFile ); + jtb.setInputFile(jtbFile); // setup output directory of grammar file (*.jj) generated by JTB jtb.setOutputDirectory(tempDirectory); - jtb.setNodeDirectory( nodeDirectory ); - jtb.setVisitorDirectory( visitorDirectory ); - jtb.setNodePackageName( nodePackage ); - jtb.setVisitorPackageName( visitorPackage ); + jtb.setNodeDirectory(nodeDirectory); + jtb.setVisitorDirectory(visitorDirectory); + jtb.setNodePackageName(nodePackage); + jtb.setVisitorPackageName(visitorPackage); jtb.run(); // generate parser files JavaCC javacc = newJavaCC(); - javacc.setInputFile( jtb.getOutputFile() ); - javacc.setOutputDirectory( parserDirectory ); + javacc.setInputFile(jtb.getOutputFile()); + javacc.setOutputDirectory(parserDirectory); javacc.run(); // copy tree node files from JTB - copyGrammarOutput( getInterimDirectory(), nodePackage, nodeDirectory, "!Node*" ); + copyGrammarOutput(getInterimDirectory(), nodePackage, nodeDirectory, "!Node*"); // copy visitor files from JTB - copyGrammarOutput( getInterimDirectory(), visitorPackage, visitorDirectory, "" ); + copyGrammarOutput(getInterimDirectory(), visitorPackage, visitorDirectory, ""); // copy parser files from JavaCC - copyGrammarOutput( getOutputDirectory(), grammarInfo.getParserPackage(), parserDirectory, - grammarInfo.getParserName() + "*" ); + copyGrammarOutput( + getOutputDirectory(), + grammarInfo.getParserPackage(), + parserDirectory, + grammarInfo.getParserName() + "*"); // copy source files which are next to grammar unless the grammar resides in an ordinary source root // (legacy support for custom sources) - if ( !isSourceRoot( grammarInfo.getSourceDirectory() ) ) - { - copyGrammarOutput( getOutputDirectory(), grammarInfo.getParserPackage(), jtbDirectory, "*" ); + if (!isSourceRoot(grammarInfo.getSourceDirectory())) { + copyGrammarOutput(getOutputDirectory(), grammarInfo.getParserPackage(), jtbDirectory, "*"); } - deleteTempDirectory( tempDirectory ); + deleteTempDirectory(tempDirectory); } /** * Gets the effective package name for the AST node files. - * + * * @return The effective package name for the AST node files, never null. */ - private String getNodePackageName() - { - if ( this.packageName != null ) - { + private String getNodePackageName() { + if (this.packageName != null) { return this.packageName + ".syntaxtree"; - } - else if ( this.nodePackageName != null ) - { + } else if (this.nodePackageName != null) { return this.nodePackageName; - } - else - { + } else { return "*.syntaxtree"; } } /** * Gets the effective package name for the visitor files. - * + * * @return The effective package name for the visitor files, never null. */ - private String getVisitorPackageName() - { - if ( this.packageName != null ) - { + private String getVisitorPackageName() { + if (this.packageName != null) { return this.packageName + ".visitor"; - } - else if ( this.visitorPackageName != null ) - { + } else if (this.visitorPackageName != null) { return this.visitorPackageName; - } - else - { + } else { return "*.visitor"; } } @@ -356,22 +334,20 @@ else if ( this.visitorPackageName != null ) * Creates a new facade to invoke JTB. Most options for the invocation are derived from the current values of the * corresponding mojo parameters. The caller is responsible to set the input file, output directories and packages * on the returned facade. - * + * * @return The facade for the tool invocation, never null. */ - private JTB newJTB() - { + private JTB newJTB() { JTB jtb = new JTB(); - jtb.setLog( getLog() ); - jtb.setDescriptiveFieldNames( this.descriptiveFieldNames ); - jtb.setJavadocFriendlyComments( this.javadocFriendlyComments ); - jtb.setNodeParentClass( this.nodeParentClass ); - jtb.setParentPointers( this.parentPointers ); - jtb.setPrinter( this.printer ); - jtb.setScheme( this.scheme ); - jtb.setSpecialTokens( this.specialTokens ); - jtb.setSupressErrorChecking( this.supressErrorChecking ); + jtb.setLog(getLog()); + jtb.setDescriptiveFieldNames(this.descriptiveFieldNames); + jtb.setJavadocFriendlyComments(this.javadocFriendlyComments); + jtb.setNodeParentClass(this.nodeParentClass); + jtb.setParentPointers(this.parentPointers); + jtb.setPrinter(this.printer); + jtb.setScheme(this.scheme); + jtb.setSpecialTokens(this.specialTokens); + jtb.setSupressErrorChecking(this.supressErrorChecking); return jtb; } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JTBMojo.java b/src/main/java/org/codehaus/mojo/javacc/JTBMojo.java index b832dda..55c6803 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JTBMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/JTBMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -31,16 +31,14 @@ * Parses a JTB file and transforms it into source files for an AST and a JavaCC grammar file which automatically builds * the AST.Note: JTB requires Java 1.5 * or higher. This goal will not work with earlier versions of the JRE. - * + * * @since 2.2 * @deprecated As of version 2.4, use the jtb-javacc goal instead. * @author Gregory Kick (gk5885@kickstyle.net) * */ @Mojo(name = "jtb", defaultPhase = LifecyclePhase.GENERATE_SOURCES) -public class JTBMojo - extends AbstractPreprocessorMojo -{ +public class JTBMojo extends AbstractPreprocessorMojo { /** * This option is short for nodePackageName = <packageName>.syntaxtree and @@ -154,7 +152,9 @@ public class JTBMojo * The directory to store the processed input files for later detection of stale sources. * */ - @Parameter(property = "javacc.timestampDirectory", defaultValue = "${project.build.directory}/generated-sources/jtb-timestamp") + @Parameter( + property = "javacc.timestampDirectory", + defaultValue = "${project.build.directory}/generated-sources/jtb-timestamp") private File timestampDirectory; /** @@ -183,125 +183,102 @@ public class JTBMojo /** * {@inheritDoc} */ - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return this.sourceDirectory; } /** * {@inheritDoc} */ - protected String[] getIncludes() - { - if ( this.includes != null ) - { + protected String[] getIncludes() { + if (this.includes != null) { return this.includes; - } - else - { - return new String[] { "**/*.jtb", "**/*.JTB" }; + } else { + return new String[] {"**/*.jtb", "**/*.JTB"}; } } /** * {@inheritDoc} */ - protected String[] getExcludes() - { + protected String[] getExcludes() { return this.excludes; } /** * {@inheritDoc} */ - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return this.outputDirectory; } /** * {@inheritDoc} */ - protected File getTimestampDirectory() - { + protected File getTimestampDirectory() { return this.timestampDirectory; } /** * {@inheritDoc} */ - protected int getStaleMillis() - { + protected int getStaleMillis() { return this.staleMillis; } /** * {@inheritDoc} */ - protected void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException - { + protected void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException { File jtbFile = grammarInfo.getGrammarFile(); - File jjDirectory = new File( getOutputDirectory(), grammarInfo.getParserDirectory() ); + File jjDirectory = new File(getOutputDirectory(), grammarInfo.getParserDirectory()); - String nodePackage = grammarInfo.resolvePackageName( getNodePackageName() ); - File nodeDirectory = new File( getOutputDirectory(), nodePackage.replace( '.', File.separatorChar ) ); + String nodePackage = grammarInfo.resolvePackageName(getNodePackageName()); + File nodeDirectory = new File(getOutputDirectory(), nodePackage.replace('.', File.separatorChar)); - String visitorPackage = grammarInfo.resolvePackageName( getVisitorPackageName() ); - File visitorDirectory = new File( getOutputDirectory(), visitorPackage.replace( '.', File.separatorChar ) ); + String visitorPackage = grammarInfo.resolvePackageName(getVisitorPackageName()); + File visitorDirectory = new File(getOutputDirectory(), visitorPackage.replace('.', File.separatorChar)); // generate final grammar file and the node/visitor files JTB jtb = newJTB(); - jtb.setInputFile( jtbFile ); - jtb.setOutputDirectory( jjDirectory ); - jtb.setNodeDirectory( nodeDirectory ); - jtb.setVisitorDirectory( visitorDirectory ); - jtb.setNodePackageName( nodePackage ); - jtb.setVisitorPackageName( visitorPackage ); + jtb.setInputFile(jtbFile); + jtb.setOutputDirectory(jjDirectory); + jtb.setNodeDirectory(nodeDirectory); + jtb.setVisitorDirectory(visitorDirectory); + jtb.setNodePackageName(nodePackage); + jtb.setVisitorPackageName(visitorPackage); jtb.run(); // create timestamp file - createTimestamp( grammarInfo ); + createTimestamp(grammarInfo); } /** * Gets the effective package name for the AST node files. - * + * * @return The effective package name for the AST node files, never null. */ - private String getNodePackageName() - { - if ( this.packageName != null ) - { + private String getNodePackageName() { + if (this.packageName != null) { return this.packageName + ".syntaxtree"; - } - else if ( this.nodePackageName != null ) - { + } else if (this.nodePackageName != null) { return this.nodePackageName; - } - else - { + } else { return "*.syntaxtree"; } } /** * Gets the effective package name for the visitor files. - * + * * @return The effective package name for the visitor files, never null. */ - private String getVisitorPackageName() - { - if ( this.packageName != null ) - { + private String getVisitorPackageName() { + if (this.packageName != null) { return this.packageName + ".visitor"; - } - else if ( this.visitorPackageName != null ) - { + } else if (this.visitorPackageName != null) { return this.visitorPackageName; - } - else - { + } else { return "*.visitor"; } } @@ -310,22 +287,20 @@ else if ( this.visitorPackageName != null ) * Creates a new facade to invoke JTB. Most options for the invocation are derived from the current values of the * corresponding mojo parameters. The caller is responsible to set the input file, output directories and packages * on the returned facade. - * + * * @return The facade for the tool invocation, never null. */ - private JTB newJTB() - { + private JTB newJTB() { JTB jtb = new JTB(); - jtb.setLog( getLog() ); - jtb.setDescriptiveFieldNames( this.descriptiveFieldNames ); - jtb.setJavadocFriendlyComments( this.javadocFriendlyComments ); - jtb.setNodeParentClass( this.nodeParentClass ); - jtb.setParentPointers( this.parentPointers ); - jtb.setPrinter( this.printer ); - jtb.setScheme( this.scheme ); - jtb.setSpecialTokens( this.specialTokens ); - jtb.setSupressErrorChecking( this.supressErrorChecking ); + jtb.setLog(getLog()); + jtb.setDescriptiveFieldNames(this.descriptiveFieldNames); + jtb.setJavadocFriendlyComments(this.javadocFriendlyComments); + jtb.setNodeParentClass(this.nodeParentClass); + jtb.setParentPointers(this.parentPointers); + jtb.setPrinter(this.printer); + jtb.setScheme(this.scheme); + jtb.setSpecialTokens(this.specialTokens); + jtb.setSupressErrorChecking(this.supressErrorChecking); return jtb; } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JavaCC.java b/src/main/java/org/codehaus/mojo/javacc/JavaCC.java index 7992978..b7f119f 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JavaCC.java +++ b/src/main/java/org/codehaus/mojo/javacc/JavaCC.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -28,14 +28,12 @@ /** * Provides a facade for the mojos to invoke JavaCC. - * + * * @author Benjamin Bentmann * @version $Id$ * @see JavaCC Command Line Syntax */ -class JavaCC - extends ToolFacade -{ +class JavaCC extends ToolFacade { /** * The input grammar. @@ -179,459 +177,397 @@ class JavaCC /** * Sets the absolute path to the grammar file to pass into JavaCC for compilation. - * + * * @param value The absolute path to the grammar file to pass into JavaCC for compilation. */ - public void setInputFile( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setInputFile(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.inputFile = value; } /** * Sets the absolute path to the output directory. - * + * * @param value The absolute path to the output directory for the generated parser file. If this directory does not * exist yet, it is created. Note that this path should already include the desired package hierarchy * because JavaCC will not append the required sub directories automatically. */ - public void setOutputDirectory( File value ) - { - if ( value != null && !value.isAbsolute() ) - { - throw new IllegalArgumentException( "path is not absolute: " + value ); + public void setOutputDirectory(File value) { + if (value != null && !value.isAbsolute()) { + throw new IllegalArgumentException("path is not absolute: " + value); } this.outputDirectory = value; } /** * Sets the option GRAMMAR_ENCODING. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setGrammarEncoding( String value ) - { + public void setGrammarEncoding(String value) { this.grammarEncoding = value; } /** * Sets the option JDK_VERSION. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setJdkVersion( String value ) - { + public void setJdkVersion(String value) { this.jdkVersion = value; } /** * Sets the option STATIC. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setStatic( Boolean value ) - { + public void setStatic(Boolean value) { this.isStatic = value; } /** * Sets the option LOOK_AHEAD. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setLookAhead( Integer value ) - { + public void setLookAhead(Integer value) { this.lookAhead = value; } /** * Sets the option CHOICE_AMBIGUITY_CHECK. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setChoiceAmbiguityCheck( Integer value ) - { + public void setChoiceAmbiguityCheck(Integer value) { this.choiceAmbiguityCheck = value; } /** * Sets the option OTHER_AMBIGUITY_CHECK. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setOtherAmbiguityCheck( Integer value ) - { + public void setOtherAmbiguityCheck(Integer value) { this.otherAmbiguityCheck = value; } /** * Sets the option DEBUG_PARSER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setDebugParser( Boolean value ) - { + public void setDebugParser(Boolean value) { this.debugParser = value; } /** * Sets the option DEBUG_LOOK_AHEAD. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setDebugLookAhead( Boolean value ) - { + public void setDebugLookAhead(Boolean value) { this.debugLookAhead = value; } /** * Sets the option DEBUG_TOKEN_MANAGER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setDebugTokenManager( Boolean value ) - { + public void setDebugTokenManager(Boolean value) { this.debugTokenManager = value; } /** * Sets the option ERROR_REPORTING. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setErrorReporting( Boolean value ) - { + public void setErrorReporting(Boolean value) { this.errorReporting = value; } /** * Sets the option JAVA_UNICODE_ESCAPE. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setJavaUnicodeEscape( Boolean value ) - { + public void setJavaUnicodeEscape(Boolean value) { this.javaUnicodeEscape = value; } /** * Sets the option UNICODE_INPUT. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setUnicodeInput( Boolean value ) - { + public void setUnicodeInput(Boolean value) { this.unicodeInput = value; } /** * Sets the option IGNORE_CASE. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setIgnoreCase( Boolean value ) - { + public void setIgnoreCase(Boolean value) { this.ignoreCase = value; } /** * Sets the option COMMON_TOKEN_ACTION. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setCommonTokenAction( Boolean value ) - { + public void setCommonTokenAction(Boolean value) { this.commonTokenAction = value; } /** * Sets the option USER_TOKEN_MANAGER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setUserTokenManager( Boolean value ) - { + public void setUserTokenManager(Boolean value) { this.userTokenManager = value; } /** * Sets the option USER_CHAR_STREAM. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setUserCharStream( Boolean value ) - { + public void setUserCharStream(Boolean value) { this.userCharStream = value; } /** * Sets the option BUILD_PARSER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setBuildParser( Boolean value ) - { + public void setBuildParser(Boolean value) { this.buildParser = value; } /** * Sets the option BUILD_TOKEN_MANAGER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setBuildTokenManager( Boolean value ) - { + public void setBuildTokenManager(Boolean value) { this.buildTokenManager = value; } /** * Sets the option TOKEN_MANAGER_USES_PARSER. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setTokenManagerUsesParser( Boolean value ) - { + public void setTokenManagerUsesParser(Boolean value) { this.tokenManagerUsesParser = value; } /** * Sets the option TOKEN_EXTENDS. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setTokenExtends( String value ) - { + public void setTokenExtends(String value) { this.tokenExtends = value; } /** * Sets the option TOKEN_FACTORY. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setTokenFactory( String value ) - { + public void setTokenFactory(String value) { this.tokenFactory = value; } /** * Sets the option SANITY_CHECK. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setSanityCheck( Boolean value ) - { + public void setSanityCheck(Boolean value) { this.sanityCheck = value; } /** * Sets the option FORCE_LA_CHECK. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setForceLaCheck( Boolean value ) - { + public void setForceLaCheck(Boolean value) { this.forceLaCheck = value; } /** * Sets the option CACHE_TOKENS. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setCacheTokens( Boolean value ) - { + public void setCacheTokens(Boolean value) { this.cacheTokens = value; } /** * Sets the option KEEP_LINE_COLUMN. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setKeepLineColumn( Boolean value ) - { + public void setKeepLineColumn(Boolean value) { this.keepLineColumn = value; } /** * Sets the option SUPPORT_CLASS_VISIBILITY_PUBLIC. - * + * * @param value The option value, may be null to use the value provided in the grammar or the default. */ - public void setSupportClassVisibilityPublic( Boolean value ) - { + public void setSupportClassVisibilityPublic(Boolean value) { this.supportClassVisibilityPublic = value; } /** * {@inheritDoc} */ - protected int execute() - throws Exception - { + protected int execute() throws Exception { String[] args = generateArguments(); - if ( this.outputDirectory != null && !this.outputDirectory.exists() ) - { + if (this.outputDirectory != null && !this.outputDirectory.exists()) { this.outputDirectory.mkdirs(); } - return org.javacc.parser.Main.mainProgram( args ); + return org.javacc.parser.Main.mainProgram(args); } /** *

Assembles the command line arguments for the invocation of JavaCC according to the configuration.

* Note: To prevent conflicts with JavaCC options that might be set directly in the grammar file, * only those parameters that have been explicitly set are passed on the command line. - * + * * @return A string array that represents the command line arguments to use for JavaCC. */ - private String[] generateArguments() - { + private String[] generateArguments() { List argsList = new ArrayList<>(); - if ( StringUtils.isNotEmpty( this.grammarEncoding ) ) - { - argsList.add( "-GRAMMAR_ENCODING=" + this.grammarEncoding ); + if (StringUtils.isNotEmpty(this.grammarEncoding)) { + argsList.add("-GRAMMAR_ENCODING=" + this.grammarEncoding); } - if ( StringUtils.isNotEmpty( this.jdkVersion ) ) - { - argsList.add( "-JDK_VERSION=" + this.jdkVersion ); + if (StringUtils.isNotEmpty(this.jdkVersion)) { + argsList.add("-JDK_VERSION=" + this.jdkVersion); } - if ( this.lookAhead != null ) - { - argsList.add( "-LOOKAHEAD=" + this.lookAhead ); + if (this.lookAhead != null) { + argsList.add("-LOOKAHEAD=" + this.lookAhead); } - if ( this.choiceAmbiguityCheck != null ) - { - argsList.add( "-CHOICE_AMBIGUITY_CHECK=" + this.choiceAmbiguityCheck ); + if (this.choiceAmbiguityCheck != null) { + argsList.add("-CHOICE_AMBIGUITY_CHECK=" + this.choiceAmbiguityCheck); } - if ( this.otherAmbiguityCheck != null ) - { - argsList.add( "-OTHER_AMBIGUITY_CHECK=" + this.otherAmbiguityCheck ); + if (this.otherAmbiguityCheck != null) { + argsList.add("-OTHER_AMBIGUITY_CHECK=" + this.otherAmbiguityCheck); } - if ( this.isStatic != null ) - { - argsList.add( "-STATIC=" + this.isStatic ); + if (this.isStatic != null) { + argsList.add("-STATIC=" + this.isStatic); } - if ( this.debugParser != null ) - { - argsList.add( "-DEBUG_PARSER=" + this.debugParser ); + if (this.debugParser != null) { + argsList.add("-DEBUG_PARSER=" + this.debugParser); } - if ( this.debugLookAhead != null ) - { - argsList.add( "-DEBUG_LOOKAHEAD=" + this.debugLookAhead ); + if (this.debugLookAhead != null) { + argsList.add("-DEBUG_LOOKAHEAD=" + this.debugLookAhead); } - if ( this.debugTokenManager != null ) - { - argsList.add( "-DEBUG_TOKEN_MANAGER=" + this.debugTokenManager ); + if (this.debugTokenManager != null) { + argsList.add("-DEBUG_TOKEN_MANAGER=" + this.debugTokenManager); } - if ( this.errorReporting != null ) - { - argsList.add( "-ERROR_REPORTING=" + this.errorReporting ); + if (this.errorReporting != null) { + argsList.add("-ERROR_REPORTING=" + this.errorReporting); } - if ( this.javaUnicodeEscape != null ) - { - argsList.add( "-JAVA_UNICODE_ESCAPE=" + this.javaUnicodeEscape ); + if (this.javaUnicodeEscape != null) { + argsList.add("-JAVA_UNICODE_ESCAPE=" + this.javaUnicodeEscape); } - if ( this.unicodeInput != null ) - { - argsList.add( "-UNICODE_INPUT=" + this.unicodeInput ); + if (this.unicodeInput != null) { + argsList.add("-UNICODE_INPUT=" + this.unicodeInput); } - if ( this.ignoreCase != null ) - { - argsList.add( "-IGNORE_CASE=" + this.ignoreCase ); + if (this.ignoreCase != null) { + argsList.add("-IGNORE_CASE=" + this.ignoreCase); } - if ( this.commonTokenAction != null ) - { - argsList.add( "-COMMON_TOKEN_ACTION=" + this.commonTokenAction ); + if (this.commonTokenAction != null) { + argsList.add("-COMMON_TOKEN_ACTION=" + this.commonTokenAction); } - if ( this.userTokenManager != null ) - { - argsList.add( "-USER_TOKEN_MANAGER=" + this.userTokenManager ); + if (this.userTokenManager != null) { + argsList.add("-USER_TOKEN_MANAGER=" + this.userTokenManager); } - if ( this.userCharStream != null ) - { - argsList.add( "-USER_CHAR_STREAM=" + this.userCharStream ); + if (this.userCharStream != null) { + argsList.add("-USER_CHAR_STREAM=" + this.userCharStream); } - if ( this.buildParser != null ) - { - argsList.add( "-BUILD_PARSER=" + this.buildParser ); + if (this.buildParser != null) { + argsList.add("-BUILD_PARSER=" + this.buildParser); } - if ( this.buildTokenManager != null ) - { - argsList.add( "-BUILD_TOKEN_MANAGER=" + this.buildTokenManager ); + if (this.buildTokenManager != null) { + argsList.add("-BUILD_TOKEN_MANAGER=" + this.buildTokenManager); } - if ( this.tokenManagerUsesParser != null ) - { - argsList.add( "-TOKEN_MANAGER_USES_PARSER=" + this.tokenManagerUsesParser ); + if (this.tokenManagerUsesParser != null) { + argsList.add("-TOKEN_MANAGER_USES_PARSER=" + this.tokenManagerUsesParser); } - if ( StringUtils.isNotEmpty( this.tokenExtends ) ) - { - argsList.add( "-TOKEN_EXTENDS=" + this.tokenExtends ); + if (StringUtils.isNotEmpty(this.tokenExtends)) { + argsList.add("-TOKEN_EXTENDS=" + this.tokenExtends); } - if ( StringUtils.isNotEmpty( this.tokenFactory ) ) - { - argsList.add( "-TOKEN_FACTORY=" + this.tokenFactory ); + if (StringUtils.isNotEmpty(this.tokenFactory)) { + argsList.add("-TOKEN_FACTORY=" + this.tokenFactory); } - if ( this.sanityCheck != null ) - { - argsList.add( "-SANITY_CHECK=" + this.sanityCheck ); + if (this.sanityCheck != null) { + argsList.add("-SANITY_CHECK=" + this.sanityCheck); } - if ( this.forceLaCheck != null ) - { - argsList.add( "-FORCE_LA_CHECK=" + this.forceLaCheck ); + if (this.forceLaCheck != null) { + argsList.add("-FORCE_LA_CHECK=" + this.forceLaCheck); } - if ( this.cacheTokens != null ) - { - argsList.add( "-CACHE_TOKENS=" + this.cacheTokens ); + if (this.cacheTokens != null) { + argsList.add("-CACHE_TOKENS=" + this.cacheTokens); } - if ( this.keepLineColumn != null ) - { - argsList.add( "-KEEP_LINE_COLUMN=" + this.keepLineColumn ); + if (this.keepLineColumn != null) { + argsList.add("-KEEP_LINE_COLUMN=" + this.keepLineColumn); } - if ( this.supportClassVisibilityPublic != null ) - { - argsList.add( "-SUPPORT_CLASS_VISIBILITY_PUBLIC=" + this.supportClassVisibilityPublic ); + if (this.supportClassVisibilityPublic != null) { + argsList.add("-SUPPORT_CLASS_VISIBILITY_PUBLIC=" + this.supportClassVisibilityPublic); } - if ( this.outputDirectory != null ) - { - argsList.add( "-OUTPUT_DIRECTORY=" + this.outputDirectory.getAbsolutePath() ); + if (this.outputDirectory != null) { + argsList.add("-OUTPUT_DIRECTORY=" + this.outputDirectory.getAbsolutePath()); } - if ( this.inputFile != null ) - { - argsList.add( this.inputFile.getAbsolutePath() ); + if (this.inputFile != null) { + argsList.add(this.inputFile.getAbsolutePath()); } return argsList.toArray(new String[0]); @@ -639,12 +575,10 @@ private String[] generateArguments() /** * Gets a string representation of the command line arguments. - * + * * @return A string representation of the command line arguments. */ - public String toString() - { - return Arrays.asList( generateArguments() ).toString(); + public String toString() { + return Arrays.asList(generateArguments()).toString(); } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/JavaCCMojo.java b/src/main/java/org/codehaus/mojo/javacc/JavaCCMojo.java index 38b1159..e53136a 100644 --- a/src/main/java/org/codehaus/mojo/javacc/JavaCCMojo.java +++ b/src/main/java/org/codehaus/mojo/javacc/JavaCCMojo.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -30,16 +30,14 @@ /** * Parses a JavaCC grammar file (*.jj) and transforms it to Java source files. Detailed information * about the JavaCC options can be found on the JavaCC website. - * + * * @since 2.0 * @author jruiz@exist.com * @author jesse jesse.mcconnell@gmail.com * */ @Mojo(name = "javacc", defaultPhase = LifecyclePhase.GENERATE_SOURCES) -public class JavaCCMojo - extends AbstractJavaCCMojo -{ +public class JavaCCMojo extends AbstractJavaCCMojo { /** * Package into which the generated classes will be put. Note that this will also be used to create the directory @@ -63,7 +61,9 @@ public class JavaCCMojo * compiling and packaging. * */ - @Parameter(property = "javacc.outputDirectory", defaultValue = "${project.build.directory}/generated-sources/javacc") + @Parameter( + property = "javacc.outputDirectory", + defaultValue = "${project.build.directory}/generated-sources/javacc") private File outputDirectory; /** @@ -92,98 +92,87 @@ public class JavaCCMojo /** * {@inheritDoc} */ - protected File getSourceDirectory() - { + protected File getSourceDirectory() { return this.sourceDirectory; } /** * {@inheritDoc} */ - protected String[] getIncludes() - { - if ( this.includes != null ) - { + protected String[] getIncludes() { + if (this.includes != null) { return this.includes; - } - else - { - return new String[] { "**/*.jj", "**/*.JJ" }; + } else { + return new String[] {"**/*.jj", "**/*.JJ"}; } } /** * {@inheritDoc} */ - protected String[] getExcludes() - { + protected String[] getExcludes() { return this.excludes; } /** * {@inheritDoc} */ - protected File getOutputDirectory() - { + protected File getOutputDirectory() { return this.outputDirectory; } /** * {@inheritDoc} */ - protected int getStaleMillis() - { + protected int getStaleMillis() { return this.staleMillis; } /** * {@inheritDoc} */ - protected File[] getCompileSourceRoots() - { - return new File[] { getOutputDirectory() }; + protected File[] getCompileSourceRoots() { + return new File[] {getOutputDirectory()}; } /** * {@inheritDoc} */ - protected String getParserPackage() - { + protected String getParserPackage() { return this.packageName; } /** * {@inheritDoc} */ - protected void processGrammar( GrammarInfo grammarInfo ) - throws MojoExecutionException, MojoFailureException - { + protected void processGrammar(GrammarInfo grammarInfo) throws MojoExecutionException, MojoFailureException { File jjFile = grammarInfo.getGrammarFile(); File jjDirectory = jjFile.getParentFile(); File tempDirectory = getTempDirectory(); // setup output directory of parser file (*.java) generated by JavaCC - File parserDirectory = new File( tempDirectory, "parser" ); + File parserDirectory = new File(tempDirectory, "parser"); // generate parser files JavaCC javacc = newJavaCC(); - javacc.setInputFile( jjFile ); - javacc.setOutputDirectory( parserDirectory ); + javacc.setInputFile(jjFile); + javacc.setOutputDirectory(parserDirectory); javacc.run(); // copy parser files from JavaCC - copyGrammarOutput( getOutputDirectory(), grammarInfo.getParserPackage(), parserDirectory, - grammarInfo.getParserName() + "*" ); + copyGrammarOutput( + getOutputDirectory(), + grammarInfo.getParserPackage(), + parserDirectory, + grammarInfo.getParserName() + "*"); // copy source files which are next to grammar unless the grammar resides in an ordinary source root // (legacy support for custom sources) - if ( !isSourceRoot( grammarInfo.getSourceDirectory() ) ) - { - copyGrammarOutput( getOutputDirectory(), grammarInfo.getParserPackage(), jjDirectory, "*" ); + if (!isSourceRoot(grammarInfo.getSourceDirectory())) { + copyGrammarOutput(getOutputDirectory(), grammarInfo.getParserPackage(), jjDirectory, "*"); } - deleteTempDirectory( tempDirectory ); + deleteTempDirectory(tempDirectory); } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/LegacyGrammarDirectoryScanner.java b/src/main/java/org/codehaus/mojo/javacc/LegacyGrammarDirectoryScanner.java index c28b98d..db5ed60 100644 --- a/src/main/java/org/codehaus/mojo/javacc/LegacyGrammarDirectoryScanner.java +++ b/src/main/java/org/codehaus/mojo/javacc/LegacyGrammarDirectoryScanner.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -26,21 +26,17 @@ * perform timestamp checking against copies of the input grammars rather than against the generated parser files. * Hence, the directory configured by {@link #setOutputDirectory(File)} is taken to be the output directory for the * timestamp files. - * + * * @author Benjamin Bentmann * @version $Id$ */ -class LegacyGrammarDirectoryScanner - extends GrammarDirectoryScanner -{ +class LegacyGrammarDirectoryScanner extends GrammarDirectoryScanner { /** * {@inheritDoc} */ - protected File[] getTargetFiles( File targetDirectory, String grammarFile, GrammarInfo grammarInfo ) - { - File timestampFile = new File( targetDirectory, grammarFile ); - return new File[] { timestampFile }; + protected File[] getTargetFiles(File targetDirectory, String grammarFile, GrammarInfo grammarInfo) { + File timestampFile = new File(targetDirectory, grammarFile); + return new File[] {timestampFile}; } - } diff --git a/src/main/java/org/codehaus/mojo/javacc/ToolFacade.java b/src/main/java/org/codehaus/mojo/javacc/ToolFacade.java index 80d0888..8372fdf 100644 --- a/src/main/java/org/codehaus/mojo/javacc/ToolFacade.java +++ b/src/main/java/org/codehaus/mojo/javacc/ToolFacade.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -26,12 +26,11 @@ /** * Provides a facade for the mojos to invoke JavaCC related tools. - * + * * @author Benjamin Bentmann * @version $Id$ */ -abstract class ToolFacade -{ +abstract class ToolFacade { /** * The logger used to output diagnostic messages. @@ -40,23 +39,20 @@ abstract class ToolFacade /** * Sets the logger used to output diagnostic messages. - * + * * @param logger The logger used to output diagnostic messages, may be null. */ - public void setLog( Log logger ) - { + public void setLog(Log logger) { this.log = logger; } /** * Gets the logger used to output diagnostic messages. - * + * * @return The logger used to output diagnostic messages, never null. */ - protected Log getLog() - { - if ( this.log == null ) - { + protected Log getLog() { + if (this.log == null) { this.log = new SystemStreamLog(); } return this.log; @@ -64,50 +60,40 @@ protected Log getLog() /** * Gets the name of the tool. - * + * * @return The name of the tool, never null. */ - protected String getToolName() - { + protected String getToolName() { String name = getClass().getName(); - return name.substring( name.lastIndexOf( '.' ) + 1 ); + return name.substring(name.lastIndexOf('.') + 1); } /** * Runs the tool using the previously set parameters. - * + * * @throws MojoExecutionException If the tool could not be invoked. * @throws MojoFailureException If the tool reported a non-zero exit code. */ - public void run() - throws MojoExecutionException, MojoFailureException - { + public void run() throws MojoExecutionException, MojoFailureException { int exitCode; - try - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Running " + getToolName() + ": " + this ); + try { + if (getLog().isDebugEnabled()) { + getLog().debug("Running " + getToolName() + ": " + this); } exitCode = execute(); + } catch (Exception e) { + throw new MojoExecutionException("Failed to execute " + getToolName(), e); } - catch ( Exception e ) - { - throw new MojoExecutionException( "Failed to execute " + getToolName(), e ); - } - if ( exitCode != 0 ) - { - throw new MojoFailureException( getToolName() + " reported exit code " + exitCode + ": " + this ); + if (exitCode != 0) { + throw new MojoFailureException(getToolName() + " reported exit code " + exitCode + ": " + this); } } /** * Runs the tool using the previously set parameters. - * + * * @return The exit code of the tool, non-zero means failure. * @throws Exception If the tool could not be invoked. */ - protected abstract int execute() - throws Exception; - + protected abstract int execute() throws Exception; } diff --git a/src/main/java/org/codehaus/mojo/javacc/UrlUtils.java b/src/main/java/org/codehaus/mojo/javacc/UrlUtils.java index 3821ade..cc4b347 100644 --- a/src/main/java/org/codehaus/mojo/javacc/UrlUtils.java +++ b/src/main/java/org/codehaus/mojo/javacc/UrlUtils.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -28,12 +28,11 @@ /** * Assists in handling of URLs. - * + * * @author Benjamin Bentmann * @version $Id$ */ -class UrlUtils -{ +class UrlUtils { /** * The protocol prefix for "jar:" URLs. @@ -54,42 +53,32 @@ class UrlUtils * Gets the absolute filesystem path to the class path root for the specified resource. The root is either a JAR * file or a directory with loose class files. If the URL does not use a supported protocol, an exception will be * thrown. - * + * * @param url The URL to the resource, may be null. * @param resource The name of the resource, must not be null. * @return The absolute filesystem path to the class path root of the resource or null if the input * URL was null. */ - public static File getResourceRoot( URL url, String resource ) - { + public static File getResourceRoot(URL url, String resource) { String path = null; - if ( url != null ) - { + if (url != null) { String spec = url.toExternalForm(); - if ( ( JAR_FILE ).regionMatches( true, 0, spec, 0, JAR_FILE.length() ) ) - { + if ((JAR_FILE).regionMatches(true, 0, spec, 0, JAR_FILE.length())) { URL jar; - try - { - jar = new URL( spec.substring( JAR.length(), spec.lastIndexOf( "!/" ) ) ); + try { + jar = new URL(spec.substring(JAR.length(), spec.lastIndexOf("!/"))); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid JAR URL: " + url + ", " + e.getMessage()); } - catch ( MalformedURLException e ) - { - throw new IllegalArgumentException( "Invalid JAR URL: " + url + ", " + e.getMessage() ); - } - path = decodeUrl( jar.getPath() ); - } - else if ( FILE.regionMatches( true, 0, spec, 0, FILE.length() ) ) - { - path = decodeUrl( url.getPath() ); - path = path.substring( 0, path.length() - resource.length() ); - } - else - { - throw new IllegalArgumentException( "Invalid class path URL: " + url ); + path = decodeUrl(jar.getPath()); + } else if (FILE.regionMatches(true, 0, spec, 0, FILE.length())) { + path = decodeUrl(url.getPath()); + path = path.substring(0, path.length() - resource.length()); + } else { + throw new IllegalArgumentException("Invalid class path URL: " + url); } } - return ( path != null ) ? new File( path ) : null; + return (path != null) ? new File(path) : null; } /** @@ -98,52 +87,39 @@ else if ( FILE.regionMatches( true, 0, spec, 0, FILE.length() ) ) * unfortunately does not enforce proper URLs. As such, this method will leniently accept invalid characters or * malformed percent-encoded octets and simply pass them literally through to the result string. Except for rare * edge cases, this will make unencoded URLs pass through unaltered. - * + * * @param url The URL to decode, may be null. * @return The decoded URL or null if the input was null. */ - public static String decodeUrl( String url ) - { + public static String decodeUrl(String url) { String decoded = url; - if ( url != null && url.indexOf( '%' ) >= 0 ) - { + if (url != null && url.indexOf('%') >= 0) { int n = url.length(); StringBuilder buffer = new StringBuilder(); - ByteBuffer bytes = ByteBuffer.allocate( n ); - for ( int i = 0; i < n; ) - { - if ( url.charAt( i ) == '%' ) - { - try - { - do - { - byte octet = (byte) Integer.parseInt( url.substring( i + 1, i + 3 ), 16 ); - bytes.put( octet ); + ByteBuffer bytes = ByteBuffer.allocate(n); + for (int i = 0; i < n; ) { + if (url.charAt(i) == '%') { + try { + do { + byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); + bytes.put(octet); i += 3; - } - while ( i < n && url.charAt( i ) == '%' ); + } while (i < n && url.charAt(i) == '%'); continue; - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { // malformed percent-encoded octet, fall through and append characters literally - } - finally - { - if ( bytes.position() > 0 ) - { + } finally { + if (bytes.position() > 0) { bytes.flip(); - buffer.append(UTF_8.decode( bytes )); + buffer.append(UTF_8.decode(bytes)); bytes.clear(); } } } - buffer.append( url.charAt( i++ ) ); + buffer.append(url.charAt(i++)); } decoded = buffer.toString(); } return decoded; } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/ForkedJvmTest.java b/src/test/java/org/codehaus/mojo/javacc/ForkedJvmTest.java index 5e0b036..ea88601 100644 --- a/src/test/java/org/codehaus/mojo/javacc/ForkedJvmTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/ForkedJvmTest.java @@ -2,109 +2,103 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ import java.io.File; -import org.codehaus.plexus.util.cli.CommandLineUtils.StringStreamConsumer; - import junit.framework.TestCase; +import org.codehaus.plexus.util.cli.CommandLineUtils.StringStreamConsumer; /** * Tests ForkedJvm. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class ForkedJvmTest - extends TestCase -{ +public class ForkedJvmTest extends TestCase { public void testToStringNullSafe() { ForkedJvm jvm = new ForkedJvm(); String string = jvm.toString(); - assertNotNull( string ); + assertNotNull(string); assertFalse(string.contains("null")); } public void testSettersNullSafe() { ForkedJvm jvm = new ForkedJvm(); - jvm.addArgument( (File) null ); - jvm.addArgument( (String) null ); - jvm.addArguments( null ); - jvm.addArguments( new String[] { null } ); - jvm.addClassPathEntry( (Class) null ); - jvm.addClassPathEntry( (File) null ); - jvm.addClassPathEntry( (String) null ); - jvm.setMainClass( (Class) null ); - jvm.setMainClass( (String) null ); - jvm.setWorkingDirectory( null ); - jvm.setSystemOut( null ); - jvm.setSystemErr( null ); + jvm.addArgument((File) null); + jvm.addArgument((String) null); + jvm.addArguments(null); + jvm.addArguments(new String[] {null}); + jvm.addClassPathEntry((Class) null); + jvm.addClassPathEntry((File) null); + jvm.addClassPathEntry((String) null); + jvm.setMainClass((Class) null); + jvm.setMainClass((String) null); + jvm.setWorkingDirectory(null); + jvm.setSystemOut(null); + jvm.setSystemErr(null); } public void testSetMainClass() { ForkedJvm jvm1 = new ForkedJvm(); - jvm1.setMainClass( MainStub.class ); + jvm1.setMainClass(MainStub.class); String cmd1 = jvm1.toString(); assertTrue(cmd1.contains(MainStub.class.getName())); ForkedJvm jvm2 = new ForkedJvm(); - jvm2.setMainClass( MainStub.class.getName() ); + jvm2.setMainClass(MainStub.class.getName()); String cmd2 = jvm2.toString(); assertTrue(cmd2.contains(MainStub.class.getName())); - assertEquals( cmd1, cmd2 ); + assertEquals(cmd1, cmd2); } - public void testFork() - throws Exception - { - File workDir = new File( System.getProperty( "user.home" ) ).getCanonicalFile(); - File file = new File( "test" ).getAbsoluteFile(); - String nonce = Integer.toString( hashCode() ); + public void testFork() throws Exception { + File workDir = new File(System.getProperty("user.home")).getCanonicalFile(); + File file = new File("test").getAbsoluteFile(); + String nonce = Integer.toString(hashCode()); StringStreamConsumer stdout = new StringStreamConsumer(); StringStreamConsumer stderr = new StringStreamConsumer(); ForkedJvm jvm = new ForkedJvm(); - jvm.setWorkingDirectory( workDir ); - jvm.setSystemOut( stdout ); - jvm.setSystemErr( stderr ); - jvm.setMainClass( MainStub.class ); - jvm.addArgument( nonce ); - jvm.addArguments( new String[] { "arg1", "arg2" } ); - jvm.addArgument( file ); - System.out.println( "Forking: " + jvm ); + jvm.setWorkingDirectory(workDir); + jvm.setSystemOut(stdout); + jvm.setSystemErr(stderr); + jvm.setMainClass(MainStub.class); + jvm.addArgument(nonce); + jvm.addArguments(new String[] {"arg1", "arg2"}); + jvm.addArgument(file); + System.out.println("Forking: " + jvm); int exitcode = jvm.run(); String out = stdout.getOutput(); String err = stderr.getOutput(); - String[] args = out.split( "(\r\n)|(\r)|(\n)" ); + String[] args = out.split("(\r\n)|(\r)|(\n)"); - assertEquals( 27, exitcode ); + assertEquals(27, exitcode); - assertEquals( workDir, new File( err.trim() ) ); + assertEquals(workDir, new File(err.trim())); - assertEquals( 4, args.length ); - assertEquals( nonce, args[0] ); - assertEquals( "arg1", args[1] ); - assertEquals( "arg2", args[2] ); - assertEquals( file, new File( args[3] ) ); + assertEquals(4, args.length); + assertEquals(nonce, args[0]); + assertEquals("arg1", args[1]); + assertEquals("arg2", args[2]); + assertEquals(file, new File(args[3])); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/GrammarInfoTest.java b/src/test/java/org/codehaus/mojo/javacc/GrammarInfoTest.java index 94813e6..2672e91 100644 --- a/src/test/java/org/codehaus/mojo/javacc/GrammarInfoTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/GrammarInfoTest.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -29,131 +29,97 @@ /** * Tests GrammarInfo. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class GrammarInfoTest - extends TestCase -{ +public class GrammarInfoTest extends TestCase { public void testInvalidFile() { - try - { - new GrammarInfo( new File( "" ).getAbsoluteFile(), "bad" ); - fail( "Missing IO exception" ); - } - catch ( IOException e ) - { + try { + new GrammarInfo(new File("").getAbsoluteFile(), "bad"); + fail("Missing IO exception"); + } catch (IOException e) { // expected } } - public void testGetGrammarFile() - throws Exception - { - File grammarFile = getGrammar( "Parser1.jj" ); - GrammarInfo info = new GrammarInfo( grammarFile.getParentFile(), grammarFile.getName() ); - assertEquals( grammarFile, info.getGrammarFile() ); + public void testGetGrammarFile() throws Exception { + File grammarFile = getGrammar("Parser1.jj"); + GrammarInfo info = new GrammarInfo(grammarFile.getParentFile(), grammarFile.getName()); + assertEquals(grammarFile, info.getGrammarFile()); } - public void testGetRelativeGrammarFile() - throws Exception - { - File grammarFile = getGrammar( "Parser1.jj" ); - GrammarInfo info = new GrammarInfo( grammarFile.getParentFile(), grammarFile.getName() ); - assertEquals( grammarFile.getName(), info.getRelativeGrammarFile() ); + public void testGetRelativeGrammarFile() throws Exception { + File grammarFile = getGrammar("Parser1.jj"); + GrammarInfo info = new GrammarInfo(grammarFile.getParentFile(), grammarFile.getName()); + assertEquals(grammarFile.getName(), info.getRelativeGrammarFile()); } - public void testGetPackageNameDeclaredPackageOverwrite() - throws Exception - { - File grammarFile = getGrammar( "Parser1.jj" ); - GrammarInfo info = new GrammarInfo( grammarFile.getParentFile(), grammarFile.getName(), "org.test" ); - assertEquals( "org.test", info.getParserPackage() ); + public void testGetPackageNameDeclaredPackageOverwrite() throws Exception { + File grammarFile = getGrammar("Parser1.jj"); + GrammarInfo info = new GrammarInfo(grammarFile.getParentFile(), grammarFile.getName(), "org.test"); + assertEquals("org.test", info.getParserPackage()); } - public void testGetPackageNameDeclaredPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser1.jj" ); - assertEquals( "org.codehaus.mojo.javacc.test", info.getParserPackage() ); + public void testGetPackageNameDeclaredPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser1.jj"); + assertEquals("org.codehaus.mojo.javacc.test", info.getParserPackage()); } - public void testGetPackageNameDefaultPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser2.jj" ); - assertEquals( "", info.getParserPackage() ); + public void testGetPackageNameDefaultPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser2.jj"); + assertEquals("", info.getParserPackage()); } - public void testGetPackageDirectoryDeclaredPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser1.jj" ); - assertEquals( new File( "org/codehaus/mojo/javacc/test" ).getPath(), info.getParserDirectory() ); + public void testGetPackageDirectoryDeclaredPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser1.jj"); + assertEquals(new File("org/codehaus/mojo/javacc/test").getPath(), info.getParserDirectory()); } - public void testGetPackageDirectoryDefaultPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser2.jj" ); - assertEquals( new File( "" ).getPath(), info.getParserDirectory() ); + public void testGetPackageDirectoryDefaultPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser2.jj"); + assertEquals(new File("").getPath(), info.getParserDirectory()); } - public void testGetParserName() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser1.jj" ); - assertEquals( "BasicParser", info.getParserName() ); + public void testGetParserName() throws Exception { + GrammarInfo info = newGrammarInfo("Parser1.jj"); + assertEquals("BasicParser", info.getParserName()); } - public void testGetParserFileDeclaredPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser1.jj" ); - assertEquals( new File( "org/codehaus/mojo/javacc/test/BasicParser.java" ).getPath(), info.getParserFile() ); + public void testGetParserFileDeclaredPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser1.jj"); + assertEquals(new File("org/codehaus/mojo/javacc/test/BasicParser.java").getPath(), info.getParserFile()); } - public void testGetParserFileDefaultPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser2.jj" ); - assertEquals( new File( "SimpleParser.java" ).getPath(), info.getParserFile() ); + public void testGetParserFileDefaultPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser2.jj"); + assertEquals(new File("SimpleParser.java").getPath(), info.getParserFile()); } - public void testResolvePackageNameDeclaredPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser1.jj" ); - assertEquals( "org.codehaus.mojo.javacc.test.node", info.resolvePackageName( "*.node" ) ); - assertEquals( "org.codehaus.mojo.javacc.testnode", info.resolvePackageName( "*node" ) ); - assertEquals( "node", info.resolvePackageName( "node" ) ); + public void testResolvePackageNameDeclaredPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser1.jj"); + assertEquals("org.codehaus.mojo.javacc.test.node", info.resolvePackageName("*.node")); + assertEquals("org.codehaus.mojo.javacc.testnode", info.resolvePackageName("*node")); + assertEquals("node", info.resolvePackageName("node")); } - public void testResolvePackageNameDefaultPackage() - throws Exception - { - GrammarInfo info = newGrammarInfo( "Parser2.jj" ); - assertEquals( "node", info.resolvePackageName( "*.node" ) ); - assertEquals( "node", info.resolvePackageName( "*node" ) ); - assertEquals( "node", info.resolvePackageName( "node" ) ); + public void testResolvePackageNameDefaultPackage() throws Exception { + GrammarInfo info = newGrammarInfo("Parser2.jj"); + assertEquals("node", info.resolvePackageName("*.node")); + assertEquals("node", info.resolvePackageName("*node")); + assertEquals("node", info.resolvePackageName("node")); } - private GrammarInfo newGrammarInfo( String resource ) - throws Exception - { - File grammarFile = getGrammar( resource ); + private GrammarInfo newGrammarInfo(String resource) throws Exception { + File grammarFile = getGrammar(resource); File sourceDir = grammarFile.getParentFile(); - return new GrammarInfo( sourceDir, grammarFile.getName() ); + return new GrammarInfo(sourceDir, grammarFile.getName()); } - private File getGrammar( String resource ) - throws Exception - { + private File getGrammar(String resource) throws Exception { URL res = getClass().getResource('/' + resource); - Objects.requireNonNull( res ); - return new File( new URI( res.toString() ) ); + Objects.requireNonNull(res); + return new File(new URI(res.toString())); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/JJDocTest.java b/src/test/java/org/codehaus/mojo/javacc/JJDocTest.java index 7e1584d..2ecf77c 100644 --- a/src/test/java/org/codehaus/mojo/javacc/JJDocTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/JJDocTest.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -23,28 +23,25 @@ /** * Tests JJDoc facade. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class JJDocTest - extends TestCase -{ +public class JJDocTest extends TestCase { public void testToStringNullSafe() { JJDoc tool = new JJDoc(); String string = tool.toString(); - assertNotNull( string ); + assertNotNull(string); assertFalse(string.contains("null")); } public void testSettersNullSafe() { JJDoc tool = new JJDoc(); - tool.setInputFile( null ); - tool.setOutputFile( null ); - tool.setOneTable( null ); - tool.setText( null ); - tool.setLog( null ); + tool.setInputFile(null); + tool.setOutputFile(null); + tool.setOneTable(null); + tool.setText(null); + tool.setLog(null); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/JJTreeTest.java b/src/test/java/org/codehaus/mojo/javacc/JJTreeTest.java index 428562f..e3eeafe 100644 --- a/src/test/java/org/codehaus/mojo/javacc/JJTreeTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/JJTreeTest.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -25,50 +25,47 @@ /** * Tests JJTree facade. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class JJTreeTest - extends TestCase -{ +public class JJTreeTest extends TestCase { public void testToStringNullSafe() { JJTree tool = new JJTree(); String string = tool.toString(); - assertNotNull( string ); + assertNotNull(string); assertFalse(string.contains("null")); } public void testSettersNullSafe() { JJTree tool = new JJTree(); - tool.setInputFile( null ); - tool.setOutputDirectory( null ); - tool.setJdkVersion( null ); - tool.setStatic( null ); - tool.setBuildNodeFiles( null ); - tool.setMulti( null ); - tool.setNodeDefaultVoid( null ); - tool.setNodeFactory( null ); - tool.setNodePackage( null ); - tool.setNodePrefix( null ); - tool.setNodeScopeHook( null ); - tool.setNodeUsesParser( null ); - tool.setVisitor( null ); - tool.setVisitorException( null ); - tool.setLog( null ); + tool.setInputFile(null); + tool.setOutputDirectory(null); + tool.setJdkVersion(null); + tool.setStatic(null); + tool.setBuildNodeFiles(null); + tool.setMulti(null); + tool.setNodeDefaultVoid(null); + tool.setNodeFactory(null); + tool.setNodePackage(null); + tool.setNodePrefix(null); + tool.setNodeScopeHook(null); + tool.setNodeUsesParser(null); + tool.setVisitor(null); + tool.setVisitorException(null); + tool.setLog(null); } public void testGetOutputFile() { - File input = new File( "Test.jjt" ).getAbsoluteFile(); - File outdir = new File( "dir" ).getAbsoluteFile(); + File input = new File("Test.jjt").getAbsoluteFile(); + File outdir = new File("dir").getAbsoluteFile(); JJTree tool = new JJTree(); - tool.setInputFile( input ); - tool.setOutputDirectory( outdir ); + tool.setInputFile(input); + tool.setOutputDirectory(outdir); File output = tool.getOutputFile(); - assertEquals( new File( outdir, "Test.jj" ), output ); + assertEquals(new File(outdir, "Test.jj"), output); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/JTBTest.java b/src/test/java/org/codehaus/mojo/javacc/JTBTest.java index 4b85cba..b6082ba 100644 --- a/src/test/java/org/codehaus/mojo/javacc/JTBTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/JTBTest.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -25,51 +25,48 @@ /** * Tests JTB facade. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class JTBTest - extends TestCase -{ +public class JTBTest extends TestCase { public void testToStringNullSafe() { JTB tool = new JTB(); String string = tool.toString(); - assertNotNull( string ); + assertNotNull(string); assertFalse(string.contains("null")); } public void testSettersNullSafe() { JTB tool = new JTB(); - tool.setInputFile( null ); - tool.setOutputDirectory( null ); - tool.setNodeDirectory( null ); - tool.setVisitorDirectory( null ); - tool.setDescriptiveFieldNames( null ); - tool.setJavadocFriendlyComments( null ); - tool.setNodePackageName( null ); - tool.setNodeParentClass( null ); - tool.setPackageName( null ); - tool.setParentPointers( null ); - tool.setPrinter( null ); - tool.setScheme( null ); - tool.setSpecialTokens( null ); - tool.setSupressErrorChecking( null ); - tool.setVisitorPackageName( null ); - tool.setLog( null ); + tool.setInputFile(null); + tool.setOutputDirectory(null); + tool.setNodeDirectory(null); + tool.setVisitorDirectory(null); + tool.setDescriptiveFieldNames(null); + tool.setJavadocFriendlyComments(null); + tool.setNodePackageName(null); + tool.setNodeParentClass(null); + tool.setPackageName(null); + tool.setParentPointers(null); + tool.setPrinter(null); + tool.setScheme(null); + tool.setSpecialTokens(null); + tool.setSupressErrorChecking(null); + tool.setVisitorPackageName(null); + tool.setLog(null); } public void testGetOutputFile() { - File input = new File( "Test.jtb" ).getAbsoluteFile(); - File outdir = new File( "dir" ).getAbsoluteFile(); + File input = new File("Test.jtb").getAbsoluteFile(); + File outdir = new File("dir").getAbsoluteFile(); JTB tool = new JTB(); - tool.setInputFile( input ); - tool.setOutputDirectory( outdir ); + tool.setInputFile(input); + tool.setOutputDirectory(outdir); File output = tool.getOutputFile(); - assertEquals( new File( outdir, "Test.jj" ), output ); + assertEquals(new File(outdir, "Test.jj"), output); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/JavaCCTest.java b/src/test/java/org/codehaus/mojo/javacc/JavaCCTest.java index 2ea0eab..1df2f22 100644 --- a/src/test/java/org/codehaus/mojo/javacc/JavaCCTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/JavaCCTest.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -23,48 +23,45 @@ /** * Tests JavaCC facade. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class JavaCCTest - extends TestCase -{ +public class JavaCCTest extends TestCase { public void testToStringNullSafe() { JavaCC tool = new JavaCC(); String string = tool.toString(); - assertNotNull( string ); + assertNotNull(string); assertFalse(string.contains("null")); } public void testSettersNullSafe() { JavaCC tool = new JavaCC(); - tool.setInputFile( null ); - tool.setOutputDirectory( null ); - tool.setJdkVersion( null ); - tool.setStatic( null ); - tool.setBuildParser( null ); - tool.setBuildTokenManager( null ); - tool.setCacheTokens( null ); - tool.setChoiceAmbiguityCheck( null ); - tool.setCommonTokenAction( null ); - tool.setDebugLookAhead( null ); - tool.setDebugParser( null ); - tool.setDebugTokenManager( null ); - tool.setErrorReporting( null ); - tool.setForceLaCheck( null ); - tool.setIgnoreCase( null ); - tool.setJavaUnicodeEscape( null ); - tool.setKeepLineColumn( null ); - tool.setLookAhead( null ); - tool.setOtherAmbiguityCheck( null ); - tool.setSanityCheck( null ); - tool.setTokenManagerUsesParser( null ); - tool.setUnicodeInput( null ); - tool.setUserCharStream( null ); - tool.setUserTokenManager( null ); - tool.setLog( null ); + tool.setInputFile(null); + tool.setOutputDirectory(null); + tool.setJdkVersion(null); + tool.setStatic(null); + tool.setBuildParser(null); + tool.setBuildTokenManager(null); + tool.setCacheTokens(null); + tool.setChoiceAmbiguityCheck(null); + tool.setCommonTokenAction(null); + tool.setDebugLookAhead(null); + tool.setDebugParser(null); + tool.setDebugTokenManager(null); + tool.setErrorReporting(null); + tool.setForceLaCheck(null); + tool.setIgnoreCase(null); + tool.setJavaUnicodeEscape(null); + tool.setKeepLineColumn(null); + tool.setLookAhead(null); + tool.setOtherAmbiguityCheck(null); + tool.setSanityCheck(null); + tool.setTokenManagerUsesParser(null); + tool.setUnicodeInput(null); + tool.setUserCharStream(null); + tool.setUserTokenManager(null); + tool.setLog(null); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/MainStub.java b/src/test/java/org/codehaus/mojo/javacc/MainStub.java index 650a45c..17b4825 100644 --- a/src/test/java/org/codehaus/mojo/javacc/MainStub.java +++ b/src/test/java/org/codehaus/mojo/javacc/MainStub.java @@ -2,41 +2,38 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ /** * Supports {@link ForkedJvmTest}. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class MainStub -{ +public class MainStub { - public static void main( String[] args ) - { + public static void main(String[] args) { for (String arg : args) { System.out.println(arg); } - System.err.println( System.getProperty( "user.dir" ) ); + System.err.println(System.getProperty("user.dir")); - System.exit( 27 ); + System.exit(27); } - } diff --git a/src/test/java/org/codehaus/mojo/javacc/UrlUtilsTest.java b/src/test/java/org/codehaus/mojo/javacc/UrlUtilsTest.java index 91b701f..14d551a 100644 --- a/src/test/java/org/codehaus/mojo/javacc/UrlUtilsTest.java +++ b/src/test/java/org/codehaus/mojo/javacc/UrlUtilsTest.java @@ -2,20 +2,20 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, + * + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations * under the License. */ @@ -27,118 +27,93 @@ /** * Tests UrlUtils. - * + * * @author Benjamin Bentmann * @version $Id$ */ -public class UrlUtilsTest - extends TestCase -{ - - public void testGetResourceRootFileWin() - throws Exception - { - assertMatch( "/C:/a dir", "file:/C:/a%20dir/org/Foo.class", "org/Foo.class" ); - assertMatch( "/C:/a dir", "file://localhost/C:/a%20dir/org/Foo.class", "org/Foo.class" ); - assertMatch( "/C:/a dir", "file:///C:/a%20dir/org/Foo.class", "org/Foo.class" ); - assertMatch( "/C:/a dir", "file:/C:/a%20dir/org/Foo.class", "/org/Foo.class" ); - assertMatch( "/C:/a dir", "file:/C:/a dir/org/Foo.class", "org/Foo.class" ); +public class UrlUtilsTest extends TestCase { + + public void testGetResourceRootFileWin() throws Exception { + assertMatch("/C:/a dir", "file:/C:/a%20dir/org/Foo.class", "org/Foo.class"); + assertMatch("/C:/a dir", "file://localhost/C:/a%20dir/org/Foo.class", "org/Foo.class"); + assertMatch("/C:/a dir", "file:///C:/a%20dir/org/Foo.class", "org/Foo.class"); + assertMatch("/C:/a dir", "file:/C:/a%20dir/org/Foo.class", "/org/Foo.class"); + assertMatch("/C:/a dir", "file:/C:/a dir/org/Foo.class", "org/Foo.class"); } - public void testGetResourceRootJarFileWin() - throws Exception - { - assertMatch( "/C:/a dir/t-1.jar", "jar:file:/C:/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); - assertMatch( "/C:/a dir/t-1.jar", "jar:file://localhost/C:/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); - assertMatch( "/C:/a dir/t-1.jar", "jar:file:///C:/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); - assertMatch( "/C:/a dir/t-1.jar", "jar:file:/C:/a%20dir/t-1.jar!/org/Foo.class", "/org/Foo.class" ); - assertMatch( "/C:/a dir/t-1.jar", "jar:file:/C:/a dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); + public void testGetResourceRootJarFileWin() throws Exception { + assertMatch("/C:/a dir/t-1.jar", "jar:file:/C:/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); + assertMatch("/C:/a dir/t-1.jar", "jar:file://localhost/C:/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); + assertMatch("/C:/a dir/t-1.jar", "jar:file:///C:/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); + assertMatch("/C:/a dir/t-1.jar", "jar:file:/C:/a%20dir/t-1.jar!/org/Foo.class", "/org/Foo.class"); + assertMatch("/C:/a dir/t-1.jar", "jar:file:/C:/a dir/t-1.jar!/org/Foo.class", "org/Foo.class"); } - public void testGetResourceRootFileWinUnc() - throws Exception - { - assertMatch( "//host/a dir", "file:////host/a%20dir/org/Foo.class", "org/Foo.class" ); + public void testGetResourceRootFileWinUnc() throws Exception { + assertMatch("//host/a dir", "file:////host/a%20dir/org/Foo.class", "org/Foo.class"); } - public void testGetResourceRootJarFileWinUnc() - throws Exception - { - assertMatch( "//host/a dir/t-1.jar", "jar:file:////host/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); + public void testGetResourceRootJarFileWinUnc() throws Exception { + assertMatch("//host/a dir/t-1.jar", "jar:file:////host/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); } - public void testGetResourceRootFileUnix() - throws Exception - { - assertMatch( "/home/a dir", "file:/home/a%20dir/org/Foo.class", "org/Foo.class" ); - assertMatch( "/home/a dir", "file://localhost/home/a%20dir/org/Foo.class", "org/Foo.class" ); - assertMatch( "/home/a dir", "file:///home/a%20dir/org/Foo.class", "org/Foo.class" ); - assertMatch( "/home/a dir", "file:/home/a%20dir/org/Foo.class", "/org/Foo.class" ); - assertMatch( "/home/a dir", "file:/home/a dir/org/Foo.class", "org/Foo.class" ); + public void testGetResourceRootFileUnix() throws Exception { + assertMatch("/home/a dir", "file:/home/a%20dir/org/Foo.class", "org/Foo.class"); + assertMatch("/home/a dir", "file://localhost/home/a%20dir/org/Foo.class", "org/Foo.class"); + assertMatch("/home/a dir", "file:///home/a%20dir/org/Foo.class", "org/Foo.class"); + assertMatch("/home/a dir", "file:/home/a%20dir/org/Foo.class", "/org/Foo.class"); + assertMatch("/home/a dir", "file:/home/a dir/org/Foo.class", "org/Foo.class"); } - public void testGetResourceRootJarFileUnix() - throws Exception - { - assertMatch( "/home/a dir/t-1.jar", "jar:file:/home/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); - assertMatch( "/home/a dir/t-1.jar", "jar:file://localhost/home/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); - assertMatch( "/home/a dir/t-1.jar", "jar:file:///home/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); - assertMatch( "/home/a dir/t-1.jar", "jar:file:/home/a%20dir/t-1.jar!/org/Foo.class", "/org/Foo.class" ); - assertMatch( "/home/a dir/t-1.jar", "jar:file:/home/a dir/t-1.jar!/org/Foo.class", "org/Foo.class" ); + public void testGetResourceRootJarFileUnix() throws Exception { + assertMatch("/home/a dir/t-1.jar", "jar:file:/home/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); + assertMatch("/home/a dir/t-1.jar", "jar:file://localhost/home/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); + assertMatch("/home/a dir/t-1.jar", "jar:file:///home/a%20dir/t-1.jar!/org/Foo.class", "org/Foo.class"); + assertMatch("/home/a dir/t-1.jar", "jar:file:/home/a%20dir/t-1.jar!/org/Foo.class", "/org/Foo.class"); + assertMatch("/home/a dir/t-1.jar", "jar:file:/home/a dir/t-1.jar!/org/Foo.class", "org/Foo.class"); } public void testGetResourceRootNullSafe() { - assertNull( UrlUtils.getResourceRoot( null, "" ) ); + assertNull(UrlUtils.getResourceRoot(null, "")); } - public void testGetResourceRootUnknownProtocal() - throws Exception - { - try - { - UrlUtils.getResourceRoot( URI.create( "http://www.foo.bar/index.html" ).toURL(), "index.html" ); - fail( "Missing runtime exception" ); - } - catch ( RuntimeException e ) - { - assertTrue( true ); + public void testGetResourceRootUnknownProtocal() throws Exception { + try { + UrlUtils.getResourceRoot(URI.create("http://www.foo.bar/index.html").toURL(), "index.html"); + fail("Missing runtime exception"); + } catch (RuntimeException e) { + assertTrue(true); } } - private void assertMatch( String expectedFile, String url, String resource ) - throws Exception - { - assertEquals( new File( expectedFile ), UrlUtils.getResourceRoot( new URL( url ), resource ) ); + private void assertMatch(String expectedFile, String url, String resource) throws Exception { + assertEquals(new File(expectedFile), UrlUtils.getResourceRoot(new URL(url), resource)); } - public void testDecodeUrl() - { - assertEquals( "", UrlUtils.decodeUrl( "" ) ); - assertEquals( "foo", UrlUtils.decodeUrl( "foo" ) ); - assertEquals( "+", UrlUtils.decodeUrl( "+" ) ); - assertEquals( "% ", UrlUtils.decodeUrl( "%25%20" ) ); - assertEquals( "%20", UrlUtils.decodeUrl( "%2520" ) ); - assertEquals( "jar:file:/C:/dir/sub dir/1.0/foo-1.0.jar!/org/Bar.class", - UrlUtils.decodeUrl( "jar:file:/C:/dir/sub%20dir/1.0/foo-1.0.jar!/org/Bar.class" ) ); + public void testDecodeUrl() { + assertEquals("", UrlUtils.decodeUrl("")); + assertEquals("foo", UrlUtils.decodeUrl("foo")); + assertEquals("+", UrlUtils.decodeUrl("+")); + assertEquals("% ", UrlUtils.decodeUrl("%25%20")); + assertEquals("%20", UrlUtils.decodeUrl("%2520")); + assertEquals( + "jar:file:/C:/dir/sub dir/1.0/foo-1.0.jar!/org/Bar.class", + UrlUtils.decodeUrl("jar:file:/C:/dir/sub%20dir/1.0/foo-1.0.jar!/org/Bar.class")); } - public void testDecodeUrlLenient() - { - assertEquals( " ", UrlUtils.decodeUrl( " " ) ); - assertEquals( "äöüß", UrlUtils.decodeUrl( "äöüß" ) ); - assertEquals( "%", UrlUtils.decodeUrl( "%" ) ); - assertEquals( "%2", UrlUtils.decodeUrl( "%2" ) ); - assertEquals( "%2G", UrlUtils.decodeUrl( "%2G" ) ); + public void testDecodeUrlLenient() { + assertEquals(" ", UrlUtils.decodeUrl(" ")); + assertEquals("äöüß", UrlUtils.decodeUrl("äöüß")); + assertEquals("%", UrlUtils.decodeUrl("%")); + assertEquals("%2", UrlUtils.decodeUrl("%2")); + assertEquals("%2G", UrlUtils.decodeUrl("%2G")); } - public void testDecodeUrlNullSafe() - { - assertNull( UrlUtils.decodeUrl( null ) ); + public void testDecodeUrlNullSafe() { + assertNull(UrlUtils.decodeUrl(null)); } - public void testDecodeUrlEncodingUtf8() - { - assertEquals( "äöüß", UrlUtils.decodeUrl( "%C3%A4%C3%B6%C3%BC%C3%9F" ) ); + public void testDecodeUrlEncodingUtf8() { + assertEquals("äöüß", UrlUtils.decodeUrl("%C3%A4%C3%B6%C3%BC%C3%9F")); } - }