*.jjt
) with JJTree and passes the output to JavaCC in order to
* finally generate a parser with parse tree actions.
*
* @goal jjtree-javacc
* @phase generate-sources
* @since 2.4
* @author Benjamin Bentmann
* @version $Id: JJTreeJavaCCMojo.java 10603 2009-09-06 15:05:08Z bentmann $
*/
public class JJTreeJavaCCMojo
extends AbstractJavaCCMojo
{
/**
* A flag whether to generate sample implementations for SimpleNode
and any other nodes used in the
* grammar. Default value is true
.
*
* @parameter expression="${buildNodeFiles}"
*/
private Boolean buildNodeFiles;
/**
* A flag whether to generate a multi mode parse tree or a single mode parse tree. Default value is
* false
.
*
* @parameter expression="${multi}"
*/
private Boolean multi;
/**
* A flag whether to make each non-decorated production void instead of an indefinite node. Default value is
* false
.
*
* @parameter expression="${nodeDefaultVoid}"
*/
private Boolean nodeDefaultVoid;
/**
* The name of a custom class that extends SimpleNode
and will be used as the super class for the
* generated tree node classes. By default, the tree node classes will directly extend the class
* SimpleNode
.
*
* @parameter expression="${nodeClass}"
* @since 2.5
*/
private String nodeClass;
/**
* 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 expression="${nodeFactory}"
*/
private String nodeFactory;
/**
* The package to generate the AST node classes into. This value may use a leading asterisk to reference the package
* of the corresponding parser. For example, if the parser package is org.apache
and this parameter
* is set to *.node
, the tree node classes will be located in the package
* org.apache.node
. By default, the package of the corresponding parser is used.
*
* @parameter expression="${nodePackage}"
*/
private String nodePackage;
/**
* The prefix used to construct node class names from node identifiers in multi mode. Default value is
* AST
.
*
* @parameter expression="${nodePrefix}"
*/
private String nodePrefix;
/**
* A flag whether user-defined parser methods should be called on entry and exit of every node scope. Default value
* is false
.
*
* @parameter expression="${nodeScopeHook}"
*/
private Boolean nodeScopeHook;
/**
* A flag whether the node construction routines need an additional method parameter to receive the parser object.
* Default value is false
.
*
* @parameter expression="${nodeUsesParser}"
*/
private Boolean nodeUsesParser;
/**
* A flag whether to insert the methods jjtGetFirstToken()
, jjtSetFirstToken()
,
* getLastToken()
and jjtSetLastToken()
into the class SimpleNode
. Default
* value is false
.
*
* @parameter expression="${trackTokens}"
* @since 2.5
*/
private Boolean trackTokens;
/**
* A flag whether to insert a jjtAccept()
method in the node classes and to generate a visitor
* implementation with an entry for every node type used in the grammar. Default value is false
.
*
* @parameter expression="${visitor}"
*/
private Boolean visitor;
/**
* The name of a class to use for the data argument of the jjtAccept()
and visit()
* methods. Default value is java.lang.Object
.
*
* @parameter expression="${visitorDataType}"
* @since 2.5
*/
private String visitorDataType;
/**
* The name of a class to use as the return type of the jjtAccept()
and visit()
methods.
* Default value is java.lang.Object
.
*
* @parameter expression="${visitorReturnType}"
* @since 2.5
*/
private String visitorReturnType;
/**
* The name of an exception class to include in the signature of the generated jjtAccept()
and
* visit()
methods. By default, the throws
clause of the generated methods is empty such
* that only unchecked exceptions can be thrown.
*
* @parameter expression="${visitorException}"
*/
private String visitorException;
/**
* The directory where the decorated JavaCC grammar files (*.jjt
) are located. It will be
* recursively scanned for input files to pass to JJTree. The parameters includes
and
* excludes
can be used to select a subset of files.
*
* @parameter expression="${sourceDirectory}" default-value="${basedir}/src/main/jjtree"
*/
private File sourceDirectory;
/**
* The directory where the AST node files generated by JJTree will be stored. The directory will be registered as a
* compile source root of the project such that the generated files will participate in later build phases like
* compiling and packaging.
*
* @parameter expression="${interimDirectory}" default-value="${project.build.directory}/generated-sources/jjtree"
*/
private File interimDirectory;
/**
* The directory where the parser files generated by JavaCC will be stored. The directory will be registered as a
* compile source root of the project such that the generated files will participate in later build phases like
* compiling and packaging.
*
* @parameter expression="${outputDirectory}" default-value="${project.build.directory}/generated-sources/javacc"
*/
private File outputDirectory;
/**
* A set of Ant-like inclusion patterns used to select files from the source directory for processing. By default,
* the patterns **/*.jj
, **/*.JJ
, **/*.jjt
and
* **/*.JJT
are used to select grammar files.
*
* @parameter
*/
private String[] includes;
/**
* A set of Ant-like exclusion patterns used to prevent certain files from being processed. By default, this set is
* empty such that no files are excluded.
*
* @parameter
*/
private String[] excludes;
/**
* The granularity in milliseconds of the last modification date for testing whether a grammar file needs
* recompilation.
*
* @parameter expression="${lastModGranularityMs}" default-value="0"
*/
private int staleMillis;
/**
* {@inheritDoc}
*/
protected File getSourceDirectory()
{
return this.sourceDirectory;
}
/**
* {@inheritDoc}
*/
protected String[] getIncludes()
{
if ( this.includes != null )
{
return this.includes;
}
else
{
return new String[] { "**/*.jj", "**/*.JJ", "**/*.jjt", "**/*.JJT" };
}
}
/**
* {@inheritDoc}
*/
protected String[] getExcludes()
{
return this.excludes;
}
/**
* {@inheritDoc}
*/
protected File getOutputDirectory()
{
return this.outputDirectory;
}
/**
* {@inheritDoc}
*/
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()
{
return this.interimDirectory;
}
/**
* {@inheritDoc}
*/
protected File[] getCompileSourceRoots()
{
return new File[] { getOutputDirectory(), getInterimDirectory() };
}
/**
* {@inheritDoc}
*/
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" );
// setup output directory of parser file (*.java) generated by JavaCC
File parserDirectory = new File( tempDirectory, "parser" );
// setup output directory of tree node files (*.java) generated by JJTree
String nodePackageName = grammarInfo.resolvePackageName( this.nodePackage );
// generate final grammar file
JJTree jjtree = newJJTree();
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.run();
// copy output from JJTree
copyGrammarOutput( getInterimDirectory(), ( nodePackageName != null ) ? nodePackageName
: grammarInfo.getParserPackage(), jjDirectory, grammarInfo.getParserName() + "TreeConstants*" );
// copy parser files from JavaCC
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, "*" );
}
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()
{
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 );
return jjtree;
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java 0000644 0001750 0001750 00000065523 11257376700 030527 0 ustar cavedon cavedon 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.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.SelectorUtils;
import org.codehaus.plexus.util.StringUtils;
/**
* Provides common services for all mojos that compile JavaCC grammar files.
*
* @author jruiz@exist.com
* @author jesse 1.5
for plugin version 2.6+ and
* 1.4
in older versions.
*
* @parameter expression="${jdkVersion}"
* @since 2.4
*/
private String jdkVersion;
/**
* The number of tokens to look ahead before making a decision at a choice point during parsing. The default value
* is 1
.
*
* @parameter expression="${lookAhead}"
*/
private Integer lookAhead;
/**
* This is the number of tokens considered in checking choices of the form "A | B | ..." for ambiguity. Default
* value is 2
.
*
* @parameter expression="${choiceAmbiguityCheck}"
*/
private Integer choiceAmbiguityCheck;
/**
* This is the number of tokens considered in checking all other kinds of choices (i.e., of the forms "(A)*",
* "(A)+", and "(A)?") for ambiguity. Default value is 1
.
*
* @parameter expression="${otherAmbiguityCheck}"
*/
private Integer otherAmbiguityCheck;
/**
* If true
, all methods and class variables are specified as static in the generated parser and
* token manager. This allows only one parser object to be present, but it improves the performance of the parser.
* Default value is true
.
*
* @parameter expression="${isStatic}"
*/
private Boolean isStatic;
/**
* This option is used to obtain debugging information from the generated parser. Setting this option to
* true
causes the parser to generate a trace of its actions. Default value is false
.
*
* @parameter expression="${debugParser}"
*/
private Boolean debugParser;
/**
* This is a boolean option whose default value is false
. Setting this option to true
* causes the parser to generate all the tracing information it does when the option debugParser
is
* true
, and in addition, also causes it to generated a trace of actions performed during lookahead
* operation.
*
* @parameter expression="${debugLookAhead}"
*/
private Boolean debugLookAhead;
/**
* This option is used to obtain debugging information from the generated token manager. Default value is
* false
.
*
* @parameter expression="${debugTokenManager}"
*/
private Boolean debugTokenManager;
/**
* Setting it to false
causes errors due to parse errors to be reported in somewhat less detail.
* Default value is true
.
*
* @parameter expression="${errorReporting}"
*/
private Boolean errorReporting;
/**
* When set to true
, the generated parser uses an input stream object that processes Java Unicode
* escapes (\
u
xxxx) before sending characters to the token manager. Default
* value is false
.
*
* @parameter expression="${javaUnicodeEscape}"
*/
private Boolean javaUnicodeEscape;
/**
* When set to true
, the generated parser uses uses an input stream object that reads Unicode files.
* By default, ASCII files are assumed. Default value is false
.
*
* @parameter expression="${unicodeInput}"
*/
private Boolean unicodeInput;
/**
* Setting this option to true
causes the generated token manager to ignore case in the token
* specifications and the input files. Default value is false
.
*
* @parameter expression="${ignoreCase}"
*/
private Boolean ignoreCase;
/**
* When set to true
, every call to the token manager's method getNextToken()
(see the
* description of the Java Compiler Compiler API)
* will cause a call to a user-defined method CommonTokenAction()
after the token has been scanned in
* by the token manager. Default value is false
.
*
* @parameter expression="${commonTokenAction}"
*/
private Boolean commonTokenAction;
/**
* The default action is to generate a token manager that works on the specified grammar tokens. If this option is
* set to true
, then the parser is generated to accept tokens from any token manager of type
* TokenManager
- this interface is generated into the generated parser directory. Default value is
* false
.
*
* @parameter expression="${userTokenManager}"
*/
private Boolean userTokenManager;
/**
* This flag controls whether the token manager will read characters from a character stream reader as defined by
* the options javaUnicodeEscape
and unicodeInput
or whether the token manager reads
* from a user-supplied implementation of CharStream
. Default value is false
.
*
* @parameter expression="${userCharStream}"
*/
private Boolean userCharStream;
/**
* A flag that controls whether the parser file (*Parser.java
) should be generated or not. If set
* to false
, only the token manager is generated. Default value is true
.
*
* @parameter expression="${buildParser}"
*/
private Boolean buildParser;
/**
* A flag that controls whether the token manager file (*TokenManager.java
) should be generated or
* not. Setting this to false
can speed up the generation process if only the parser part of the
* grammar changed. Default value is true
.
*
* @parameter expression="${buildTokenManager}"
*/
private Boolean buildTokenManager;
/**
* 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 expression="${tokenManagerUsesParser}"
*/
private Boolean tokenManagerUsesParser;
/**
* The name of the base class for the generated Token
class. Default value is
* java.lang.Object
.
*
* @parameter expression="${tokenExtends}"
* @since 2.5
*/
private String tokenExtends;
/**
* The name of a custom factory class used to create Token
objects. This class must have a method with
* the signature public static Token newToken(int ofKind, String image)
. By default, tokens are created
* by calling Token.newToken()
.
*
* @parameter expression="${tokenFactory}"
* @since 2.5
*/
private String tokenFactory;
/**
* Enables/disables many syntactic and semantic checks on the grammar file during parser generation. Default value
* is true
.
*
* @parameter expression="${sanityCheck}"
*/
private Boolean sanityCheck;
/**
* This option setting controls lookahead ambiguity checking performed by JavaCC. Default value is
* false
.
*
* @parameter expression="${forceLaCheck}"
*/
private Boolean forceLaCheck;
/**
* Setting this option to true
causes the generated parser to lookahead for extra tokens ahead of
* time. Default value is false
.
*
* @parameter expression="${cacheTokens}"
*/
private Boolean cacheTokens;
/**
* A flag whether to keep line and column information along with a token. Default value is true
.
*
* @parameter expression="${keepLineColumn}"
*/
private Boolean keepLineColumn;
/**
* A flag whether the generated support classes of the parser should have public or package-private visibility.
* Default value is true
.
*
* @parameter expression="${supportClassVisibilityPublic}"
* @since 2.6
*/
private Boolean supportClassVisibilityPublic;
/**
* The file encoding to use for reading the grammar files.
*
* @parameter expression="${grammarEncoding}" default-value="${project.build.sourceEncoding}"
* @since 2.6
*/
private String grammarEncoding;
/**
* 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()
{
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()
{
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()
{
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.
*/
protected abstract String[] getIncludes();
/**
* 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.
*/
protected abstract String[] getExcludes();
/**
* 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
.
*/
protected abstract File getOutputDirectory();
/**
* 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.
*/
protected abstract int getStaleMillis();
/**
* 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()
{
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
{
GrammarInfo[] grammarInfos = scanForGrammars();
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
{
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!" );
}
for ( int i = 0; i < grammarInfos.length; i++ )
{
processGrammar( grammarInfos[i] );
}
getLog().info( "Processed " + grammarInfos.length + " grammar" + ( grammarInfos.length != 1 ? "s" : "" ) );
}
Collection compileSourceRoots = new LinkedHashSet( Arrays.asList( getCompileSourceRoots() ) );
for ( Iterator it = compileSourceRoots.iterator(); it.hasNext(); )
{
addSourceRoot( (File) it.next() );
}
}
/**
* 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;
/**
* 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() )
{
return null;
}
GrammarInfo[] grammarInfos;
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.scan();
grammarInfos = scanner.getIncludedGrammars();
}
catch ( Exception e )
{
throw new MojoExecutionException( "Failed to scan for grammars: " + getSourceDirectory(), e );
}
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() );
}
/**
* 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 );
}
}
/**
* Scans the filesystem for output files and copies them to the specified compile source root. An output file is
* 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
.
* @param tempDirectory The (absolute) path to the directory to scan for generated output files, must not be
* null
.
* @param updatePattern A glob pattern that matches the (simple) names of those files which should always be updated
* in case we are outputting directly into src/main/java
, may be null
. A
* 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
{
Collection tempFiles = FileUtils.getFiles( tempDirectory, "*.java", null );
for ( Iterator it = tempFiles.iterator(); it.hasNext(); )
{
File tempFile = (File) it.next();
String outputPath = "";
if ( packageName.length() > 0 )
{
outputPath = packageName.replace( '.', '/' ) + '/';
}
outputPath += tempFile.getName();
File outputFile = new File( sourceRoot, outputPath );
File sourceFile = findSourceFile( outputPath );
boolean alwaysUpdate = false;
if ( updatePattern != null && sourceFile != null )
{
if ( updatePattern.startsWith( "!" ) )
{
alwaysUpdate = !SelectorUtils.match( updatePattern.substring( 1 ), tempFile.getName() );
}
else
{
alwaysUpdate = SelectorUtils.match( updatePattern, tempFile.getName() );
}
}
if ( sourceFile == null || ( alwaysUpdate && sourceFile.equals( outputFile ) ) )
{
getLog().debug( "Copying generated file: " + outputPath );
try
{
FileUtils.copyFile( tempFile, outputFile );
}
catch ( IOException 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 );
}
}
/**
* 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
{
this.nonGeneratedSourceRoots = new LinkedHashSet();
try
{
String targetPrefix =
new File( this.project.getBuild().getDirectory() ).getCanonicalPath() + File.separator;
Collection sourceRoots = this.project.getCompileSourceRoots();
for ( Iterator it = sourceRoots.iterator(); it.hasNext(); )
{
File sourceRoot = new File( it.next().toString() );
if ( !sourceRoot.isAbsolute() )
{
sourceRoot = new File( this.project.getBasedir(), sourceRoot.getPath() );
}
String sourcePath = sourceRoot.getCanonicalPath();
if ( !sourcePath.startsWith( targetPrefix ) )
{
this.nonGeneratedSourceRoots.add( sourceRoot );
getLog().debug( "Non-generated compile source root: " + sourceRoot );
}
else
{
getLog().debug( "Generated compile source root: " + sourceRoot );
}
}
}
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 )
{
Collection sourceRoots = this.nonGeneratedSourceRoots;
for ( Iterator it = sourceRoots.iterator(); it.hasNext(); )
{
File sourceRoot = (File) it.next();
File sourceFile = new File( sourceRoot, filename );
if ( sourceFile.exists() )
{
return sourceFile;
}
}
return null;
}
/**
* 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 );
}
/**
* 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() );
}
}
/**
* 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()
{
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 );
return javacc;
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/AbstractPreprocessorMojo.java 0000644 0001750 0001750 00000017263 10761360260 032115 0 ustar cavedon cavedon 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 org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
/**
* Provides common services for all mojos that preprocess JavaCC grammar files.
*
* @author Benjamin Bentmann
* @version $Id: AbstractPreprocessorMojo.java 6353 2008-02-27 22:14:08Z bentmann $
*/
public abstract class AbstractPreprocessorMojo
extends AbstractMojo
{
/**
* The current Maven project.
*
* @parameter default-value="${project}"
* @readonly
* @required
*/
private MavenProject project;
/**
* 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.
*/
protected abstract String[] getIncludes();
/**
* 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.
*/
protected abstract String[] getExcludes();
/**
* 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
.
*/
protected abstract File getOutputDirectory();
/**
* 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
.
*/
protected abstract File getTimestampDirectory();
/**
* 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.
*/
protected abstract int getStaleMillis();
/**
* 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." );
GrammarInfo[] grammarInfos = scanForGrammars();
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() )
{
getTimestampDirectory().mkdirs();
}
for ( int i = 0; i < grammarInfos.length; i++ )
{
processGrammar( grammarInfos[i] );
}
getLog().info( "Processed " + grammarInfos.length + " grammar" + ( grammarInfos.length != 1 ? "s" : "" ) );
}
addCompileSourceRoot();
}
/**
* 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;
/**
* 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() )
{
return null;
}
GrammarInfo[] grammarInfos;
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.scan();
grammarInfos = scanner.getIncludedGrammars();
}
catch ( Exception e )
{
throw new MojoExecutionException( "Failed to scan for grammars: " + getSourceDirectory(), e );
}
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 )
{
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 );
}
}
/**
* 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() );
}
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JTBJavaCCMojo.java 0000644 0001750 0001750 00000031657 11113311543 027365 0 ustar cavedon cavedon 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 org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Preprocesses ordinary grammar files (*.jtb
) with JTB and passes the output to JavaCC in order to
* finally generate a parser with parse tree actions.nodePackageName
= <packageName>.syntaxtree
and
* visitorPackageName
= <packageName>.visitor
. Note that this option takes
* precedence over nodePackageName
and visitorPackageName
if specified.
*
* @parameter expression="${package}"
*/
private String packageName;
/**
* This option specifies the package for the generated AST nodes. This value may use a leading asterisk to reference
* the package of the corresponding parser. For example, if the parser package is org.apache
and this
* parameter is set to *.demo
, the tree node classes will be located in the package
* org.apache.demo
. Default value is *.syntaxtree
.
*
* @parameter expression="${nodePackageName}"
*/
private String nodePackageName;
/**
* This option specifies the package for the generated visitors. This value may use a leading asterisk to reference
* the package of the corresponding parser. For example, if the parser package is org.apache
and this
* parameter is set to *.demo
, the visitor classes will be located in the package
* org.apache.demo
. Default value is *.visitor
.
*
* @parameter expression="${visitorPackageName}"
*/
private String visitorPackageName;
/**
* If true
, JTB will suppress its semantic error checking. Default value is false
.
*
* @parameter expression="${supressErrorChecking}"
*/
private Boolean supressErrorChecking;
/**
* If true
, all generated comments will be wrapped in <pre>
tags so that they
* are formatted correctly in API docs. Default value is false
.
*
* @parameter expression="${javadocFriendlyComments}"
*/
private Boolean javadocFriendlyComments;
/**
* Setting this option to true
causes JTB to generate field names that reflect the structure of the
* tree instead of generic names like f0
, f1
etc. Default value is false
.
*
* @parameter expression="${descriptiveFieldNames}"
*/
private Boolean descriptiveFieldNames;
/**
* The qualified name of a user-defined class from which all AST nodes will inherit. By default, AST nodes will
* inherit from the generated class Node
.
*
* @parameter expression="${nodeParentClass}"
*/
private String nodeParentClass;
/**
* If true
, all nodes will contain fields for its parent node. Default value is false
.
*
* @parameter expression="${parentPointers}"
*/
private Boolean parentPointers;
/**
* If true
, JTB will include JavaCC "special tokens" in the AST. Default value is false
.
*
* @parameter expression="${specialTokens}"
*/
private Boolean specialTokens;
/**
* If true
, JTB will generate the following files to support the Schema programming language:
* false
.
*
* @parameter expression="${scheme}"
*/
private Boolean scheme;
/**
* If true
, JTB will generate a syntax tree dumping visitor. Default value is false
.
*
* @parameter expression="${printer}"
*/
private Boolean printer;
/**
* The directory where the JavaCC grammar files (*.jtb
) are located. It will be recursively scanned
* for input files to pass to JTB. The parameters includes
and excludes
can be used to
* select a subset of files.
*
* @parameter expression="${sourceDirectory}" default-value="${basedir}/src/main/jtb"
*/
private File sourceDirectory;
/**
* The directory where the visitor and AST node files generated by JTB will be stored. The directory will be
* registered as a compile source root of the project such that the generated files will participate in later build
* phases like compiling and packaging.
*
* @parameter expression="${interimDirectory}" default-value="${project.build.directory}/generated-sources/jtb"
*/
private File interimDirectory;
/**
* The directory where the parser files generated by JavaCC will be stored. The directory will be registered as a
* compile source root of the project such that the generated files will participate in later build phases like
* compiling and packaging.
*
* @parameter expression="${outputDirectory}" default-value="${project.build.directory}/generated-sources/javacc"
*/
private File outputDirectory;
/**
* A set of Ant-like inclusion patterns used to select files from the source directory for processing. By default,
* the patterns **/*.jj
, **/*.JJ
, **/*.jtb
and
* **/*.JTB
are used to select grammar files.
*
* @parameter
*/
private String[] includes;
/**
* A set of Ant-like exclusion patterns used to prevent certain files from being processing. By default, this set is
* empty such that no files are excluded.
*
* @parameter
*/
private String[] excludes;
/**
* The granularity in milliseconds of the last modification date for testing whether a grammar file needs
* recompilation.
*
* @parameter expression="${lastModGranularityMs}" default-value="0"
*/
private int staleMillis;
/**
* {@inheritDoc}
*/
protected File getSourceDirectory()
{
return this.sourceDirectory;
}
/**
* {@inheritDoc}
*/
protected String[] getIncludes()
{
if ( this.includes != null )
{
return this.includes;
}
else
{
return new String[] { "**/*.jj", "**/*.JJ", "**/*.jtb", "**/*.JTB" };
}
}
/**
* {@inheritDoc}
*/
protected String[] getExcludes()
{
return this.excludes;
}
/**
* {@inheritDoc}
*/
protected File getOutputDirectory()
{
return this.outputDirectory;
}
/**
* {@inheritDoc}
*/
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()
{
return this.interimDirectory;
}
/**
* {@inheritDoc}
*/
protected File[] getCompileSourceRoots()
{
return new File[] { getOutputDirectory(), getInterimDirectory() };
}
/**
* {@inheritDoc}
*/
protected void processGrammar( GrammarInfo grammarInfo )
throws MojoExecutionException, MojoFailureException
{
File jtbFile = grammarInfo.getGrammarFile();
File jtbDirectory = jtbFile.getParentFile();
File tempDirectory = getTempDirectory();
// setup output directory of grammar file (*.jj) generated by JTB
File jjDirectory = tempDirectory;
// setup output directory of tree node files (*.java) generated by JTB
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" );
// setup output directory of parser file (*.java) generated by JavaCC
File parserDirectory = new File( tempDirectory, "parser" );
// 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.run();
// generate parser files
JavaCC javacc = newJavaCC();
javacc.setInputFile( jtb.getOutputFile() );
javacc.setOutputDirectory( parserDirectory );
javacc.run();
// copy tree node files from JTB
copyGrammarOutput( getInterimDirectory(), nodePackage, nodeDirectory, "!Node*" );
// copy visitor files from JTB
copyGrammarOutput( getInterimDirectory(), visitorPackage, visitorDirectory, "" );
// copy parser files from JavaCC
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, "*" );
}
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 )
{
return this.packageName + ".syntaxtree";
}
else if ( this.nodePackageName != null )
{
return this.nodePackageName;
}
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 )
{
return this.packageName + ".visitor";
}
else if ( this.visitorPackageName != null )
{
return this.visitorPackageName;
}
else
{
return "*.visitor";
}
}
/**
* 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()
{
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 );
return jtb;
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JJDocMojo.java 0000644 0001750 0001750 00000046257 11250747644 026712 0 ustar cavedon cavedon 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.doxia.siterenderer.Renderer;
import org.apache.maven.project.MavenProject;
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.
*
* @goal jjdoc
* @execute phase=generate-sources
* @since 2.3
* @author Paul Gier
* @version $Id: JJDocMojo.java 10603 2009-09-06 15:05:08Z bentmann $
* @see JJDoc Documentation
*/
public class JJDocMojo
extends AbstractMavenReport
{
// ----------------------------------------------------------------------
// Mojo Parameters
// ----------------------------------------------------------------------
/**
* The current Maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The site renderer.
*
* @component
*/
private Renderer siteRenderer;
/**
* 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 default-value="${basedir}/src/main/javacc"
* @readonly
*/
private File defaultGrammarDirectoryJavaCC;
/**
* The default source directory for grammar files generated by JJTree.
*
* @parameter default-value="${project.build.directory}/generated-sources/jjtree"
* @readonly
*/
private File defaultGrammarDirectoryJJTree;
/**
* The default source directory for grammar files generated by JTB.
*
* @parameter default-value="${project.build.directory}/generated-sources/jtb"
* @readonly
*/
private File defaultGrammarDirectoryJTB;
/**
* The relative path of the JJDoc reports in the output directory. This path will be appended to the output
* directory.
*
* @parameter default-value="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 expression="${outputDirectory}" default-value="${project.reporting.outputDirectory}"
*/
private File outputDirectory;
/**
* The file encoding to use for reading the grammar files.
*
* @parameter expression="${grammarEncoding}" default-value="${project.build.sourceEncoding}"
* @since 2.6
*/
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.
*
* @parameter expression="${cssHref}"
* @since 2.5
*/
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 expression="${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
.
*
* @parameter expression="${bnf}"
* @since 2.6
*/
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 expression="${oneTable}" default-value=true
*/
private boolean oneTable;
/**
* Get the maven project.
*
* @see org.apache.maven.reporting.AbstractMavenReport#getProject()
* @return The current Maven project.
*/
protected MavenProject getProject()
{
return this.project;
}
/**
* Get the site renderer.
*
* @see org.apache.maven.reporting.AbstractMavenReport#getSiteRenderer()
* @return The site renderer.
*/
protected Renderer getSiteRenderer()
{
return this.siteRenderer;
}
/**
* 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 (File[]) directories.toArray( new File[directories.size()] );
}
// ----------------------------------------------------------------------
// 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()
{
File sourceDirs[] = getSourceDirectories();
for ( int i = 0; i < sourceDirs.length; i++ )
{
File sourceDir = sourceDirs[i];
String[] files = sourceDir.list();
if ( files != null && files.length > 0 )
{
return true;
}
}
return false;
}
/**
* 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
{
Sink sink = getSink();
createReportHeader( getBundle( locale ), sink );
File[] sourceDirs = getSourceDirectories();
for ( int j = 0; j < sourceDirs.length; j++ )
{
File sourceDir = sourceDirs[j];
GrammarInfo[] grammarInfos = scanForGrammars( sourceDir );
if ( grammarInfos == null )
{
getLog().debug( "Skipping non-existing source directory: " + sourceDir );
}
else
{
Arrays.sort( grammarInfos, GrammarInfoComparator.getInstance() );
for ( int i = 0; i < grammarInfos.length; i++ )
{
GrammarInfo grammarInfo = grammarInfos[i];
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();
}
/**
* 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( Boolean.valueOf( 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( Object o1, Object o2 )
{
int rel;
GrammarInfo info1 = (GrammarInfo) o1;
String[] paths1 = info1.getRelativeGrammarFile().split( "\\" + File.separatorChar );
GrammarInfo info2 = (GrammarInfo) o2;
String[] paths2 = info2.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] );
}
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JTBMojo.java 0000644 0001750 0001750 00000025453 11067720504 026363 0 ustar cavedon cavedon 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 org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Parses a JTB file and transforms it into source files for an AST and a JavaCC grammar file which automatically builds
* the AST.jtb-javacc
goal instead.
* @author Gregory Kick (gk5885@kickstyle.net)
* @version $Id: JTBMojo.java 7743 2008-09-28 15:22:44Z bentmann $
*/
public class JTBMojo
extends AbstractPreprocessorMojo
{
/**
* This option is short for nodePackageName
= <packageName>.syntaxtree
and
* visitorPackageName
= <packageName>.visitor
. Note that this option takes
* precedence over nodePackageName
and visitorPackageName
if specified.
*
* @parameter expression="${package}"
*/
private String packageName;
/**
* This option specifies the package for the generated AST nodes. This value may use a leading asterisk to reference
* the package of the corresponding parser. For example, if the parser package is org.apache
and this
* parameter is set to *.demo
, the tree node classes will be located in the package
* org.apache.demo
. Default value is *.syntaxtree
.
*
* @parameter expression="${nodePackageName}"
*/
private String nodePackageName;
/**
* This option specifies the package for the generated visitors. This value may use a leading asterisk to reference
* the package of the corresponding parser. For example, if the parser package is org.apache
and this
* parameter is set to *.demo
, the visitor classes will be located in the package
* org.apache.demo
. Default value is *.visitor
.
*
* @parameter expression="${visitorPackageName}"
*/
private String visitorPackageName;
/**
* If true
, JTB will suppress its semantic error checking. Default value is false
.
*
* @parameter expression="${supressErrorChecking}"
*/
private Boolean supressErrorChecking;
/**
* If true
, all generated comments will be wrapped in <pre>
tags so that they
* are formatted correctly in API docs. Default value is false
.
*
* @parameter expression="${javadocFriendlyComments}"
*/
private Boolean javadocFriendlyComments;
/**
* Setting this option to true
causes JTB to generate field names that reflect the structure of the
* tree instead of generic names like f0
, f1
etc. Default value is false
.
*
* @parameter expression="${descriptiveFieldNames}"
*/
private Boolean descriptiveFieldNames;
/**
* The qualified name of a user-defined class from which all AST nodes will inherit. By default, AST nodes will
* inherit from the generated class Node
.
*
* @parameter expression="${nodeParentClass}"
*/
private String nodeParentClass;
/**
* If true
, all nodes will contain fields for its parent node. Default value is false
.
*
* @parameter expression="${parentPointers}"
*/
private Boolean parentPointers;
/**
* If true
, JTB will include JavaCC "special tokens" in the AST. Default value is false
.
*
* @parameter expression="${specialTokens}"
*/
private Boolean specialTokens;
/**
* If true
, JTB will generate the following files to support the Schema programming language:
* false
.
*
* @parameter expression="${scheme}"
*/
private Boolean scheme;
/**
* If true
, JTB will generate a syntax tree dumping visitor. Default value is false
.
*
* @parameter expression="${printer}"
*/
private Boolean printer;
/**
* The directory where the JavaCC grammar files (*.jtb
) are located. It will be recursively scanned
* for input files to pass to JTB.
*
* @parameter expression="${sourceDirectory}" default-value="${basedir}/src/main/jtb"
*/
private File sourceDirectory;
/**
* The directory where the output Java files will be located.
*
* @parameter expression="${outputDirectory}" default-value="${project.build.directory}/generated-sources/jtb"
*/
private File outputDirectory;
/**
* The directory to store the processed input files for later detection of stale sources.
*
* @parameter expression="${timestampDirectory}"
* default-value="${project.build.directory}/generated-sources/jtb-timestamp"
*/
private File timestampDirectory;
/**
* The granularity in milliseconds of the last modification date for testing whether a source needs recompilation.
*
* @parameter expression="${lastModGranularityMs}" default-value="0"
*/
private int staleMillis;
/**
* A set of Ant-like inclusion patterns used to select files from the source directory for processing. By default,
* the patterns **/*.jtb
and **/*.JTB
are used to select grammar files.
*
* @parameter
*/
private String[] includes;
/**
* A set of Ant-like exclusion patterns used to prevent certain files from being processed. By default, this set is
* empty such that no files are excluded.
*
* @parameter
*/
private String[] excludes;
/**
* {@inheritDoc}
*/
protected File getSourceDirectory()
{
return this.sourceDirectory;
}
/**
* {@inheritDoc}
*/
protected String[] getIncludes()
{
if ( this.includes != null )
{
return this.includes;
}
else
{
return new String[] { "**/*.jtb", "**/*.JTB" };
}
}
/**
* {@inheritDoc}
*/
protected String[] getExcludes()
{
return this.excludes;
}
/**
* {@inheritDoc}
*/
protected File getOutputDirectory()
{
return this.outputDirectory;
}
/**
* {@inheritDoc}
*/
protected File getTimestampDirectory()
{
return this.timestampDirectory;
}
/**
* {@inheritDoc}
*/
protected int getStaleMillis()
{
return this.staleMillis;
}
/**
* {@inheritDoc}
*/
protected void processGrammar( GrammarInfo grammarInfo )
throws MojoExecutionException, MojoFailureException
{
File jtbFile = grammarInfo.getGrammarFile();
File jjDirectory = new File( getOutputDirectory(), grammarInfo.getParserDirectory() );
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 ) );
// 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.run();
// create timestamp file
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 )
{
return this.packageName + ".syntaxtree";
}
else if ( this.nodePackageName != null )
{
return this.nodePackageName;
}
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 )
{
return this.packageName + ".visitor";
}
else if ( this.visitorPackageName != null )
{
return this.visitorPackageName;
}
else
{
return "*.visitor";
}
}
/**
* 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()
{
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 );
return jtb;
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/ForkedJvm.java 0000644 0001750 0001750 00000026001 11070232511 026762 0 ustar cavedon cavedon 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.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;
/**
* Runs the main()
method of some tool in a forked JVM.
*
* @author Benjamin Bentmann
* @version $Id: ForkedJvm.java 7758 2008-09-29 20:06:33Z bentmann $
* @see java - The Java Application
* Launcher
*/
class ForkedJvm
{
/**
* The consumer for System.out
messages.
*/
private StreamConsumer systemOut;
/**
* The consumer for System.err
messages.
*/
private StreamConsumer systemErr;
/**
* The executable used to fork the JVM.
*/
private String executable;
/**
* The working directory for the forked JVM.
*/
private File workingDirectory;
/**
* The class path entries for the forked JVM, given as strings.
*/
private Set classPathEntries = new LinkedHashSet();
/**
* The qualified name of the class on which to invoke the main()
method.
*/
private String mainClass;
/**
* The command line arguments to pass to the main()
method, given as strings.
*/
private List cmdLineArgs = new ArrayList();
/**
* Creates a new configuration to fork a JVM.
*/
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";
}
/**
* 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 )
{
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 )
{
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 )
{
this.systemErr = consumer;
}
/**
* Gets the class path for the forked JVM.
*
* @return The class path for the forked JVM.
*/
private String getClassPath()
{
return StringUtils.join( this.classPathEntries.iterator(), File.pathSeparator );
}
/**
* 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 );
}
}
/**
* 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() );
}
}
/**
* 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 ) );
}
/**
* 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() );
}
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() );
}
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 )
{
URL url;
if ( loader != null )
{
url = loader.getResource( resource );
}
else
{
url = ClassLoader.getSystemResource( resource );
}
return UrlUtils.getResourceRoot( url, resource );
}
return null;
}
/**
* 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 )
{
this.mainClass = 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 );
}
/**
* Gets the command line arguments for the main()
method.
*
* @return The command line arguments for the main()
method.
*/
private String[] getArguments()
{
return (String[]) this.cmdLineArgs.toArray( new String[this.cmdLineArgs.size()] );
}
/**
* 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 );
}
}
/**
* 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() );
}
}
/**
* 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 )
{
for ( int i = 0; i < arguments.length; i++ )
{
addArgument( arguments[i] );
}
}
}
/**
* 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()
{
/*
* 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
* setWorkingDirectory(File) and addArguments() rather than createArg().
*/
Commandline cli = new Commandline();
cli.setExecutable( this.executable );
if ( this.workingDirectory != null )
{
cli.setWorkingDirectory( this.workingDirectory.getAbsolutePath() );
}
String classPath = getClassPath();
if ( classPath != null && classPath.length() > 0 )
{
cli.addArguments( new String[] { "-cp", classPath } );
}
if ( this.mainClass != null && this.mainClass.length() > 0 )
{
cli.addArguments( new String[] { this.mainClass } );
}
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 );
}
/**
* 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() );
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JJTreeMojo.java 0000644 0001750 0001750 00000026725 11072177317 027076 0 ustar cavedon cavedon 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 org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Parses a JJTree grammar file (*.jjt
) and transforms it to Java source files and a JavaCC grammar
* file. Please see the JJTree Reference Documentation for
* more information.
*
* @goal jjtree
* @phase generate-sources
* @since 2.0
* @deprecated As of version 2.4, use the jjtree-javacc
goal instead.
* @author jesse 1.4
.
*
* @parameter expression="${jdkVersion}"
* @since 2.4
*/
private String jdkVersion;
/**
* A flag whether to generate sample implementations for SimpleNode
and any other nodes used in the
* grammar. Default value is true
.
*
* @parameter expression="${buildNodeFiles}"
*/
private Boolean buildNodeFiles;
/**
* A flag whether to generate a multi mode parse tree or a single mode parse tree. Default value is
* false
.
*
* @parameter expression="${multi}"
*/
private Boolean multi;
/**
* A flag whether to make each non-decorated production void instead of an indefinite node. Default value is
* false
.
*
* @parameter expression="${nodeDefaultVoid}"
*/
private Boolean nodeDefaultVoid;
/**
* The name of a custom class that extends SimpleNode
and will be used as the super class for the
* generated tree node classes. By default, the tree node classes will directly extend the class
* SimpleNode
.
*
* @parameter expression="${nodeClass}"
* @since 2.5
*/
private String nodeClass;
/**
* 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 expression="${nodeFactory}"
*/
private String nodeFactory;
/**
* The package to generate the AST node classes into. This value may use a leading asterisk to reference the package
* of the corresponding parser. For example, if the parser package is org.apache
and this parameter
* is set to *.demo
, the tree node classes will be located in the package
* org.apache.demo
. By default, the package of the corresponding parser is used.
*
* @parameter expression="${nodePackage}"
*/
private String nodePackage;
/**
* The prefix used to construct node class names from node identifiers in multi mode. Default value is
* AST
.
*
* @parameter expression="${nodePrefix}"
*/
private String nodePrefix;
/**
* A flag whether user-defined parser methods should be called on entry and exit of every node scope. Default value
* is false
.
*
* @parameter expression="${nodeScopeHook}"
*/
private Boolean nodeScopeHook;
/**
* A flag whether the node construction routines need an additional method parameter to receive the parser object.
* Default value is false
.
*
* @parameter expression="${nodeUsesParser}"
*/
private Boolean nodeUsesParser;
/**
* A flag whether to generate code for a static parser. Note that this setting must match the corresponding option
* for the javacc
mojo. Default value is true
.
*
* @parameter expression="${isStatic}" alias="staticOption"
*/
private Boolean isStatic;
/**
* A flag whether to insert the methods jjtGetFirstToken()
, jjtSetFirstToken()
,
* getLastToken()
and jjtSetLastToken()
into the class SimpleNode
. Default
* value is false
.
*
* @parameter expression="${trackTokens}"
* @since 2.5
*/
private Boolean trackTokens;
/**
* A flag whether to insert a jjtAccept()
method in the node classes and to generate a visitor
* implementation with an entry for every node type used in the grammar. Default value is false
.
*
* @parameter expression="${visitor}"
*/
private Boolean visitor;
/**
* The name of a class to use for the data argument of the jjtAccept()
and visit()
* methods. Default value is java.lang.Object
.
*
* @parameter expression="${visitorDataType}"
* @since 2.5
*/
private String visitorDataType;
/**
* The name of a class to use as the return type of the jjtAccept()
and visit()
methods.
* Default value is java.lang.Object
.
*
* @parameter expression="${visitorReturnType}"
* @since 2.5
*/
private String visitorReturnType;
/**
* The name of an exception class to include in the signature of the generated jjtAccept()
* and visit()
methods. By default, the throws
clause of the generated methods is
* empty such that only unchecked exceptions can be thrown.
*
* @parameter expression="${visitorException}"
*/
private String visitorException;
/**
* Directory where the input JJTree files (*.jjt
) are located.
*
* @parameter expression="${sourceDirectory}" default-value="${basedir}/src/main/jjtree"
*/
private File sourceDirectory;
/**
* Directory where the output Java files for the node classes and the JavaCC grammar file will be located.
*
* @parameter expression="${outputDirectory}" default-value="${project.build.directory}/generated-sources/jjtree"
*/
private File outputDirectory;
/**
* The directory to store the processed input files for later detection of stale sources.
*
* @parameter expression="${timestampDirectory}"
* default-value="${project.build.directory}/generated-sources/jjtree-timestamp"
*/
private File timestampDirectory;
/**
* The granularity in milliseconds of the last modification date for testing whether a source needs recompilation.
*
* @parameter expression="${lastModGranularityMs}" default-value="0"
*/
private int staleMillis;
/**
* A set of Ant-like inclusion patterns used to select files from the source directory for processing. By default,
* the patterns **/*.jjt
and **/*.JJT
are used to select grammar files.
*
* @parameter
*/
private String[] includes;
/**
* A set of Ant-like exclusion patterns used to prevent certain files from being processed. By default, this set is
* empty such that no files are excluded.
*
* @parameter
*/
private String[] excludes;
/**
* {@inheritDoc}
*/
protected File getSourceDirectory()
{
return this.sourceDirectory;
}
/**
* {@inheritDoc}
*/
protected String[] getIncludes()
{
if ( this.includes != null )
{
return this.includes;
}
else
{
return new String[] { "**/*.jjt", "**/*.JJT" };
}
}
/**
* {@inheritDoc}
*/
protected String[] getExcludes()
{
return this.excludes;
}
/**
* {@inheritDoc}
*/
protected File getOutputDirectory()
{
return this.outputDirectory;
}
/**
* {@inheritDoc}
*/
protected File getTimestampDirectory()
{
return this.timestampDirectory;
}
/**
* {@inheritDoc}
*/
protected int getStaleMillis()
{
return this.staleMillis;
}
/**
* {@inheritDoc}
*/
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 );
File nodeDirectory;
if ( nodePackageName != null )
{
nodeDirectory = new File( nodePackageName.replace( '.', File.separatorChar ) );
}
else
{
nodeDirectory = new File( grammarInfo.getParserDirectory() );
}
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.run();
// create timestamp file
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()
{
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 );
return jjtree;
}
/**
* 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()
{
// do nothing
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/GrammarDirectoryScanner.java 0000644 0001750 0001750 00000017407 10753435762 031716 0 ustar cavedon cavedon 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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.plexus.util.DirectoryScanner;
/**
* Scans source directories for JavaCC grammar files.
*
* @author Benjamin Bentmann
* @version $Id: GrammarDirectoryScanner.java 6282 2008-02-09 23:49:06Z bentmann $
*/
class GrammarDirectoryScanner
{
/**
* The directory scanner used to scan the source directory for files.
*/
private DirectoryScanner scanner;
/**
* 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.
*/
private File outputDirectory;
// TODO: Once the parameter "packageName" from the javacc mojo has been deleted, remove this field, too.
/**
* The package name for the generated parser, may be null
to use the package declaration from the
* grammar file.
*/
private String parserPackage;
/**
* The granularity in milliseconds of the last modification date for testing whether a grammar file needs
* recompilation because its corresponding target file is stale.
*/
private int staleMillis;
/**
* A set of grammar infos describing the included grammar files, must never be null
.
*/
private List includedGrammars;
/**
* Creates a new grammar directory scanner.
*/
public GrammarDirectoryScanner()
{
this.scanner = new DirectoryScanner();
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 );
}
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 )
{
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 );
}
/**
* 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 );
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 );
}
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 )
{
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
{
this.includedGrammars.clear();
this.scanner.scan();
String[] includedFiles = this.scanner.getIncludedFiles();
for ( int i = 0; i < includedFiles.length; i++ )
{
String includedFile = includedFiles[i];
GrammarInfo grammarInfo = new GrammarInfo( this.scanner.getBasedir(), includedFile, this.parserPackage );
if ( this.outputDirectory != null )
{
File sourceFile = grammarInfo.getGrammarFile();
File[] targetFiles = getTargetFiles( this.outputDirectory, includedFile, grammarInfo );
for ( int j = 0; j < targetFiles.length; j++ )
{
File targetFile = targetFiles[j];
if ( !targetFile.exists()
|| targetFile.lastModified() + this.staleMillis < sourceFile.lastModified() )
{
this.includedGrammars.add( grammarInfo );
break;
}
}
}
else
{
this.includedGrammars.add( grammarInfo );
}
}
}
/**
* 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
* null
.
* @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 };
}
/**
* 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()
{
return (GrammarInfo[]) this.includedGrammars.toArray( new GrammarInfo[this.includedGrammars.size()] );
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/GrammarInfo.java 0000644 0001750 0001750 00000024033 11113311543 027301 0 ustar cavedon cavedon 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.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.codehaus.plexus.util.FileUtils;
/**
* 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
* @version $Id: GrammarInfo.java 8156 2008-11-26 18:20:19Z bentmann $
*/
class GrammarInfo
{
/**
* The absolute path to the base directory in which the grammar file resides.
*/
private final File sourceDirectory;
/**
* The path to the grammar file (relative to its source directory, e.g. "grammars/MyParser.jj").
*/
private final String grammarFile;
/**
* The declared package for the generated parser (e.g. "org.apache").
*/
private final String parserPackage;
/**
* The path to the directory of the parser package (relative to a source root directory, e.g. "org/apache").
*/
private final String parserDirectory;
/**
* The simple name of the generated parser (e.g. "MyParser").
*/
private final String parserName;
/**
* The path to the generated parser file (relative to a source root directory, e.g. "org/apache/MyParser.java").
*/
private final String parserFile;
/**
* 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 );
}
/**
* 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
.
* @param packageName The package name for the generated parser, may be null
to use the package
* 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 );
}
this.sourceDirectory = sourceDir;
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 );
}
// NOTE: JavaCC uses the platform default encoding to read files, so must we
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
{
this.parserPackage = packageName;
}
this.parserDirectory = this.parserPackage.replace( '.', File.separatorChar );
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
{
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 )
{
final String packageDeclaration = "package\\s+([^\\s.;]+(\\.[^\\s.;]+)*)\\s*;";
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 )
{
final String parserBegin = "PARSER_BEGIN\\s*\\(\\s*([^\\s\\)]+)\\s*\\)";
Matcher matcher = Pattern.compile( parserBegin ).matcher( grammar );
if ( matcher.find() )
{
return matcher.group( 1 );
}
return "";
}
/**
* 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()
{
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 );
}
/**
* 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()
{
return this.grammarFile;
}
/**
* Resolves the specified package name against the package name of the parser generated from this grammar. To
* 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 )
{
String resolvedPackageName = packageName;
if ( resolvedPackageName != null && resolvedPackageName.startsWith( "*" ) )
{
resolvedPackageName = getParserPackage() + resolvedPackageName.substring( 1 );
if ( resolvedPackageName.startsWith( "." ) )
{
resolvedPackageName = resolvedPackageName.substring( 1 );
}
}
return resolvedPackageName;
}
/**
* 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()
{
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()
{
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()
{
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()
{
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()
{
return getGrammarFile() + " -> " + getParserFile();
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JJTree.java 0000644 0001750 0001750 00000032053 11250747644 026244 0 ustar cavedon cavedon 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.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
/**
* Provides a facade for the mojos to invoke JJTree.
*
* @author Benjamin Bentmann
* @version $Id: JJTree.java 10603 2009-09-06 15:05:08Z bentmann $
* @see JJTree Reference
*/
class JJTree
extends ToolFacade
{
/**
* The input grammar.
*/
private File inputFile;
/**
* The option OUTPUT_DIRECTORY.
*/
private File outputDirectory;
/**
* The option GRAMMAR_ENCODING.
*/
private String grammarEncoding;
/**
* The option JDK_VERSION.
*/
private String jdkVersion;
/**
* The option STATIC.
*/
private Boolean isStatic;
/**
* The option BUILD_NODE_FILES.
*/
private Boolean buildNodeFiles;
/**
* The option MULTI.
*/
private Boolean multi;
/**
* The option NODE_DEFAULT_VOID.
*/
private Boolean nodeDefaultVoid;
/**
* The option NODE_CLASS.
*/
private String nodeClass;
/**
* The option NODE_FACTORY.
*/
private String nodeFactory;
/**
* The option NODE_PACKAGE.
*/
private String nodePackage;
/**
* The option NODE_PREFIX.
*/
private String nodePrefix;
/**
* The option NODE_SCOPE_HOOK.
*/
private Boolean nodeScopeHook;
/**
* The option NODE_USES_PARSER.
*/
private Boolean nodeUsesParser;
/**
* The option TRACK_TOKENS.
*/
private Boolean trackTokens;
/**
* The option VISITOR.
*/
private Boolean visitor;
/**
* The option VISITOR_DATA_TYPE.
*/
private String visitorDataType;
/**
* The option VISITOR_RETURN_TYPE.
*/
private String visitorReturnType;
/**
* The option VISITOR_EXCEPTION.
*/
private String visitorException;
/**
* 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 );
}
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 );
}
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()
{
File outputFile = null;
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
this.visitorException = value;
}
/**
* {@inheritDoc}
*/
protected int execute()
throws Exception
{
String[] args = generateArguments();
if ( this.outputDirectory != null && !this.outputDirectory.exists() )
{
this.outputDirectory.mkdirs();
}
org.javacc.jjtree.JJTree jjtree = new org.javacc.jjtree.JJTree();
return jjtree.main( args );
}
/**
* Assembles the command line arguments for the invocation of JJTree according to the configuration.null
.
*/
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 )
{
this.log = new SystemStreamLog();
}
return this.log;
}
/**
* Gets the name of the tool.
*
* @return The name of the tool, never null
.
*/
protected String getToolName()
{
String name = getClass().getName();
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
{
int exitCode;
try
{
if ( getLog().isDebugEnabled() )
{
getLog().debug( "Running " + getToolName() + ": " + this );
}
exitCode = execute();
}
catch ( Exception e )
{
throw new MojoExecutionException( "Failed to execute " + getToolName(), e );
}
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;
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/UrlUtils.java 0000644 0001750 0001750 00000013020 11017732160 026661 0 ustar cavedon cavedon 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.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/**
* Assists in handling of URLs.
*
* @author Benjamin Bentmann
* @version $Id: UrlUtils.java 7084 2008-05-30 08:01:52Z bentmann $
*/
class UrlUtils
{
/**
* The UTF-8 character set, used to decode octets in URLs.
*/
private static final Charset UTF8 = Charset.forName( "UTF-8" );
/**
* The protocol prefix for "jar:" URLs.
*/
private static final String JAR = "jar:";
/**
* The protocol prefix for "file:" URLs.
*/
private static final String FILE = "file:";
/**
* The protocol prefix for "jar:file:" URLs.
*/
private static final String JAR_FILE = JAR + FILE;
/**
* 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 )
{
String path = null;
if ( url != null )
{
String spec = url.toExternalForm();
if ( ( JAR_FILE ).regionMatches( true, 0, spec, 0, JAR_FILE.length() ) )
{
URL jar;
try
{
jar = new URL( spec.substring( JAR.length(), spec.lastIndexOf( "!/" ) ) );
}
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 );
}
}
return ( path != null ) ? new File( path ) : null;
}
/**
* Decodes the specified URL as per RFC 3986, i.e. transforms percent-encoded octets to characters by decoding with
* the UTF-8 character set. This function is primarily intended for usage with {@link java.net.URL} which
* 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 )
{
String decoded = url;
if ( url != null && url.indexOf( '%' ) >= 0 )
{
int n = url.length();
StringBuffer buffer = new StringBuffer();
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 ) == '%' );
continue;
}
catch ( RuntimeException e )
{
// malformed percent-encoded octet, fall through and append characters literally
}
finally
{
if ( bytes.position() > 0 )
{
bytes.flip();
buffer.append( UTF8.decode( bytes ).toString() );
bytes.clear();
}
}
}
buffer.append( url.charAt( i++ ) );
}
decoded = buffer.toString();
}
return decoded;
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JJDoc.java 0000644 0001750 0001750 00000017336 11250747644 026061 0 ustar cavedon cavedon 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.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.StreamConsumer;
/**
* Provides a facade for the mojos to invoke JJDoc.
*
* @author Paul Gier, Benjamin Bentmann
* @version $Id: JJDoc.java 10603 2009-09-06 15:05:08Z bentmann $
* @see JJDoc Reference
*/
class JJDoc
extends ToolFacade
{
/**
* The input grammar.
*/
private File inputFile;
/**
* The option OUTPUT_FILE.
*/
private File outputFile;
/**
* The option GRAMMAR_ENCODING.
*/
private String grammarEncoding;
/**
* The option CSS.
*/
private String cssHref;
/**
* The option TEXT.
*/
private Boolean text;
/**
* The option BNF.
*/
private Boolean bnf;
/**
* The option ONE_TABLE.
*/
private Boolean oneTable;
/**
* 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 );
}
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 );
}
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
this.oneTable = value;
}
/**
* {@inheritDoc}
*/
protected int execute()
throws Exception
{
String[] args = generateArguments();
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 );
}
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()
{
List argsList = new ArrayList();
if ( StringUtils.isNotEmpty( this.grammarEncoding ) )
{
argsList.add( "-GRAMMAR_ENCODING=" + this.grammarEncoding );
}
if ( this.text != null )
{
argsList.add( "-TEXT=" + this.text );
}
if ( this.bnf != null )
{
argsList.add( "-BNF=" + this.bnf );
}
if ( this.oneTable != null )
{
argsList.add( "-ONE_TABLE=" + this.oneTable );
}
if ( this.outputFile != null )
{
argsList.add( "-OUTPUT_FILE=" + this.outputFile.getAbsolutePath() );
}
if ( StringUtils.isNotEmpty( this.cssHref ) )
{
argsList.add( "-CSS=" + this.cssHref );
}
if ( this.inputFile != null )
{
argsList.add( this.inputFile.getAbsolutePath() );
}
return (String[]) argsList.toArray( new String[argsList.size()] );
}
/**
* 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();
}
/**
* Consume and log command line output from the JJDoc process.
*/
class MojoLogStreamConsumer
implements StreamConsumer
{
/**
* The line prefix used by JJDoc to report errors.
*/
private static final String ERROR_PREFIX = "Error: ";
/**
* The line prefix used by JJDoc to report warnings.
*/
private static final String WARN_PREFIX = "Warning: ";
/**
* Determines if the stream consumer is being used for System.out
or System.err
.
*/
private boolean err;
/**
* Single param constructor.
*
* @param error If set to true
, all consumed lines will be logged at the error level.
*/
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 );
}
}
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/LegacyGrammarDirectoryScanner.java 0000644 0001750 0001750 00000003273 10753057643 033035 0 ustar cavedon cavedon 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;
/**
* Scans source directories for JavaCC grammar files. This scanner supports {@link JJTreeMojo} and {@link JTBMojo} which
* 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: LegacyGrammarDirectoryScanner.java 6251 2008-02-08 13:56:51Z bentmann $
*/
class LegacyGrammarDirectoryScanner
extends GrammarDirectoryScanner
{
/**
* {@inheritDoc}
*/
protected File[] getTargetFiles( File targetDirectory, String grammarFile, GrammarInfo grammarInfo )
{
File timestampFile = new File( targetDirectory, grammarFile );
return new File[] { timestampFile };
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JavaCCMojo.java 0000644 0001750 0001750 00000013032 11113311543 027010 0 ustar cavedon cavedon 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 org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* 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.
*
* @goal javacc
* @phase generate-sources
* @since 2.0
* @author jruiz@exist.com
* @author jesse *.jj
) are located.
*
* @parameter expression="${sourceDirectory}" default-value="${basedir}/src/main/javacc"
*/
private File sourceDirectory;
/**
* The directory where the parser files generated by JavaCC will be stored. The directory will be registered as a
* compile source root of the project such that the generated files will participate in later build phases like
* compiling and packaging.
*
* @parameter expression="${outputDirectory}" default-value="${project.build.directory}/generated-sources/javacc"
*/
private File outputDirectory;
/**
* The granularity in milliseconds of the last modification date for testing whether a source needs recompilation.
*
* @parameter expression="${lastModGranularityMs}" default-value="0"
*/
private int staleMillis;
/**
* A set of Ant-like inclusion patterns used to select files from the source directory for processing. By default,
* the patterns **/*.jj
and **/*.JJ
are used to select grammar files.
*
* @parameter
*/
private String[] includes;
/**
* A set of Ant-like exclusion patterns used to prevent certain files from being processed. By default, this set is
* empty such that no files are excluded.
*
* @parameter
*/
private String[] excludes;
/**
* {@inheritDoc}
*/
protected File getSourceDirectory()
{
return this.sourceDirectory;
}
/**
* {@inheritDoc}
*/
protected String[] getIncludes()
{
if ( this.includes != null )
{
return this.includes;
}
else
{
return new String[] { "**/*.jj", "**/*.JJ" };
}
}
/**
* {@inheritDoc}
*/
protected String[] getExcludes()
{
return this.excludes;
}
/**
* {@inheritDoc}
*/
protected File getOutputDirectory()
{
return this.outputDirectory;
}
/**
* {@inheritDoc}
*/
protected int getStaleMillis()
{
return this.staleMillis;
}
/**
* {@inheritDoc}
*/
protected File[] getCompileSourceRoots()
{
return new File[] { getOutputDirectory() };
}
/**
* {@inheritDoc}
*/
protected String getParserPackage()
{
return this.packageName;
}
/**
* {@inheritDoc}
*/
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" );
// generate parser files
JavaCC javacc = newJavaCC();
javacc.setInputFile( jjFile );
javacc.setOutputDirectory( parserDirectory );
javacc.run();
// copy parser files from JavaCC
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, "*" );
}
deleteTempDirectory( tempDirectory );
}
}
javacc-maven-plugin-2.6/src/main/java/org/codehaus/mojo/javacc/JavaCC.java 0000644 0001750 0001750 00000042052 11250747644 026210 0 ustar cavedon cavedon 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.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.codehaus.plexus.util.StringUtils;
/**
* Provides a facade for the mojos to invoke JavaCC.
*
* @author Benjamin Bentmann
* @version $Id: JavaCC.java 10603 2009-09-06 15:05:08Z bentmann $
* @see JavaCC Command Line Syntax
*/
class JavaCC
extends ToolFacade
{
/**
* The input grammar.
*/
private File inputFile;
/**
* The option OUTPUT_DIRECTORY.
*/
private File outputDirectory;
/**
* The option GRAMMAR_ENCODING.
*/
private String grammarEncoding;
/**
* The option JDK_VERSION.
*/
private String jdkVersion;
/**
* The option STATIC.
*/
private Boolean isStatic;
/**
* The option LOOK_AHEAD.
*/
private Integer lookAhead;
/**
* The option CHOICE_AMBIGUITY_CHECK.
*/
private Integer choiceAmbiguityCheck;
/**
* The option OTHER_AMBIGUITY_CHECK.
*/
private Integer otherAmbiguityCheck;
/**
* The option DEBUG_PARSER.
*/
private Boolean debugParser;
/**
* The option DEBUG_LOOK_AHEAD.
*/
private Boolean debugLookAhead;
/**
* The option DEBUG_TOKEN_MANAGER.
*/
private Boolean debugTokenManager;
/**
* The option ERROR_REPORTING.
*/
private Boolean errorReporting;
/**
* The option JAVA_UNICODE_ESCAPE.
*/
private Boolean javaUnicodeEscape;
/**
* The option UNICODE_INPUT.
*/
private Boolean unicodeInput;
/**
* The option IGNORE_CASE.
*/
private Boolean ignoreCase;
/**
* The option COMMON_TOKEN_ACTION.
*/
private Boolean commonTokenAction;
/**
* The option USER_TOKEN_MANAGER.
*/
private Boolean userTokenManager;
/**
* The option USER_CHAR_STREAM.
*/
private Boolean userCharStream;
/**
* The option BUILD_PARSER.
*/
private Boolean buildParser;
/**
* The option BUILD_TOKEN_MANAGER.
*/
private Boolean buildTokenManager;
/**
* The option TOKEN_MANAGER_USES_PARSER.
*/
private Boolean tokenManagerUsesParser;
/**
* The option TOKEN_EXTENDS.
*/
private String tokenExtends;
/**
* The option TOKEN_FACTORY.
*/
private String tokenFactory;
/**
* The option SANITY_CHECK.
*/
private Boolean sanityCheck;
/**
* The option FORCE_LA_CHECK.
*/
private Boolean forceLaCheck;
/**
* The option CACHE_TOKENS.
*/
private Boolean cacheTokens;
/**
* The option KEEP_LINE_COLUMN.
*/
private Boolean keepLineColumn;
/**
* The option SUPPORT_CLASS_VISIBILITY_PUBLIC.
*/
private Boolean supportClassVisibilityPublic;
/**
* 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 );
}
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 );
}
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
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 )
{
this.supportClassVisibilityPublic = value;
}
/**
* {@inheritDoc}
*/
protected int execute()
throws Exception
{
String[] args = generateArguments();
if ( this.outputDirectory != null && !this.outputDirectory.exists() )
{
this.outputDirectory.mkdirs();
}
return org.javacc.parser.Main.mainProgram( args );
}
/**
* Assembles the command line arguments for the invocation of JavaCC according to the configuration.null
if either the
* input file or the output directory have not been set.
*/
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 );
}
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 );
}
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 )
{
return this.nodeDirectory;
}
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 );
}
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 )
{
return this.visitorDirectory;
}
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 )
{
this.packageName = value;
}
/**
* Sets the option "-np".
*
* @param value The option value, may be null
.
*/
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 )
{
return ( this.packageName.length() <= 0 ) ? SYNTAX_TREE : this.packageName + '.' + SYNTAX_TREE;
}
else if ( this.nodePackageName != null )
{
return this.nodePackageName;
}
else
{
return SYNTAX_TREE;
}
}
/**
* Sets the option "-vp".
*
* @param value The option value, may be null
.
*/
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 )
{
return ( this.packageName.length() <= 0 ) ? VISITOR : this.packageName + '.' + VISITOR;
}
else if ( this.visitorPackageName != null )
{
return this.visitorPackageName;
}
else
{
return VISITOR;
}
}
/**
* Sets the option "-e".
*
* @param value The option value, may be null
.
*/
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 )
{
this.javadocFriendlyComments = value;
}
/**
* Sets the option "-f".
*
* @param value The option value, may be null
.
*/
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 )
{
this.nodeParentClass = value;
}
/**
* Sets the option "-pp".
*
* @param value The option value, may be null
.
*/
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 )
{
this.specialTokens = value;
}
/**
* Sets the toolkit option "-scheme".
*
* @param value The option value, may be null
.
*/
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 )
{
this.printer = value;
}
/**
* {@inheritDoc}
*/
protected int execute()
throws Exception
{
String[] args = generateArguments();
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 );
}
int exitcode = jvm.run();
moveJavaFiles();
return exitcode;
}
/**
* 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()
{
List argsList = new ArrayList();
argsList.add( "-np" );
argsList.add( getEffectiveNodePackageName() );
argsList.add( "-vp" );
argsList.add( getEffectiveVisitorPackageName() );
if ( this.supressErrorChecking != null && this.supressErrorChecking.booleanValue() )
{
argsList.add( "-e" );
}
if ( this.javadocFriendlyComments != null && this.javadocFriendlyComments.booleanValue() )
{
argsList.add( "-jd" );
}
if ( this.descriptiveFieldNames != null && this.descriptiveFieldNames.booleanValue() )
{
argsList.add( "-f" );
}
if ( this.nodeParentClass != null )
{
argsList.add( "-ns" );
argsList.add( this.nodeParentClass );
}
if ( this.parentPointers != null && this.parentPointers.booleanValue() )
{
argsList.add( "-pp" );
}
if ( this.specialTokens != null && this.specialTokens.booleanValue() )
{
argsList.add( "-tk" );
}
if ( this.scheme != null && this.scheme.booleanValue() )
{
argsList.add( "-scheme" );
}
if ( this.printer != null && this.printer.booleanValue() )
{
argsList.add( "-printer" );
}
File outputFile = getOutputFile();
if ( outputFile != null )
{
argsList.add( "-o" );
argsList.add( outputFile.getAbsolutePath() );
}
if ( this.inputFile != null )
{
argsList.add( this.inputFile.getAbsolutePath() );
}
return (String[]) argsList.toArray( new String[argsList.size()] );
}
/**
* 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 );
}
return null;
}
/**
* 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();
File nodeDstDir = getEffectiveNodeDirectory();
moveDirectory( nodeSrcDir, nodeDstDir );
File visitorSrcDir = new File( getLastPackageName( getEffectiveVisitorPackageName() ) ).getAbsoluteFile();
File visitorDstDir = getEffectiveVisitorDirectory();
moveDirectory( visitorSrcDir, visitorDstDir );
}
/**
* Moves all Java files generated by JTB from the specified source directory to the given target directory. Existing
* files in the target directory will be overwritten. Note that this move assumes a flat source directory, i.e.
* copying of sub directories is not supported.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 );
/*
* 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 )
{
return;
}
for ( int i = 0; i < sourceFiles.length; i++ )
{
File sourceFile = sourceFiles[i];
if ( sourceFile.isFile() && sourceFile.getName().endsWith( ".java" ) )
{
try
{
FileUtils.copyFileToDirectory( sourceFile, targetDir );
if ( !sourceFile.delete() )
{
getLog().error( "Failed to delete original JTB output file: " + sourceFile );
}
}
catch ( Exception e )
{
throw new IOException( "Failed to move JTB output file: " + sourceFile + " -> " + targetDir );
}
}
}
if ( 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 );
}
}
/**
* 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();
}
/**
* Consume and log command line output from the JJDoc process.
*/
class MojoLogStreamConsumer
implements StreamConsumer
{
/**
* The line prefix used by JTB to report infos.
*/
private static final String INFO_PREFIX = "JTB: ";
/**
* Determines if the stream consumer is being used for System.out
or System.err
.
*/
private boolean err;
/**
* Single param constructor.
*
* @param error If set to true
, all consumed lines will be logged at the error level.
*/
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 );
}
}
}
}
javacc-maven-plugin-2.6/src/main/resources/ 0000755 0001750 0001750 00000000000 11411772440 020556 5 ustar cavedon cavedon javacc-maven-plugin-2.6/src/main/resources/NOTICE 0000644 0001750 0001750 00000000255 10756563055 021477 0 ustar cavedon cavedon Codehaus Mojo javacc-maven-plugin
Copyright 2001-2008 (C) The original author or authors.
This product includes software developed at
The Codehaus (http://codehaus.org/).
javacc-maven-plugin-2.6/src/main/resources/jjdoc-report_de.properties 0000644 0001750 0001750 00000002110 10741176350 025743 0 ustar cavedon cavedon #
# 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.
#
report.jjdoc.name=JJDoc Bericht
report.jjdoc.title=JJDoc Bericht
report.jjdoc.short.description=Dokumentation der JavaCC Grammatiken.
report.jjdoc.description=Diese Seite bietet eine Übersicht der JJDoc Dokumentation zu den von JavaCC verarbeiteten Grammatiken.
report.jjdoc.table.heading=Grammatikdatei
javacc-maven-plugin-2.6/src/main/resources/jjdoc-report_en.properties 0000644 0001750 0001750 00000002304 10741176350 025762 0 ustar cavedon cavedon #
# 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.
#
# NOTE:
# This bundle is intentionally empty because English strings are provided by the base bundle via the parent chain. It
# must be provided nevertheless such that a request for locale "en" will not errorneously pick up the bundle for the
# JVM's default locale (which need not be "en"). See the method javadoc about
# ResourceBundle.getBundle(String, Locale, ClassLoader)
# for a full description of the lookup strategy.
javacc-maven-plugin-2.6/src/main/resources/jjdoc-report.properties 0000644 0001750 0001750 00000002067 10740505605 025304 0 ustar cavedon cavedon #
# 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.
#
report.jjdoc.name=JJDoc Report
report.jjdoc.title=JJDoc Reports
report.jjdoc.short.description=JavaCC grammar documentation.
report.jjdoc.description=This page provides a list of the JJDoc reports that were generated for the JavaCC grammar files.
report.jjdoc.table.heading=Grammar File
javacc-maven-plugin-2.6/src/site/ 0000755 0001750 0001750 00000000000 11411772440 016564 5 ustar cavedon cavedon javacc-maven-plugin-2.6/src/site/apt/ 0000755 0001750 0001750 00000000000 11411772440 017350 5 ustar cavedon cavedon javacc-maven-plugin-2.6/src/site/apt/index.apt.vm 0000644 0001750 0001750 00000011262 11113552622 021605 0 ustar cavedon cavedon ------
Introduction
------
If you have custom source files like a hand-crafted Token.java
and want to use these files
instead of the ones generated by JavaCC/JJTree/JTB, simply store your custom sources in the ordinary
directory for Java sources, i.e. usually src/main/java
. This will prevent the plugin from
generating these files.
For plugin versions prior to 2.5, you will need to put any custom source files directly next to the grammar file instead. The plugin will then copy your sources to the output directory of the generated parser file such that they eventually make it onto your class path. This approach is still supported by newer plugin versions but not recommended.
JavaCC
facade.
*
* @author Benjamin Bentmann
* @version $Id: JavaCCTest.java 6198 2008-02-03 21:32:31Z bentmann $
*/
public class JavaCCTest
extends TestCase
{
public void testToStringNullSafe()
throws Exception
{
JavaCC tool = new JavaCC();
String string = tool.toString();
assertNotNull( string );
assertTrue( string.indexOf( "null" ) < 0 );
}
public void testSettersNullSafe()
throws Exception
{
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 );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/JJDocTest.java 0000644 0001750 0001750 00000003067 10751431357 026744 0 ustar cavedon cavedon 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 junit.framework.TestCase;
/**
* Tests JJDoc
facade.
*
* @author Benjamin Bentmann
* @version $Id: JJDocTest.java 6198 2008-02-03 21:32:31Z bentmann $
*/
public class JJDocTest
extends TestCase
{
public void testToStringNullSafe()
throws Exception
{
JJDoc tool = new JJDoc();
String string = tool.toString();
assertNotNull( string );
assertTrue( string.indexOf( "null" ) < 0 );
}
public void testSettersNullSafe()
throws Exception
{
JJDoc tool = new JJDoc();
tool.setInputFile( null );
tool.setOutputFile( null );
tool.setOneTable( null );
tool.setText( null );
tool.setLog( null );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/GrammarInfoTest.java 0000644 0001750 0001750 00000012144 10753435762 030217 0 ustar cavedon cavedon 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.io.IOException;
import java.net.URI;
import junit.framework.TestCase;
/**
* Tests GrammarInfo
.
*
* @author Benjamin Bentmann
* @version $Id: GrammarInfoTest.java 6282 2008-02-09 23:49:06Z bentmann $
*/
public class GrammarInfoTest
extends TestCase
{
public void testInvalidFile()
throws Exception
{
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 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 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 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 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 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 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 );
File sourceDir = grammarFile.getParentFile();
return new GrammarInfo( sourceDir, grammarFile.getName() );
}
private File getGrammar( String resource )
throws Exception
{
return new File( new URI( getClass().getResource( '/' + resource ).toString() ) );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/JJTreeTest.java 0000644 0001750 0001750 00000004571 10753417337 027143 0 ustar cavedon cavedon 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 junit.framework.TestCase;
/**
* Tests JJTree
facade.
*
* @author Benjamin Bentmann
* @version $Id: JJTreeTest.java 6281 2008-02-09 21:45:03Z bentmann $
*/
public class JJTreeTest
extends TestCase
{
public void testToStringNullSafe()
throws Exception
{
JJTree tool = new JJTree();
String string = tool.toString();
assertNotNull( string );
assertTrue( string.indexOf( "null" ) < 0 );
}
public void testSettersNullSafe()
throws Exception
{
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 );
}
public void testGetOutputFile()
throws Exception
{
File input = new File( "Test.jjt" ).getAbsoluteFile();
File outdir = new File( "dir" ).getAbsoluteFile();
JJTree tool = new JJTree();
tool.setInputFile( input );
tool.setOutputDirectory( outdir );
File output = tool.getOutputFile();
assertEquals( new File( outdir, "Test.jj" ), output );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/ForkedJvmTest.java 0000644 0001750 0001750 00000007353 11134054525 027676 0 ustar cavedon cavedon 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 org.codehaus.plexus.util.cli.CommandLineUtils.StringStreamConsumer;
import junit.framework.TestCase;
/**
* Tests ForkedJvm
.
*
* @author Benjamin Bentmann
* @version $Id: ForkedJvmTest.java 8698 2009-01-16 09:54:29Z bentmann $
*/
public class ForkedJvmTest
extends TestCase
{
public void testToStringNullSafe()
throws Exception
{
ForkedJvm jvm = new ForkedJvm();
String string = jvm.toString();
assertNotNull( string );
assertTrue( string.indexOf( "null" ) < 0 );
}
public void testSettersNullSafe()
throws Exception
{
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 );
}
public void testSetMainClass()
throws Exception
{
ForkedJvm jvm1 = new ForkedJvm();
jvm1.setMainClass( MainStub.class );
String cmd1 = jvm1.toString();
assertTrue( cmd1.indexOf( MainStub.class.getName() ) >= 0 );
ForkedJvm jvm2 = new ForkedJvm();
jvm2.setMainClass( MainStub.class.getName() );
String cmd2 = jvm2.toString();
assertTrue( cmd2.indexOf( MainStub.class.getName() ) >= 0 );
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() );
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 );
int exitcode = jvm.run();
String out = stdout.getOutput();
String err = stderr.getOutput();
String[] args = out.split( "(\r\n)|(\r)|(\n)" );
assertEquals( 27, exitcode );
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] ) );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/UrlUtilsTest.java 0000644 0001750 0001750 00000013234 11017634224 027565 0 ustar cavedon cavedon 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.net.URL;
import junit.framework.TestCase;
/**
* Tests UrlUtils
.
*
* @author Benjamin Bentmann
* @version $Id: UrlUtilsTest.java 7083 2008-05-29 23:13:24Z bentmann $
*/
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 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 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 testGetResourceRootNullSafe()
throws Exception
{
assertNull( UrlUtils.getResourceRoot( null, "" ) );
}
public void testGetResourceRootUnknownProtocal()
throws Exception
{
try
{
UrlUtils.getResourceRoot( new URL( "http://www.foo.bar/index.html" ), "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 ) );
}
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( "\u00E4\u00F6\u00FC\u00DF", UrlUtils.decodeUrl( "\u00E4\u00F6\u00FC\u00DF" ) );
assertEquals( "%", UrlUtils.decodeUrl( "%" ) );
assertEquals( "%2", UrlUtils.decodeUrl( "%2" ) );
assertEquals( "%2G", UrlUtils.decodeUrl( "%2G" ) );
}
public void testDecodeUrlNullSafe()
{
assertNull( UrlUtils.decodeUrl( null ) );
}
public void testDecodeUrlEncodingUtf8()
{
assertEquals( "\u00E4\u00F6\u00FC\u00DF", UrlUtils.decodeUrl( "%C3%A4%C3%B6%C3%BC%C3%9F" ) );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/JTBTest.java 0000644 0001750 0001750 00000004664 10753417337 026442 0 ustar cavedon cavedon 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 junit.framework.TestCase;
/**
* Tests JTB
facade.
*
* @author Benjamin Bentmann
* @version $Id: JTBTest.java 6281 2008-02-09 21:45:03Z bentmann $
*/
public class JTBTest
extends TestCase
{
public void testToStringNullSafe()
throws Exception
{
JTB tool = new JTB();
String string = tool.toString();
assertNotNull( string );
assertTrue( string.indexOf( "null" ) < 0 );
}
public void testSettersNullSafe()
throws Exception
{
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 );
}
public void testGetOutputFile()
throws Exception
{
File input = new File( "Test.jtb" ).getAbsoluteFile();
File outdir = new File( "dir" ).getAbsoluteFile();
JTB tool = new JTB();
tool.setInputFile( input );
tool.setOutputDirectory( outdir );
File output = tool.getOutputFile();
assertEquals( new File( outdir, "Test.jj" ), output );
}
}
javacc-maven-plugin-2.6/src/test/java/org/codehaus/mojo/javacc/MainStub.java 0000644 0001750 0001750 00000002404 10752135053 026662 0 ustar cavedon cavedon 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.
*/
/**
* Supports {@link ForkedJvmTest}.
*
* @author Benjamin Bentmann
* @version $Id: MainStub.java 6212 2008-02-05 19:34:03Z bentmann $
*/
public class MainStub
{
public static void main( String[] args )
{
for ( int i = 0; i < args.length; i++ )
{
System.out.println( args[i] );
}
System.err.println( System.getProperty( "user.dir" ) );
System.exit( 27 );
}
}
javacc-maven-plugin-2.6/src/test/resources/ 0000755 0001750 0001750 00000000000 11411772436 020616 5 ustar cavedon cavedon javacc-maven-plugin-2.6/src/test/resources/Parser2.jj 0000644 0001750 0001750 00000000772 10747643633 022476 0 ustar cavedon cavedon
options {
LOOKAHEAD = 1;
CHOICE_AMBIGUITY_CHECK = 2;
OTHER_AMBIGUITY_CHECK = 1;
STATIC = true;
DEBUG_PARSER = false;
}
PARSER_BEGIN(SimpleParser)
// use default package
public class SimpleParser {
public static void main(String args[]) throws ParseException {
SimpleParser parser = new SimpleParser(System.in);
parser.Input();
}
}
PARSER_END(SimpleParser)
void Input() :
{}
{
MatchedBraces() ("\n"|"\r")*