From 5fb64ceb02525c3d6b8b47157e2683b74ef7eea4 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Sun, 12 Nov 2023 16:42:55 +0100 Subject: [PATCH] Enable spotless for code formatting - reformat --- pom.xml | 73 +- .../codehaus/mojo/exec/AbstractExecMojo.java | 165 ++-- .../org/codehaus/mojo/exec/AbstractPath.java | 35 +- .../codehaus/mojo/exec/AbstractProperty.java | 4 +- .../org/codehaus/mojo/exec/Classpath.java | 4 +- .../codehaus/mojo/exec/EnvStreamConsumer.java | 122 +-- .../org/codehaus/mojo/exec/ExecJavaMojo.java | 675 ++++++------- .../java/org/codehaus/mojo/exec/ExecMojo.java | 920 +++++++----------- .../mojo/exec/ExecutableDependency.java | 57 +- .../codehaus/mojo/exec/ExtendedExecutor.java | 44 +- .../mojo/exec/LineRedirectOutputStream.java | 2 +- .../org/codehaus/mojo/exec/Modulepath.java | 4 +- .../codehaus/mojo/exec/PathsToolchain.java | 119 ++- .../mojo/exec/PathsToolchainFactory.java | 290 +++--- .../codehaus/mojo/exec/ProjectProperties.java | 4 +- .../java/org/codehaus/mojo/exec/Property.java | 25 +- .../mojo/exec/SystemExitException.java | 19 +- .../codehaus/mojo/exec/SystemExitManager.java | 30 +- .../codehaus/mojo/exec/SystemProperty.java | 4 +- .../mojo/exec/URLClassLoaderBuilder.java | 400 +++----- .../org/codehaus/mojo/exec/DummyMain.java | 19 +- .../codehaus/mojo/exec/ExecJavaMojoTest.java | 227 ++--- .../org/codehaus/mojo/exec/ExecMojoTest.java | 322 +++--- .../mojo/exec/FindClassInClasspath.java | 32 +- .../mojo/exec/HelloSystemProperty.java | 10 +- .../exec/LineRedirectOutputStreamTest.java | 17 +- .../codehaus/mojo/exec/MainUncooperative.java | 51 +- .../codehaus/mojo/exec/MainWithThreads.java | 63 +- .../java/org/codehaus/mojo/exec/NoMain.java | 9 +- .../org/codehaus/mojo/exec/Slf4jMain.java | 14 +- .../org/codehaus/mojo/exec/ThrowingMain.java | 11 +- .../mojo/exec/URLClassLoaderBuilderTest.java | 46 +- .../util/interpolation/Interpolator.java | 7 +- .../interpolation/RegexBasedInterpolator.java | 36 +- .../util/interpolation/ValueSource.java | 8 +- 35 files changed, 1583 insertions(+), 2285 deletions(-) diff --git a/pom.xml b/pom.xml index 8ef151e5..2c9e02ae 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 @@ -16,9 +17,13 @@ https://www.mojohaus.org/exec-maven-plugin 2005 - - ${mavenVersion} - + + + Apache License 2 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + @@ -105,21 +110,25 @@ - - - Apache License 2 - https://www.apache.org/licenses/LICENSE-2.0.txt - repo - - + + ${mavenVersion} + scm:git:https://github.com/mojohaus/exec-maven-plugin.git scm:git:ssh://git@github.com/mojohaus/exec-maven-plugin.git - https://github.com/mojohaus/exec-maven-plugin/tree/master HEAD + https://github.com/mojohaus/exec-maven-plugin/tree/master + + 3.6.3 + 11 + 1.7.36 + 1C + 2022-07-15T02:43:45Z + + org.apache.maven @@ -176,7 +185,7 @@ plexus-component-annotations 2.1.1 true - + org.apache.commons @@ -227,14 +236,6 @@ - - 3.6.3 - 11 - 1.7.36 - 1C - 2022-07-15T02:43:45Z - - @@ -254,13 +255,6 @@ org.codehaus.mojo animal-sniffer-maven-plugin - - - - check - - - org.codehaus.mojo.signature @@ -271,6 +265,13 @@ java.lang.invoke.MethodHandle + + + + check + + + org.codehaus.plexus @@ -290,10 +291,10 @@ copy-test-deps - generate-test-resources copy + generate-test-resources @@ -412,14 +413,6 @@ org.codehaus.mojo mrm-maven-plugin - - - - start - stop - - - @@ -431,6 +424,14 @@ + + + + start + stop + + + maven-enforcer-plugin diff --git a/src/main/java/org/codehaus/mojo/exec/AbstractExecMojo.java b/src/main/java/org/codehaus/mojo/exec/AbstractExecMojo.java index e72cb564..48fe8ed8 100644 --- a/src/main/java/org/codehaus/mojo/exec/AbstractExecMojo.java +++ b/src/main/java/org/codehaus/mojo/exec/AbstractExecMojo.java @@ -40,19 +40,17 @@ * @author Philippe Jacot (PJA) * @author Jerome Lacoste */ -public abstract class AbstractExecMojo - extends AbstractMojo -{ +public abstract class AbstractExecMojo extends AbstractMojo { /** * The enclosing project. */ - @Parameter( defaultValue = "${project}", readonly = true ) + @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; - - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; - @Parameter( readonly = true, defaultValue = "${plugin.artifacts}" ) + @Parameter(readonly = true, defaultValue = "${plugin.artifacts}") private List pluginDependencies; /** @@ -74,55 +72,55 @@ public abstract class AbstractExecMojo * This folder is added to the list of those folders containing source to be compiled. Use this if your plugin * generates source code. */ - @Parameter( property = "sourceRoot" ) + @Parameter(property = "sourceRoot") private File sourceRoot; /** * This folder is added to the list of those folders containing source to be compiled for testing. Use this if your * plugin generates test source code. */ - @Parameter( property = "testSourceRoot" ) + @Parameter(property = "testSourceRoot") private File testSourceRoot; /** * Arguments separated by space for the executed program. For example: "-j 20" */ - @Parameter( property = "exec.args" ) + @Parameter(property = "exec.args") private String commandlineArgs; /** * Defines the scope of the classpath passed to the plugin. Set to compile,test,runtime or system depending on your * needs. Since 1.1.2, the default value is 'runtime' instead of 'compile'. */ - @Parameter( property = "exec.classpathScope", defaultValue = "runtime" ) + @Parameter(property = "exec.classpathScope", defaultValue = "runtime") protected String classpathScope; /** * Skip the execution. Starting with version 1.4.0 the former name skip has been changed into * exec.skip. - * + * * @since 1.0.1 */ // TODO: Remove the alias in version 1.5.0 of the plugin. - @Parameter( property = "exec.skip", defaultValue = "false", alias = "skip" ) + @Parameter(property = "exec.skip", defaultValue = "false", alias = "skip") private boolean skip; /** * Add project resource directories to classpath. This is especially useful if the exec plugin is used for a code * generator that reads its settings from the classpath. - * + * * @since 1.5.1 */ - @Parameter( property = "addResourcesToClasspath", defaultValue = "false" ) + @Parameter(property = "addResourcesToClasspath", defaultValue = "false") private boolean addResourcesToClasspath; /** * Add project output directory to classpath. This might be undesirable when the exec plugin is run before the * compile step. Default is true. - * + * * @since 1.5.1 */ - @Parameter( property = "addOutputToClasspath", defaultValue = "true" ) + @Parameter(property = "addOutputToClasspath", defaultValue = "true") private boolean addOutputToClasspath; /** @@ -132,52 +130,37 @@ public abstract class AbstractExecMojo * @param artifacts the list where to collect the scope specific artifacts * @param theClasspathFiles the list where to collect the scope specific output directories */ - protected void collectProjectArtifactsAndClasspath( List artifacts, List theClasspathFiles ) - { - if ( addResourcesToClasspath ) - { - for ( Resource r : project.getBuild().getResources() ) - { - theClasspathFiles.add( Paths.get( r.getDirectory() ) ); + protected void collectProjectArtifactsAndClasspath(List artifacts, List theClasspathFiles) { + if (addResourcesToClasspath) { + for (Resource r : project.getBuild().getResources()) { + theClasspathFiles.add(Paths.get(r.getDirectory())); } } - if ( "compile".equals( classpathScope ) ) - { - artifacts.addAll( project.getCompileArtifacts() ); - if ( addOutputToClasspath ) - { - theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); + if ("compile".equals(classpathScope)) { + artifacts.addAll(project.getCompileArtifacts()); + if (addOutputToClasspath) { + theClasspathFiles.add(Paths.get(project.getBuild().getOutputDirectory())); } - } - else if ( "test".equals( classpathScope ) ) - { - artifacts.addAll( project.getTestArtifacts() ); - if ( addOutputToClasspath ) - { - theClasspathFiles.add( Paths.get( project.getBuild().getTestOutputDirectory() ) ); - theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); + } else if ("test".equals(classpathScope)) { + artifacts.addAll(project.getTestArtifacts()); + if (addOutputToClasspath) { + theClasspathFiles.add(Paths.get(project.getBuild().getTestOutputDirectory())); + theClasspathFiles.add(Paths.get(project.getBuild().getOutputDirectory())); } - } - else if ( "runtime".equals( classpathScope ) ) - { - artifacts.addAll( project.getRuntimeArtifacts() ); - if ( addOutputToClasspath ) - { - theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); + } else if ("runtime".equals(classpathScope)) { + artifacts.addAll(project.getRuntimeArtifacts()); + if (addOutputToClasspath) { + theClasspathFiles.add(Paths.get(project.getBuild().getOutputDirectory())); } - } - else if ( "system".equals( classpathScope ) ) - { - artifacts.addAll( project.getSystemArtifacts() ); - } - else - { - throw new IllegalStateException( "Invalid classpath scope: " + classpathScope ); + } else if ("system".equals(classpathScope)) { + artifacts.addAll(project.getSystemArtifacts()); + } else { + throw new IllegalStateException("Invalid classpath scope: " + classpathScope); } - getLog().debug( "Collected project artifacts " + artifacts ); - getLog().debug( "Collected project classpath " + theClasspathFiles ); + getLog().debug("Collected project artifacts " + artifacts); + getLog().debug("Collected project classpath " + theClasspathFiles); } /** @@ -188,22 +171,14 @@ else if ( "system".equals( classpathScope ) ) * @return Array of String representing the arguments * @throws MojoExecutionException for wrong formatted arguments */ - protected String[] parseCommandlineArgs() - throws MojoExecutionException - { - if ( commandlineArgs == null ) - { + protected String[] parseCommandlineArgs() throws MojoExecutionException { + if (commandlineArgs == null) { return null; - } - else - { - try - { - return CommandLineUtils.translateCommandline( commandlineArgs ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( e.getMessage() ); + } else { + try { + return CommandLineUtils.translateCommandline(commandlineArgs); + } catch (Exception e) { + throw new MojoExecutionException(e.getMessage()); } } } @@ -211,26 +186,22 @@ protected String[] parseCommandlineArgs() /** * @return true of the mojo has command line arguments */ - protected boolean hasCommandlineArgs() - { - return ( commandlineArgs != null ); + protected boolean hasCommandlineArgs() { + return (commandlineArgs != null); } /** * Register compile and compile tests source roots if necessary */ - protected void registerSourceRoots() - { - if ( sourceRoot != null ) - { - getLog().info( "Registering compile source root " + sourceRoot ); - project.addCompileSourceRoot( sourceRoot.toString() ); + protected void registerSourceRoots() { + if (sourceRoot != null) { + getLog().info("Registering compile source root " + sourceRoot); + project.addCompileSourceRoot(sourceRoot.toString()); } - if ( testSourceRoot != null ) - { - getLog().info( "Registering compile test source root " + testSourceRoot ); - project.addTestCompileSourceRoot( testSourceRoot.toString() ); + if (testSourceRoot != null) { + getLog().info("Registering compile test source root " + testSourceRoot); + project.addTestCompileSourceRoot(testSourceRoot.toString()); } } @@ -239,46 +210,38 @@ protected void registerSourceRoots() * * @return true to skip */ - protected boolean isSkip() - { + protected boolean isSkip() { return skip; } - protected final MavenSession getSession() - { + protected final MavenSession getSession() { return session; } - protected final List getPluginDependencies() - { + protected final List getPluginDependencies() { return pluginDependencies; } /** * Examine the plugin dependencies to find the executable artifact. - * + * * @return an artifact which refers to the actual executable tool (not a POM) * @throws MojoExecutionException if no executable artifact was found */ - protected Artifact findExecutableArtifact() - throws MojoExecutionException - { + protected Artifact findExecutableArtifact() throws MojoExecutionException { // ILimitedArtifactIdentifier execToolAssembly = this.getExecutableToolAssembly(); Artifact executableTool = null; - for ( Artifact pluginDep : this.pluginDependencies ) - { - if ( this.executableDependency.matches( pluginDep ) ) - { + for (Artifact pluginDep : this.pluginDependencies) { + if (this.executableDependency.matches(pluginDep)) { executableTool = pluginDep; break; } } - if ( executableTool == null ) - { - throw new MojoExecutionException( "No dependency of the plugin matches the specified executableDependency." - + " Specified executableToolAssembly is: " + executableDependency.toString() ); + if (executableTool == null) { + throw new MojoExecutionException("No dependency of the plugin matches the specified executableDependency." + + " Specified executableToolAssembly is: " + executableDependency.toString()); } return executableTool; diff --git a/src/main/java/org/codehaus/mojo/exec/AbstractPath.java b/src/main/java/org/codehaus/mojo/exec/AbstractPath.java index 28749382..2ff7571f 100644 --- a/src/main/java/org/codehaus/mojo/exec/AbstractPath.java +++ b/src/main/java/org/codehaus/mojo/exec/AbstractPath.java @@ -21,49 +21,40 @@ import java.util.Collection; -abstract class AbstractPath -{ +abstract class AbstractPath { /** * @parameter dependency */ private Collection dependencies; - public void setDependencies( Collection deps ) - { + public void setDependencies(Collection deps) { this.dependencies = deps; } - public void setDependency( String dependency ) - { + public void setDependency(String dependency) { // Is the the correct thing to do? See MOJO-348 - if ( dependencies == null ) - { - setDependencies( new java.util.ArrayList() ); + if (dependencies == null) { + setDependencies(new java.util.ArrayList()); } - dependencies.add( dependency ); + dependencies.add(dependency); } - public Collection getDependencies() - { + public Collection getDependencies() { return dependencies; } - public String toString() - { - StringBuilder buffer = new StringBuilder( "Classpath {" ); + public String toString() { + StringBuilder buffer = new StringBuilder("Classpath {"); - if ( dependencies != null ) - { - for ( String dep : dependencies ) - { - buffer.append( " " ).append( dep ); + if (dependencies != null) { + for (String dep : dependencies) { + buffer.append(" ").append(dep); } } - buffer.append( "}" ); + buffer.append("}"); return buffer.toString(); } - } diff --git a/src/main/java/org/codehaus/mojo/exec/AbstractProperty.java b/src/main/java/org/codehaus/mojo/exec/AbstractProperty.java index 25142dd8..c3ddecb4 100644 --- a/src/main/java/org/codehaus/mojo/exec/AbstractProperty.java +++ b/src/main/java/org/codehaus/mojo/exec/AbstractProperty.java @@ -22,6 +22,4 @@ /** * Base type for system properties. */ -public class AbstractProperty -{ -} +public class AbstractProperty {} diff --git a/src/main/java/org/codehaus/mojo/exec/Classpath.java b/src/main/java/org/codehaus/mojo/exec/Classpath.java index bba223e0..16c86a53 100644 --- a/src/main/java/org/codehaus/mojo/exec/Classpath.java +++ b/src/main/java/org/codehaus/mojo/exec/Classpath.java @@ -22,6 +22,4 @@ /** * @author Jerome Lacoste (jerome@coffeebreaks.org) */ -public class Classpath extends AbstractPath -{ -} +public class Classpath extends AbstractPath {} diff --git a/src/main/java/org/codehaus/mojo/exec/EnvStreamConsumer.java b/src/main/java/org/codehaus/mojo/exec/EnvStreamConsumer.java index ab2aa62b..74bce11a 100644 --- a/src/main/java/org/codehaus/mojo/exec/EnvStreamConsumer.java +++ b/src/main/java/org/codehaus/mojo/exec/EnvStreamConsumer.java @@ -1,68 +1,54 @@ -package org.codehaus.mojo.exec; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.codehaus.plexus.util.StringUtils; -import org.codehaus.plexus.util.cli.StreamConsumer; - -public class EnvStreamConsumer - implements StreamConsumer -{ - - public static final String START_PARSING_INDICATOR = - "================================This is the beginning of env parsing================================"; - - private Map envs = new HashMap(); - - private List unparsed = new ArrayList(); - - private boolean startParsing = false; - - public void consumeLine( String line ) - { - - if ( line.startsWith( START_PARSING_INDICATOR ) ) - { - this.startParsing = true; - return; - } - - if ( this.startParsing ) - { - String[] tokens = StringUtils.split( line, "=", 2 ); - if ( tokens.length == 2 ) - { - envs.put( tokens[0], tokens[1] ); - } else { - // Don't hide an environment variable with no value e.g. APP_OVERRIDE= - String trimmedLine = line.trim(); - if ( trimmedLine.endsWith("=") ) - { - envs.put( trimmedLine.substring( 0, ( trimmedLine.length() - 1 ) ), null ); - } - else - { - unparsed.add( line ); - } - } - } - else - { - System.out.println( line ); - } - - } - - public Map getParsedEnv() - { - return this.envs; - } - - public List getUnparsedLines() - { - return this.unparsed; - } -} +package org.codehaus.mojo.exec; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.cli.StreamConsumer; + +public class EnvStreamConsumer implements StreamConsumer { + + public static final String START_PARSING_INDICATOR = + "================================This is the beginning of env parsing================================"; + + private Map envs = new HashMap(); + + private List unparsed = new ArrayList(); + + private boolean startParsing = false; + + public void consumeLine(String line) { + + if (line.startsWith(START_PARSING_INDICATOR)) { + this.startParsing = true; + return; + } + + if (this.startParsing) { + String[] tokens = StringUtils.split(line, "=", 2); + if (tokens.length == 2) { + envs.put(tokens[0], tokens[1]); + } else { + // Don't hide an environment variable with no value e.g. APP_OVERRIDE= + String trimmedLine = line.trim(); + if (trimmedLine.endsWith("=")) { + envs.put(trimmedLine.substring(0, (trimmedLine.length() - 1)), null); + } else { + unparsed.add(line); + } + } + } else { + System.out.println(line); + } + } + + public Map getParsedEnv() { + return this.envs; + } + + public List getUnparsedLines() { + return this.unparsed; + } +} diff --git a/src/main/java/org/codehaus/mojo/exec/ExecJavaMojo.java b/src/main/java/org/codehaus/mojo/exec/ExecJavaMojo.java index b96150b2..1d9aaaf0 100644 --- a/src/main/java/org/codehaus/mojo/exec/ExecJavaMojo.java +++ b/src/main/java/org/codehaus/mojo/exec/ExecJavaMojo.java @@ -42,18 +42,16 @@ /** * Executes the supplied java class in the current VM with the enclosing project's dependencies as classpath. - * + * * @author Kaare Nilsen (kaare.nilsen@gmail.com), David Smiley (dsmiley@mitre.org) * @since 1.0 */ -@Mojo( name = "java", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST ) -public class ExecJavaMojo - extends AbstractExecMojo -{ +@Mojo(name = "java", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST) +public class ExecJavaMojo extends AbstractExecMojo { // Implementation note: Constants can be included in javadocs by {@value #MY_CONST} private static final String THREAD_STOP_UNAVAILABLE = - "Thread.stop() is unavailable in this JRE version, cannot force-stop any threads"; - + "Thread.stop() is unavailable in this JRE version, cannot force-stop any threads"; + @Component private RepositorySystem repositorySystem; @@ -67,13 +65,12 @@ public class ExecJavaMojo * The main class to execute.
* With Java 9 and above you can prefix it with the modulename, e.g. com.greetings/com.greetings.Main * Without modulename the classpath will be used, with modulename a new modulelayer will be created. - * + * * @since 1.0 */ - @Parameter( required = true, property = "exec.mainClass" ) + @Parameter(required = true, property = "exec.mainClass") private String mainClass; - /** * Forces the creation of fork join common pool to avoids the threads to be owned by the isolated thread group * and prevent a proper shutdown. @@ -82,22 +79,22 @@ public class ExecJavaMojo * * @since 3.0.1 */ - @Parameter( property = "exec.preloadCommonPool", defaultValue = "0" ) + @Parameter(property = "exec.preloadCommonPool", defaultValue = "0") private int preloadCommonPool; /** * The class arguments. - * + * * @since 1.0 */ - @Parameter( property = "exec.arguments" ) + @Parameter(property = "exec.arguments") private String[] arguments; /** * A list of system properties to be passed. Note: as the execution is not forked, some system properties required * by the JVM cannot be passed here. Use MAVEN_OPTS or the exec:exec instead. See the user guide for more * information. - * + * * @since 1.0 */ @Parameter @@ -106,20 +103,20 @@ public class ExecJavaMojo /** * Indicates if mojo should be kept running after the mainclass terminates. Use full for server like apps with * daemon threads. - * + * * @deprecated since 1.1-alpha-1 * @since 1.0 */ - @Parameter( property = "exec.keepAlive", defaultValue = "false" ) + @Parameter(property = "exec.keepAlive", defaultValue = "false") @Deprecated private boolean keepAlive; /** * Indicates if the project dependencies should be used when executing the main class. - * + * * @since 1.1-beta-1 */ - @Parameter( property = "exec.includeProjectDependencies", defaultValue = "true" ) + @Parameter(property = "exec.includeProjectDependencies", defaultValue = "true") private boolean includeProjectDependencies; /** @@ -128,10 +125,10 @@ public class ExecJavaMojo * This is useful when project dependencies are not appropriate. Using only the plugin dependencies can be * particularly useful when the project is not a java project. For example a mvn project using the csharp plugins * only expects to see dotnet libraries as dependencies. - * + * * @since 1.1-beta-1 */ - @Parameter( property = "exec.includePluginsDependencies", defaultValue = "false" ) + @Parameter(property = "exec.includePluginsDependencies", defaultValue = "false") private boolean includePluginDependencies; /** @@ -143,10 +140,10 @@ public class ExecJavaMojo * are properly cleaned up to ensure they don't interfere with subsequent activity. In that case, see * {@link #daemonThreadJoinTimeout} and {@link #stopUnresponsiveDaemonThreads} for further tuning. *

- * + * * @since 1.1-beta-1 */ - @Parameter( property = "exec.cleanupDaemonThreads", defaultValue = "true" ) + @Parameter(property = "exec.cleanupDaemonThreads", defaultValue = "true") private boolean cleanupDaemonThreads; /** @@ -160,10 +157,10 @@ public class ExecJavaMojo * infinitely wait by default otherwise maven could hang. A sensible default value has been chosen, but this default * value may change in the future based on user feedback. *

- * + * * @since 1.1-beta-1 */ - @Parameter( property = "exec.daemonThreadJoinTimeout", defaultValue = "15000" ) + @Parameter(property = "exec.daemonThreadJoinTimeout", defaultValue = "15000") private long daemonThreadJoinTimeout; /** @@ -179,17 +176,17 @@ public class ExecJavaMojo * Note: In JDK 20+, the long deprecated {@link Thread#stop()} (since JDK 1.2) has been removed and will * throw an {@link UnsupportedOperationException}. This will be handled gracefully, yielding a log warning * {@value #THREAD_STOP_UNAVAILABLE} once and not trying to stop any further threads during the same execution. - * + * * @since 1.1-beta-1 */ - @Parameter( property = "exec.stopUnresponsiveDaemonThreads", defaultValue = "false" ) + @Parameter(property = "exec.stopUnresponsiveDaemonThreads", defaultValue = "false") private boolean stopUnresponsiveDaemonThreads; private Properties originalSystemProperties; /** * Additional elements to be appended to the classpath. - * + * * @since 1.3 */ @Parameter @@ -220,176 +217,155 @@ public class ExecJavaMojo * * @since 3.2.0 */ - @Parameter( property = "exec.blockSystemExit", defaultValue = "false" ) + @Parameter(property = "exec.blockSystemExit", defaultValue = "false") private boolean blockSystemExit; /** * Execute goal. - * + * * @throws MojoExecutionException execution of the main class or one of the threads it generated failed. * @throws MojoFailureException something bad happened... */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( isSkip() ) - { - getLog().info( "skipping execute as per configuration" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (isSkip()) { + getLog().info("skipping execute as per configuration"); return; } - if ( null == arguments ) - { + if (null == arguments) { arguments = new String[0]; } - if ( getLog().isDebugEnabled() ) - { - StringBuffer msg = new StringBuffer( "Invoking : " ); - msg.append( mainClass ); - msg.append( ".main(" ); - for ( int i = 0; i < arguments.length; i++ ) - { - if ( i > 0 ) - { - msg.append( ", " ); + if (getLog().isDebugEnabled()) { + StringBuffer msg = new StringBuffer("Invoking : "); + msg.append(mainClass); + msg.append(".main("); + for (int i = 0; i < arguments.length; i++) { + if (i > 0) { + msg.append(", "); } - msg.append( arguments[i] ); + msg.append(arguments[i]); } - msg.append( ")" ); - getLog().debug( msg ); + msg.append(")"); + getLog().debug(msg); } - if ( preloadCommonPool >= 0 ) - { + if (preloadCommonPool >= 0) { preloadCommonPool(); } - IsolatedThreadGroup threadGroup = new IsolatedThreadGroup( mainClass /* name */ ); - Thread bootstrapThread = new Thread( threadGroup, new Runnable() - { - // TODO: - // Adjust implementation for future JDKs after removal of SecurityManager. - // See https://openjdk.org/jeps/411 for basic information. - // See https://bugs.openjdk.org/browse/JDK-8199704 for details about how users might be able to block - // System::exit in post-removal JDKs (still undecided at the time of writing this comment). - @SuppressWarnings( "removal" ) - public void run() - { - int sepIndex = mainClass.indexOf( '/' ); - - final String bootClassName; - if ( sepIndex >= 0 ) - { - bootClassName = mainClass.substring( sepIndex + 1 ); - } - else - { - bootClassName = mainClass; - } - - SecurityManager originalSecurityManager = System.getSecurityManager(); - - try - { - Class bootClass = Thread.currentThread().getContextClassLoader().loadClass( bootClassName ); - - MethodHandles.Lookup lookup = MethodHandles.lookup(); - - MethodHandle mainHandle = - lookup.findStatic( bootClass, "main", - MethodType.methodType( void.class, String[].class ) ); - - if ( blockSystemExit ) - { - System.setSecurityManager( new SystemExitManager( originalSecurityManager ) ); + IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(mainClass /* name */); + Thread bootstrapThread = new Thread( + threadGroup, + new Runnable() { + // TODO: + // Adjust implementation for future JDKs after removal of SecurityManager. + // See https://openjdk.org/jeps/411 for basic information. + // See https://bugs.openjdk.org/browse/JDK-8199704 for details about how users might be able to + // block + // System::exit in post-removal JDKs (still undecided at the time of writing this comment). + @SuppressWarnings("removal") + public void run() { + int sepIndex = mainClass.indexOf('/'); + + final String bootClassName; + if (sepIndex >= 0) { + bootClassName = mainClass.substring(sepIndex + 1); + } else { + bootClassName = mainClass; + } + + SecurityManager originalSecurityManager = System.getSecurityManager(); + + try { + Class bootClass = Thread.currentThread() + .getContextClassLoader() + .loadClass(bootClassName); + + MethodHandles.Lookup lookup = MethodHandles.lookup(); + + MethodHandle mainHandle = lookup.findStatic( + bootClass, "main", MethodType.methodType(void.class, String[].class)); + + if (blockSystemExit) { + System.setSecurityManager(new SystemExitManager(originalSecurityManager)); + } + mainHandle.invoke(arguments); + } catch (IllegalAccessException + | NoSuchMethodException + | NoSuchMethodError e) { // just pass it on + Thread.currentThread() + .getThreadGroup() + .uncaughtException( + Thread.currentThread(), + new Exception( + "The specified mainClass doesn't contain a main method with appropriate signature.", + e)); + } catch ( + InvocationTargetException + e) { // use the cause if available to improve the plugin execution output + Throwable exceptionToReport = e.getCause() != null ? e.getCause() : e; + Thread.currentThread() + .getThreadGroup() + .uncaughtException(Thread.currentThread(), exceptionToReport); + } catch (SystemExitException systemExitException) { + getLog().info(systemExitException.getMessage()); + if (systemExitException.getExitCode() != 0) { + throw systemExitException; + } + } catch (Throwable e) { // just pass it on + Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), e); + } finally { + if (blockSystemExit) { + System.setSecurityManager(originalSecurityManager); + } + } } - mainHandle.invoke( arguments ); - } - catch ( IllegalAccessException | NoSuchMethodException | NoSuchMethodError e ) - { // just pass it on - Thread.currentThread().getThreadGroup().uncaughtException( Thread.currentThread(), - new Exception( "The specified mainClass doesn't contain a main method with appropriate signature.", - e ) ); - } - catch ( InvocationTargetException e ) - { // use the cause if available to improve the plugin execution output - Throwable exceptionToReport = e.getCause() != null ? e.getCause() : e; - Thread.currentThread().getThreadGroup().uncaughtException( Thread.currentThread(), exceptionToReport ); - } - catch ( SystemExitException systemExitException ) - { - getLog().info( systemExitException.getMessage() ); - if ( systemExitException.getExitCode() != 0 ) - { - throw systemExitException; - } - } - catch ( Throwable e ) - { // just pass it on - Thread.currentThread().getThreadGroup().uncaughtException( Thread.currentThread(), e ); - } - finally - { - if ( blockSystemExit ) - { - System.setSecurityManager( originalSecurityManager ); - } - } - } - }, mainClass + ".main()" ); + }, + mainClass + ".main()"); URLClassLoader classLoader = getClassLoader(); - bootstrapThread.setContextClassLoader( classLoader ); + bootstrapThread.setContextClassLoader(classLoader); setSystemProperties(); bootstrapThread.start(); - joinNonDaemonThreads( threadGroup ); + joinNonDaemonThreads(threadGroup); // It's plausible that spontaneously a non-daemon thread might be created as we try and shut down, // but it's too late since the termination condition (only daemon threads) has been triggered. - if ( keepAlive ) - { - getLog().warn( "Warning: keepAlive is now deprecated and obsolete. Do you need it? Please comment on MEXEC-6." ); - waitFor( 0 ); + if (keepAlive) { + getLog().warn( + "Warning: keepAlive is now deprecated and obsolete. Do you need it? Please comment on MEXEC-6."); + waitFor(0); } - if ( cleanupDaemonThreads ) - { + if (cleanupDaemonThreads) { - terminateThreads( threadGroup ); + terminateThreads(threadGroup); - try - { + try { threadGroup.destroy(); - } - catch ( IllegalThreadStateException e ) - { - getLog().warn( "Couldn't destroy threadgroup " + threadGroup, e ); + } catch (IllegalThreadStateException e) { + getLog().warn("Couldn't destroy threadgroup " + threadGroup, e); } } - if ( classLoader != null ) - { - try - { + if (classLoader != null) { + try { classLoader.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { getLog().error(e.getMessage(), e); } } - if ( originalSystemProperties != null ) - { - System.setProperties( originalSystemProperties ); + if (originalSystemProperties != null) { + System.setProperties(originalSystemProperties); } - synchronized ( threadGroup ) - { - if ( threadGroup.uncaughtException != null ) - { - throw new MojoExecutionException( "An exception occurred while executing the Java class. " - + threadGroup.uncaughtException.getMessage(), threadGroup.uncaughtException ); + synchronized (threadGroup) { + if (threadGroup.uncaughtException != null) { + throw new MojoExecutionException( + "An exception occurred while executing the Java class. " + + threadGroup.uncaughtException.getMessage(), + threadGroup.uncaughtException); } } @@ -399,35 +375,23 @@ public void run() /** * To avoid the exec:java to consider common pool threads leaked, let's pre-create them. */ - private void preloadCommonPool() - { - try - { + private void preloadCommonPool() { + try { // ensure common pool exists in the jvm final ExecutorService es = ForkJoinPool.commonPool(); - final int max = preloadCommonPool > 0 - ? preloadCommonPool : - ForkJoinPool.getCommonPoolParallelism(); - final CountDownLatch preLoad = new CountDownLatch( 1 ); - for ( int i = 0; - i < max; - i++ ) - { + final int max = preloadCommonPool > 0 ? preloadCommonPool : ForkJoinPool.getCommonPoolParallelism(); + final CountDownLatch preLoad = new CountDownLatch(1); + for (int i = 0; i < max; i++) { es.submit(() -> { - try - { + try { preLoad.await(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } preLoad.countDown(); - } - catch (final Exception e) - { + } catch (final Exception e) { getLog().debug(e.getMessage() + ", skipping commonpool earger init"); } } @@ -435,156 +399,122 @@ private void preloadCommonPool() /** * a ThreadGroup to isolate execution and collect exceptions. */ - class IsolatedThreadGroup - extends ThreadGroup - { + class IsolatedThreadGroup extends ThreadGroup { private Throwable uncaughtException; // synchronize access to this - public IsolatedThreadGroup( String name ) - { - super( name ); + public IsolatedThreadGroup(String name) { + super(name); } - public void uncaughtException( Thread thread, Throwable throwable ) - { - if ( throwable instanceof ThreadDeath ) - { + public void uncaughtException(Thread thread, Throwable throwable) { + if (throwable instanceof ThreadDeath) { return; // harmless } - synchronized ( this ) - { - if ( uncaughtException == null ) // only remember the first one + synchronized (this) { + if (uncaughtException == null) // only remember the first one { uncaughtException = throwable; // will be reported eventually } } - getLog().warn( throwable ); + getLog().warn(throwable); } } - private void joinNonDaemonThreads( ThreadGroup threadGroup ) - { + private void joinNonDaemonThreads(ThreadGroup threadGroup) { boolean foundNonDaemon; - do - { + do { foundNonDaemon = false; - Collection threads = getActiveThreads( threadGroup ); - for ( Thread thread : threads ) - { - if ( thread.isDaemon() ) - { + Collection threads = getActiveThreads(threadGroup); + for (Thread thread : threads) { + if (thread.isDaemon()) { continue; } foundNonDaemon = true; // try again; maybe more threads were created while we were busy - joinThread( thread, 0 ); + joinThread(thread, 0); } - } - while ( foundNonDaemon ); + } while (foundNonDaemon); } - private void joinThread( Thread thread, long timeoutMsecs ) - { - try - { - getLog().debug( "joining on thread " + thread ); - thread.join( timeoutMsecs ); - } - catch ( InterruptedException e ) - { + private void joinThread(Thread thread, long timeoutMsecs) { + try { + getLog().debug("joining on thread " + thread); + thread.join(timeoutMsecs); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); // good practice if don't throw - getLog().warn( "interrupted while joining against thread " + thread, e ); // not expected! + getLog().warn("interrupted while joining against thread " + thread, e); // not expected! } - if ( thread.isAlive() ) // generally abnormal + if (thread.isAlive()) // generally abnormal { - getLog().warn( "thread " + thread + " was interrupted but is still alive after waiting at least " - + timeoutMsecs + "msecs" ); + getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least " + + timeoutMsecs + "msecs"); } } - private void terminateThreads( ThreadGroup threadGroup ) - { + private void terminateThreads(ThreadGroup threadGroup) { long startTime = System.currentTimeMillis(); Set uncooperativeThreads = new HashSet(); // these were not responsive to interruption - for ( Collection threads = getActiveThreads( threadGroup ); !threads.isEmpty(); threads = - getActiveThreads( threadGroup ), threads.removeAll( uncooperativeThreads ) ) - { + for (Collection threads = getActiveThreads(threadGroup); + !threads.isEmpty(); + threads = getActiveThreads(threadGroup), threads.removeAll(uncooperativeThreads)) { // Interrupt all threads we know about as of this instant (harmless if spuriously went dead (! isAlive()) // or if something else interrupted it ( isInterrupted() ). - for ( Thread thread : threads ) - { - getLog().debug( "interrupting thread " + thread ); + for (Thread thread : threads) { + getLog().debug("interrupting thread " + thread); thread.interrupt(); } // Now join with a timeout and call stop() (assuming flags are set right) boolean threadStopIsAvailable = true; - for ( Thread thread : threads ) - { - if ( !thread.isAlive() ) - { + for (Thread thread : threads) { + if (!thread.isAlive()) { continue; // and, presumably it won't show up in getActiveThreads() next iteration } - if ( daemonThreadJoinTimeout <= 0 ) - { - joinThread( thread, 0 ); // waits until not alive; no timeout + if (daemonThreadJoinTimeout <= 0) { + joinThread(thread, 0); // waits until not alive; no timeout continue; } - long timeout = daemonThreadJoinTimeout - ( System.currentTimeMillis() - startTime ); - if ( timeout > 0 ) - { - joinThread( thread, timeout ); + long timeout = daemonThreadJoinTimeout - (System.currentTimeMillis() - startTime); + if (timeout > 0) { + joinThread(thread, timeout); } - if ( !thread.isAlive() ) - { + if (!thread.isAlive()) { continue; } - uncooperativeThreads.add( thread ); // ensure we don't process again - if ( stopUnresponsiveDaemonThreads && threadStopIsAvailable ) - { - getLog().warn( "thread " + thread + " will be Thread.stop()'ed" ); - try - { + uncooperativeThreads.add(thread); // ensure we don't process again + if (stopUnresponsiveDaemonThreads && threadStopIsAvailable) { + getLog().warn("thread " + thread + " will be Thread.stop()'ed"); + try { thread.stop(); - } - catch ( UnsupportedOperationException unsupportedOperationException ) - { + } catch (UnsupportedOperationException unsupportedOperationException) { threadStopIsAvailable = false; - getLog().warn( THREAD_STOP_UNAVAILABLE ); + getLog().warn(THREAD_STOP_UNAVAILABLE); } - } - else - { - getLog().warn( "thread " + thread + " will linger despite being asked to die via interruption" ); + } else { + getLog().warn("thread " + thread + " will linger despite being asked to die via interruption"); } } } - if ( !uncooperativeThreads.isEmpty() ) - { - getLog().warn( "NOTE: " + uncooperativeThreads.size() + " thread(s) did not finish despite being asked to" - + " via interruption. This is not a problem with exec:java, it is a problem with the running code." - + " Although not serious, it should be remedied." ); - } - else - { + if (!uncooperativeThreads.isEmpty()) { + getLog().warn("NOTE: " + uncooperativeThreads.size() + " thread(s) did not finish despite being asked to" + + " via interruption. This is not a problem with exec:java, it is a problem with the running code." + + " Although not serious, it should be remedied."); + } else { int activeCount = threadGroup.activeCount(); - if ( activeCount != 0 ) - { + if (activeCount != 0) { // TODO this may be nothing; continue on anyway; perhaps don't even log in future Thread[] threadsArray = new Thread[1]; - threadGroup.enumerate( threadsArray ); - getLog().debug( "strange; " + activeCount + " thread(s) still active in the group " + threadGroup - + " such as " + threadsArray[0] ); + threadGroup.enumerate(threadsArray); + getLog().debug("strange; " + activeCount + " thread(s) still active in the group " + threadGroup + + " such as " + threadsArray[0]); } } } - private Collection getActiveThreads( ThreadGroup threadGroup ) - { + private Collection getActiveThreads(ThreadGroup threadGroup) { Thread[] threads = new Thread[threadGroup.activeCount()]; - int numThreads = threadGroup.enumerate( threads ); - Collection result = new ArrayList( numThreads ); - for ( int i = 0; i < threads.length && threads[i] != null; i++ ) - { - result.add( threads[i] ); + int numThreads = threadGroup.enumerate(threads); + Collection result = new ArrayList(numThreads); + for (int i = 0; i < threads.length && threads[i] != null; i++) { + result.add(threads[i]); } return result; // note: result should be modifiable } @@ -592,76 +522,61 @@ private Collection getActiveThreads( ThreadGroup threadGroup ) /** * Pass any given system properties to the java system properties. */ - private void setSystemProperties() - { - if ( systemProperties == null ) - { + private void setSystemProperties() { + if (systemProperties == null) { return; } // copy otherwise the restore phase does nothing originalSystemProperties = new Properties(); originalSystemProperties.putAll(System.getProperties()); - if ( Stream.of( systemProperties ).anyMatch( it -> it instanceof ProjectProperties ) ) - { - System.getProperties().putAll( project.getProperties() ); + if (Stream.of(systemProperties).anyMatch(it -> it instanceof ProjectProperties)) { + System.getProperties().putAll(project.getProperties()); } - for ( AbstractProperty systemProperty : systemProperties ) - { - if ( ! ( systemProperty instanceof Property ) ) - { + for (AbstractProperty systemProperty : systemProperties) { + if (!(systemProperty instanceof Property)) { continue; } Property prop = (Property) systemProperty; String value = prop.getValue(); - System.setProperty( prop.getKey(), value == null ? "" : value ); + System.setProperty(prop.getKey(), value == null ? "" : value); } } /** * Set up a classloader for the execution of the main class. - * + * * @return the classloader * @throws MojoExecutionException if a problem happens */ - private URLClassLoader getClassLoader() - throws MojoExecutionException - { + private URLClassLoader getClassLoader() throws MojoExecutionException { List classpathURLs = new ArrayList<>(); - this.addRelevantPluginDependenciesToClasspath( classpathURLs ); - this.addRelevantProjectDependenciesToClasspath( classpathURLs ); - this.addAdditionalClasspathElements( classpathURLs ); - - try - { + this.addRelevantPluginDependenciesToClasspath(classpathURLs); + this.addRelevantProjectDependenciesToClasspath(classpathURLs); + this.addAdditionalClasspathElements(classpathURLs); + + try { return URLClassLoaderBuilder.builder() - .setLogger( getLog() ) - .setPaths( classpathURLs ) - .setExclusions( classpathFilenameExclusions ) + .setLogger(getLog()) + .setPaths(classpathURLs) + .setExclusions(classpathFilenameExclusions) .build(); + } catch (NullPointerException | IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } - catch ( NullPointerException | IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); - } - } - private void addAdditionalClasspathElements( List path ) - { - if ( additionalClasspathElements != null ) - { - for ( String classPathElement : additionalClasspathElements ) - { - Path file = Paths.get( classPathElement ); - if ( !file.isAbsolute() ) - { - file = project.getBasedir().toPath().resolve( file ); + private void addAdditionalClasspathElements(List path) { + if (additionalClasspathElements != null) { + for (String classPathElement : additionalClasspathElements) { + Path file = Paths.get(classPathElement); + if (!file.isAbsolute()) { + file = project.getBasedir().toPath().resolve(file); } - getLog().debug( "Adding additional classpath element: " + file + " to classpath" ); - path.add( file ); + getLog().debug("Adding additional classpath element: " + file + " to classpath"); + path.add(file); } } } @@ -669,151 +584,121 @@ private void addAdditionalClasspathElements( List path ) /** * Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and * ExecutableDependency into consideration. - * + * * @param path classpath of {@link java.net.URL} objects * @throws MojoExecutionException if a problem happens */ - private void addRelevantPluginDependenciesToClasspath( List path ) - throws MojoExecutionException - { - if ( hasCommandlineArgs() ) - { + private void addRelevantPluginDependenciesToClasspath(List path) throws MojoExecutionException { + if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } - for ( Artifact classPathElement : this.determineRelevantPluginDependencies() ) - { - getLog().debug( "Adding plugin dependency artifact: " + classPathElement.getArtifactId() - + " to classpath" ); - path.add( classPathElement.getFile().toPath() ); + for (Artifact classPathElement : this.determineRelevantPluginDependencies()) { + getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); + path.add(classPathElement.getFile().toPath()); } } /** * Add any relevant project dependencies to the classpath. Takes includeProjectDependencies into consideration. - * + * * @param path classpath of {@link java.net.URL} objects */ - private void addRelevantProjectDependenciesToClasspath( List path ) - { - if ( this.includeProjectDependencies ) - { - getLog().debug( "Project Dependencies will be included." ); + private void addRelevantProjectDependenciesToClasspath(List path) { + if (this.includeProjectDependencies) { + getLog().debug("Project Dependencies will be included."); List artifacts = new ArrayList<>(); List theClasspathFiles = new ArrayList<>(); - collectProjectArtifactsAndClasspath( artifacts, theClasspathFiles ); + collectProjectArtifactsAndClasspath(artifacts, theClasspathFiles); - for ( Path classpathFile : theClasspathFiles ) - { - getLog().debug( "Adding to classpath : " + classpathFile ); - path.add( classpathFile ); + for (Path classpathFile : theClasspathFiles) { + getLog().debug("Adding to classpath : " + classpathFile); + path.add(classpathFile); } - for ( Artifact classPathElement : artifacts ) - { - getLog().debug( "Adding project dependency artifact: " + classPathElement.getArtifactId() - + " to classpath" ); - path.add( classPathElement.getFile().toPath() ); + for (Artifact classPathElement : artifacts) { + getLog().debug("Adding project dependency artifact: " + classPathElement.getArtifactId() + + " to classpath"); + path.add(classPathElement.getFile().toPath()); } + } else { + getLog().debug("Project Dependencies will be excluded."); } - else - { - getLog().debug( "Project Dependencies will be excluded." ); - } - } /** * Determine all plugin dependencies relevant to the executable. Takes includePlugins, and the executableDependency * into consideration. - * + * * @return a set of Artifact objects. (Empty set is returned if there are no relevant plugin dependencies.) * @throws MojoExecutionException if a problem happens resolving the plufin dependencies */ - private Set determineRelevantPluginDependencies() - throws MojoExecutionException - { + private Set determineRelevantPluginDependencies() throws MojoExecutionException { Set relevantDependencies; - if ( this.includePluginDependencies ) - { - if ( this.executableDependency == null ) - { - getLog().debug( "All Plugin Dependencies will be included." ); - relevantDependencies = new HashSet<>( this.getPluginDependencies() ); - } - else - { - getLog().debug( "Selected plugin Dependencies will be included." ); + if (this.includePluginDependencies) { + if (this.executableDependency == null) { + getLog().debug("All Plugin Dependencies will be included."); + relevantDependencies = new HashSet<>(this.getPluginDependencies()); + } else { + getLog().debug("Selected plugin Dependencies will be included."); Artifact executableArtifact = this.findExecutableArtifact(); - relevantDependencies = this.resolveExecutableDependencies( executableArtifact ); + relevantDependencies = this.resolveExecutableDependencies(executableArtifact); } - } - else - { + } else { relevantDependencies = Collections.emptySet(); - getLog().debug( "Plugin Dependencies will be excluded." ); + getLog().debug("Plugin Dependencies will be excluded."); } return relevantDependencies; } /** * Resolve the executable dependencies for the specified project - * + * * @param executableArtifact the executable plugin dependency * @return a set of Artifacts * @throws MojoExecutionException if a failure happens */ - private Set resolveExecutableDependencies( Artifact executableArtifact ) - throws MojoExecutionException - { - try - { + private Set resolveExecutableDependencies(Artifact executableArtifact) throws MojoExecutionException { + try { CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRoot( - new Dependency( RepositoryUtils.toArtifact( executableArtifact ), classpathScope ) ); - collectRequest.setRepositories( project.getRemotePluginRepositories() ); + collectRequest.setRoot(new Dependency(RepositoryUtils.toArtifact(executableArtifact), classpathScope)); + collectRequest.setRepositories(project.getRemotePluginRepositories()); - DependencyFilter classpathFilter = DependencyFilterUtils.classpathFilter( classpathScope ); + DependencyFilter classpathFilter = DependencyFilterUtils.classpathFilter(classpathScope); - DependencyRequest dependencyRequest = new DependencyRequest( collectRequest, classpathFilter ); + DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFilter); DependencyResult dependencyResult = - repositorySystem.resolveDependencies( getSession().getRepositorySession(), dependencyRequest ); + repositorySystem.resolveDependencies(getSession().getRepositorySession(), dependencyRequest); return dependencyResult.getArtifactResults().stream() - .map( ArtifactResult::getArtifact ) - .map( RepositoryUtils::toArtifact ) - .collect( Collectors.toSet() ); - } - catch ( DependencyResolutionException ex ) - { - throw new MojoExecutionException( "Encountered problems resolving dependencies of the executable " - + "in preparation for its execution.", ex ); + .map(ArtifactResult::getArtifact) + .map(RepositoryUtils::toArtifact) + .collect(Collectors.toSet()); + } catch (DependencyResolutionException ex) { + throw new MojoExecutionException( + "Encountered problems resolving dependencies of the executable " + + "in preparation for its execution.", + ex); } } /** * Stop program execution for nn millis. - * + * * @param millis the number of millis-seconds to wait for, 0 stops program forever. */ - private void waitFor( long millis ) - { + private void waitFor(long millis) { Object lock = new Object(); - synchronized ( lock ) - { - try - { - lock.wait( millis ); - } - catch ( InterruptedException e ) - { + synchronized (lock) { + try { + lock.wait(millis); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); // good practice if don't throw - getLog().warn( "Spuriously interrupted while waiting for " + millis + "ms", e ); + getLog().warn("Spuriously interrupted while waiting for " + millis + "ms", e); } } } - } diff --git a/src/main/java/org/codehaus/mojo/exec/ExecMojo.java b/src/main/java/org/codehaus/mojo/exec/ExecMojo.java index d24d8dfd..0b5765aa 100644 --- a/src/main/java/org/codehaus/mojo/exec/ExecMojo.java +++ b/src/main/java/org/codehaus/mojo/exec/ExecMojo.java @@ -80,15 +80,13 @@ * @version $Id$ * @since 1.0 */ -@Mojo( name = "exec", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST ) -public class ExecMojo - extends AbstractExecMojo -{ +@Mojo(name = "exec", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST) +public class ExecMojo extends AbstractExecMojo { /** * Trying to recognize whether the given {@link #executable} might be a {@code java} binary. */ - private static final Pattern ENDS_WITH_JAVA = Pattern.compile( "^.*java(\\.exe|\\.bin)?$", Pattern.CASE_INSENSITIVE ); + private static final Pattern ENDS_WITH_JAVA = Pattern.compile("^.*java(\\.exe|\\.bin)?$", Pattern.CASE_INSENSITIVE); /** *

@@ -108,7 +106,7 @@ public class ExecMojo * * @since 1.0 */ - @Parameter( property = "exec.executable" ) + @Parameter(property = "exec.executable") private String executable; /** @@ -123,7 +121,7 @@ public class ExecMojo * * @since 3.0.0 */ - @Parameter( property = "exec.timeout", defaultValue = "0" ) + @Parameter(property = "exec.timeout", defaultValue = "0") private int timeout; /** @@ -131,7 +129,7 @@ public class ExecMojo * The toolchain. If omitted, "jdk" is assumed. *

*/ - @Parameter( property = "exec.toolchain", defaultValue = "jdk" ) + @Parameter(property = "exec.toolchain", defaultValue = "jdk") private String toolchain; /** @@ -139,7 +137,7 @@ public class ExecMojo * * @since 1.0 */ - @Parameter( property = "exec.workingdir" ) + @Parameter(property = "exec.workingdir") private File workingDirectory; /** @@ -152,7 +150,7 @@ public class ExecMojo * @see java.lang.System#err * @see java.lang.System#in */ - @Parameter( property = "exec.outputFile" ) + @Parameter(property = "exec.outputFile") private File outputFile; /** @@ -162,7 +160,7 @@ public class ExecMojo * @since 3.0.1 * @see ProcessBuilder#inheritIO() */ - @Parameter( property = "exec.inheritIo" ) + @Parameter(property = "exec.inheritIo") private boolean inheritIo; /** @@ -228,7 +226,7 @@ public class ExecMojo * @see java.lang.System#err * @see java.lang.System#in */ - @Parameter( property = "exec.useMavenLogger", defaultValue = "false" ) + @Parameter(property = "exec.useMavenLogger", defaultValue = "false") private boolean useMavenLogger; /** @@ -238,7 +236,7 @@ public class ExecMojo * * @since 3.0.0 */ - @Parameter( property = "exec.quietLogs", defaultValue = "false" ) + @Parameter(property = "exec.quietLogs", defaultValue = "false") private boolean quietLogs; /** @@ -255,13 +253,13 @@ public class ExecMojo /** * @since 1.0 */ - @Parameter( readonly = true, required = true, defaultValue = "${basedir}" ) + @Parameter(readonly = true, required = true, defaultValue = "${basedir}") private File basedir; /** * @since 3.0.0 */ - @Parameter( readonly = true, required = true, defaultValue = "${project.build.directory}" ) + @Parameter(readonly = true, required = true, defaultValue = "${project.build.directory}") private File buildDirectory; /** @@ -290,7 +288,7 @@ public class ExecMojo /** * The current build session instance. This is used for toolchain manager API calls. */ - @Parameter( defaultValue = "${session}", readonly = true ) + @Parameter(defaultValue = "${session}", readonly = true) private MavenSession session; /** @@ -308,7 +306,7 @@ public class ExecMojo * * @since 1.1.2 */ - @Parameter( property = "exec.longClasspath", defaultValue = "false" ) + @Parameter(property = "exec.longClasspath", defaultValue = "false") private boolean longClasspath; /** @@ -317,7 +315,7 @@ public class ExecMojo * * @since 1.1.2 */ - @Parameter( property = "exec.longModulepath", defaultValue = "true" ) + @Parameter(property = "exec.longModulepath", defaultValue = "true") private boolean longModulepath; /** @@ -329,13 +327,13 @@ public class ExecMojo * * @since 3.1.1 */ - @Parameter (property = "exec.forceJava", defaultValue = "false" ) + @Parameter(property = "exec.forceJava", defaultValue = "false") private boolean forceJava; /** * If set to true the child process executes asynchronously and build execution continues in parallel. */ - @Parameter( property = "exec.async", defaultValue = "false" ) + @Parameter(property = "exec.async", defaultValue = "false") private boolean async; /** @@ -343,7 +341,7 @@ public class ExecMojo * child process continues execution after JVM shutdown. Applies only to asynchronous processes; ignored for * synchronous processes. */ - @Parameter( property = "exec.asyncDestroyOnShutdown", defaultValue = "true" ) + @Parameter(property = "exec.asyncDestroyOnShutdown", defaultValue = "true") private boolean asyncDestroyOnShutdown = true; public static final String CLASSPATH_TOKEN = "%classpath"; @@ -355,130 +353,103 @@ public class ExecMojo * * @throws MojoExecutionException if a failure happens */ - public void execute() - throws MojoExecutionException - { - if ( executable == null ) - { - if (executableDependency == null) - { - throw new MojoExecutionException( "The parameter 'executable' is missing or invalid" ); + public void execute() throws MojoExecutionException { + if (executable == null) { + if (executableDependency == null) { + throw new MojoExecutionException("The parameter 'executable' is missing or invalid"); } executable = findExecutableArtifact().getFile().getAbsolutePath(); - getLog().debug( "using executable dependency " + executable); + getLog().debug("using executable dependency " + executable); } - if ( isSkip() ) - { - getLog().info( "skipping execute as per configuration" ); + if (isSkip()) { + getLog().info("skipping execute as per configuration"); return; } - if ( basedir == null ) - { - throw new IllegalStateException( "basedir is null. Should not be possible." ); + if (basedir == null) { + throw new IllegalStateException("basedir is null. Should not be possible."); } - try - { + try { handleWorkingDirectory(); - String argsProp = getSystemProperty( "exec.args" ); + String argsProp = getSystemProperty("exec.args"); List commandArguments = new ArrayList(); - if ( hasCommandlineArgs() ) - { - handleCommandLineArgs( commandArguments ); - } - else if ( !StringUtils.isEmpty( argsProp ) ) - { - handleSystemPropertyArguments( argsProp, commandArguments ); - } - else - { - if ( arguments != null ) - { - handleArguments( commandArguments ); + if (hasCommandlineArgs()) { + handleCommandLineArgs(commandArguments); + } else if (!StringUtils.isEmpty(argsProp)) { + handleSystemPropertyArguments(argsProp, commandArguments); + } else { + if (arguments != null) { + handleArguments(commandArguments); } } Map enviro = handleSystemEnvVariables(); - CommandLine commandLine = getExecutablePath( enviro, workingDirectory ); + CommandLine commandLine = getExecutablePath(enviro, workingDirectory); - String[] args = commandArguments.toArray( new String[commandArguments.size()] ); + String[] args = commandArguments.toArray(new String[commandArguments.size()]); - commandLine.addArguments( args, false ); + commandLine.addArguments(args, false); - Executor exec = new ExtendedExecutor( inheritIo ); - if ( this.timeout > 0 ) - { - exec.setWatchdog( new ExecuteWatchdog( this.timeout ) ); + Executor exec = new ExtendedExecutor(inheritIo); + if (this.timeout > 0) { + exec.setWatchdog(new ExecuteWatchdog(this.timeout)); } - exec.setWorkingDirectory( workingDirectory ); - fillSuccessCodes( exec ); + exec.setWorkingDirectory(workingDirectory); + fillSuccessCodes(exec); - if ( OS.isFamilyOpenVms() && inheritIo ) - { - getLog().warn("The inheritIo flag is not supported on OpenVMS, execution will proceed without stream inheritance."); + if (OS.isFamilyOpenVms() && inheritIo) { + getLog().warn( + "The inheritIo flag is not supported on OpenVMS, execution will proceed without stream inheritance."); } - getLog().debug( "Executing command line: " + commandLine ); + getLog().debug("Executing command line: " + commandLine); - try - { + try { int resultCode; - if ( outputFile != null ) - { - if ( !outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs() ) - { - getLog().warn( "Could not create non existing parent directories for log file: " + outputFile ); + if (outputFile != null) { + if (!outputFile.getParentFile().exists() + && !outputFile.getParentFile().mkdirs()) { + getLog().warn("Could not create non existing parent directories for log file: " + outputFile); } FileOutputStream outputStream = null; - try - { - outputStream = new FileOutputStream( outputFile ); + try { + outputStream = new FileOutputStream(outputFile); - resultCode = executeCommandLine( exec, commandLine, enviro, outputStream ); + resultCode = executeCommandLine(exec, commandLine, enviro, outputStream); + } finally { + IOUtil.close(outputStream); } - finally - { - IOUtil.close( outputStream ); - } - } - else if (useMavenLogger) - { + } else if (useMavenLogger) { getLog().debug("Will redirect program output to Maven logger"); // If running parallel, append the projects original (i.e. current) thread name to the program // output as a log prefix, to enable easy tracing of program output when intermixed with other // Maven log output. NOTE: The accept(..) methods are running in PumpStreamHandler thread, // which is why we capture the thread name prefix here. - final String logPrefix = session.isParallel() ? "[" + Thread.currentThread().getName() + "] " : ""; - Consumer mavenOutRedirect = new Consumer() - { + final String logPrefix = + session.isParallel() ? "[" + Thread.currentThread().getName() + "] " : ""; + Consumer mavenOutRedirect = new Consumer() { @Override - public void accept(String logMessage) - { - if (quietLogs) - { + public void accept(String logMessage) { + if (quietLogs) { getLog().debug(logPrefix + logMessage); - } - else - { + } else { getLog().info(logPrefix + logMessage); } } }; - Consumer mavenErrRedirect = new Consumer() - { + Consumer mavenErrRedirect = new Consumer() { @Override - public void accept(String logMessage) - { + public void accept(String logMessage) { getLog().error(logPrefix + logMessage); } }; @@ -487,80 +458,60 @@ public void accept(String logMessage) OutputStream err = new LineRedirectOutputStream(mavenErrRedirect)) { resultCode = executeCommandLine(exec, commandLine, enviro, out, err); } - } - else - { - resultCode = executeCommandLine( exec, commandLine, enviro, System.out, System.err ); + } else { + resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err); } - if ( isResultCodeAFailure( resultCode ) ) - { + if (isResultCodeAFailure(resultCode)) { String message = "Result of " + commandLine.toString() + " execution is: '" + resultCode + "'."; - getLog().error( message ); - throw new MojoExecutionException( message ); + getLog().error(message); + throw new MojoExecutionException(message); } - } - catch ( ExecuteException e ) - { - if ( exec.getWatchdog() != null && exec.getWatchdog().killedProcess() ) - { + } catch (ExecuteException e) { + if (exec.getWatchdog() != null && exec.getWatchdog().killedProcess()) { final String message = "Timeout. Process runs longer than " + this.timeout + " ms."; - getLog().error( message ); - throw new MojoExecutionException( message, e ); - } - else - { - getLog().error( "Command execution failed.", e ); - throw new MojoExecutionException( "Command execution failed.", e ); + getLog().error(message); + throw new MojoExecutionException(message, e); + } else { + getLog().error("Command execution failed.", e); + throw new MojoExecutionException("Command execution failed.", e); } - } - catch ( IOException e ) - { - getLog().error( "Command execution failed.", e ); - throw new MojoExecutionException( "Command execution failed.", e ); + } catch (IOException e) { + getLog().error("Command execution failed.", e); + throw new MojoExecutionException("Command execution failed.", e); } registerSourceRoots(); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "I/O Error", e ); + } catch (IOException e) { + throw new MojoExecutionException("I/O Error", e); } } - private Map handleSystemEnvVariables() - throws MojoExecutionException - { + private Map handleSystemEnvVariables() throws MojoExecutionException { Map enviro = new HashMap(); Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); - for ( Map.Entry entry : systemEnvVars.entrySet() ) - { - enviro.put( (String) entry.getKey(), (String) entry.getValue() ); + for (Map.Entry entry : systemEnvVars.entrySet()) { + enviro.put((String) entry.getKey(), (String) entry.getValue()); } - if ( environmentVariables != null ) - { - enviro.putAll( environmentVariables ); + if (environmentVariables != null) { + enviro.putAll(environmentVariables); } - if ( this.environmentScript != null ) - { - getLog().info( "Pick up external environment script: " + this.environmentScript ); - Map envVarsFromScript = this.createEnvs( this.environmentScript ); - if ( envVarsFromScript != null ) - { - enviro.putAll( envVarsFromScript ); + if (this.environmentScript != null) { + getLog().info("Pick up external environment script: " + this.environmentScript); + Map envVarsFromScript = this.createEnvs(this.environmentScript); + if (envVarsFromScript != null) { + enviro.putAll(envVarsFromScript); } } - if ( this.getLog().isDebugEnabled() ) - { + if (this.getLog().isDebugEnabled()) { Set keys = new TreeSet(); - keys.addAll( enviro.keySet() ); - for ( String key : keys ) - { - this.getLog().debug( "env: " + key + "=" + enviro.get( key ) ); + keys.addAll(enviro.keySet()); + for (String key : keys) { + this.getLog().debug("env: " + key + "=" + enviro.get(key)); } } @@ -574,116 +525,89 @@ private Map handleSystemEnvVariables() * * @throws MojoExecutionException */ - private void handleWorkingDirectory() - throws MojoExecutionException - { - if ( workingDirectory == null ) - { + private void handleWorkingDirectory() throws MojoExecutionException { + if (workingDirectory == null) { workingDirectory = basedir; } - if ( !workingDirectory.exists() ) - { - getLog().debug( "Making working directory '" + workingDirectory.getAbsolutePath() + "'." ); - if ( !workingDirectory.mkdirs() ) - { - throw new MojoExecutionException( "Could not make working directory: '" - + workingDirectory.getAbsolutePath() + "'" ); + if (!workingDirectory.exists()) { + getLog().debug("Making working directory '" + workingDirectory.getAbsolutePath() + "'."); + if (!workingDirectory.mkdirs()) { + throw new MojoExecutionException( + "Could not make working directory: '" + workingDirectory.getAbsolutePath() + "'"); } } } - private void handleSystemPropertyArguments( String argsProp, List commandArguments ) - throws MojoExecutionException - { - getLog().debug( "got arguments from system properties: " + argsProp ); + private void handleSystemPropertyArguments(String argsProp, List commandArguments) + throws MojoExecutionException { + getLog().debug("got arguments from system properties: " + argsProp); - try - { - String[] args = CommandLineUtils.translateCommandline( argsProp ); - commandArguments.addAll( Arrays.asList( args ) ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Couldn't parse systemproperty 'exec.args'" ); + try { + String[] args = CommandLineUtils.translateCommandline(argsProp); + commandArguments.addAll(Arrays.asList(args)); + } catch (Exception e) { + throw new MojoExecutionException("Couldn't parse systemproperty 'exec.args'"); } } - private void handleCommandLineArgs( List commandArguments ) - throws MojoExecutionException, IOException - { + private void handleCommandLineArgs(List commandArguments) throws MojoExecutionException, IOException { String[] args = parseCommandlineArgs(); - for ( int i = 0; i < args.length; i++ ) - { - if ( isLongClassPathArgument( args[i] ) ) - { + for (int i = 0; i < args.length; i++) { + if (isLongClassPathArgument(args[i])) { // it is assumed that starting from -cp or -classpath the arguments // are: -classpath/-cp %classpath mainClass // the arguments are replaced with: -jar $TMP/maven-exec.jar // NOTE: the jar will contain the classpath and the main class - commandArguments.add( "-jar" ); - File tmpFile = createJar( computePath( null ), args[i + 2] ); - commandArguments.add( tmpFile.getAbsolutePath() ); + commandArguments.add("-jar"); + File tmpFile = createJar(computePath(null), args[i + 2]); + commandArguments.add(tmpFile.getAbsolutePath()); i += 2; - } - else if ( args[i].contains( CLASSPATH_TOKEN ) ) - { - commandArguments.add( args[i].replace( CLASSPATH_TOKEN, computeClasspathString( null ) ) ); - } - else - { - commandArguments.add( args[i] ); + } else if (args[i].contains(CLASSPATH_TOKEN)) { + commandArguments.add(args[i].replace(CLASSPATH_TOKEN, computeClasspathString(null))); + } else { + commandArguments.add(args[i]); } } } - private void handleArguments( List commandArguments ) - throws MojoExecutionException, IOException - { + private void handleArguments(List commandArguments) throws MojoExecutionException, IOException { String specialArg = null; - for ( int i = 0; i < arguments.size(); i++ ) - { - Object argument = arguments.get( i ); + for (int i = 0; i < arguments.size(); i++) { + Object argument = arguments.get(i); - if ( specialArg != null ) - { - if ( isLongClassPathArgument( specialArg ) && argument instanceof Classpath ) - { + if (specialArg != null) { + if (isLongClassPathArgument(specialArg) && argument instanceof Classpath) { // it is assumed that starting from -cp or -classpath the arguments // are: -classpath/-cp %classpath mainClass // the arguments are replaced with: -jar $TMP/maven-exec.jar // NOTE: the jar will contain the classpath and the main class - commandArguments.add( "-jar" ); + commandArguments.add("-jar"); - File tmpFile = createJar( computePath( (Classpath) argument ), - (String) arguments.get( ++i ) ); - commandArguments.add( tmpFile.getAbsolutePath() ); - } - else if ( isLongModulePathArgument( specialArg ) && argument instanceof Modulepath ) - { - String filePath = new File( buildDirectory, "modulepath" ).getAbsolutePath(); + File tmpFile = createJar(computePath((Classpath) argument), (String) arguments.get(++i)); + commandArguments.add(tmpFile.getAbsolutePath()); + } else if (isLongModulePathArgument(specialArg) && argument instanceof Modulepath) { + String filePath = new File(buildDirectory, "modulepath").getAbsolutePath(); StringBuilder modulePath = new StringBuilder(); - modulePath.append( '"' ); - - for ( Iterator it = computePath( (Modulepath) argument ).iterator(); it.hasNext(); ) - { - modulePath.append( it.next().replace( "\\", "\\\\" ) ); - if ( it.hasNext() ) - { - modulePath.append( File.pathSeparatorChar ); + modulePath.append('"'); + + for (Iterator it = + computePath((Modulepath) argument).iterator(); + it.hasNext(); ) { + modulePath.append(it.next().replace("\\", "\\\\")); + if (it.hasNext()) { + modulePath.append(File.pathSeparatorChar); } } - modulePath.append( '"' ); + modulePath.append('"'); - createArgFile( filePath, Arrays.asList( "-p", modulePath.toString() ) ); - commandArguments.add( '@' + filePath ); - } - else - { - commandArguments.add( specialArg ); + createArgFile(filePath, Arrays.asList("-p", modulePath.toString())); + commandArguments.add('@' + filePath); + } else { + commandArguments.add(specialArg); } specialArg = null; @@ -691,63 +615,47 @@ else if ( isLongModulePathArgument( specialArg ) && argument instanceof Modulepa continue; } - if ( argument instanceof Classpath ) - { + if (argument instanceof Classpath) { Classpath specifiedClasspath = (Classpath) argument; - commandArguments.add( computeClasspathString( specifiedClasspath ) ); - } - else if ( argument instanceof Modulepath ) - { + commandArguments.add(computeClasspathString(specifiedClasspath)); + } else if (argument instanceof Modulepath) { Modulepath specifiedModulepath = (Modulepath) argument; - commandArguments.add( computeClasspathString( specifiedModulepath ) ); - } - else if ( (argument instanceof String) && (isLongModulePathArgument( (String) argument ) || isLongClassPathArgument( (String) argument )) ) - { + commandArguments.add(computeClasspathString(specifiedModulepath)); + } else if ((argument instanceof String) + && (isLongModulePathArgument((String) argument) || isLongClassPathArgument((String) argument))) { specialArg = (String) argument; - } - else if (argument == null) - { - commandArguments.add( "" ); - } - else - { - commandArguments.add( (String) argument ); + } else if (argument == null) { + commandArguments.add(""); + } else { + commandArguments.add((String) argument); } } } - private void fillSuccessCodes( Executor exec ) - { - if ( successCodes != null && successCodes.length > 0 ) - { - exec.setExitValues( successCodes ); + private void fillSuccessCodes(Executor exec) { + if (successCodes != null && successCodes.length > 0) { + exec.setExitValues(successCodes); } } - boolean isResultCodeAFailure( int result ) - { - if ( successCodes == null || successCodes.length == 0 ) - { + boolean isResultCodeAFailure(int result) { + if (successCodes == null || successCodes.length == 0) { return result != 0; } - for ( int successCode : successCodes ) - { - if ( successCode == result ) - { + for (int successCode : successCodes) { + if (successCode == result) { return false; } } return true; } - private boolean isLongClassPathArgument( String arg ) - { - return isJavaExec() && longClasspath && ( "-classpath".equals( arg ) || "-cp".equals( arg ) ); + private boolean isLongClassPathArgument(String arg) { + return isJavaExec() && longClasspath && ("-classpath".equals(arg) || "-cp".equals(arg)); } - private boolean isLongModulePathArgument( String arg ) - { - return isJavaExec() && longModulepath && ( "--module-path".equals( arg ) || "-p".equals( arg ) ); + private boolean isLongModulePathArgument(String arg) { + return isJavaExec() && longModulepath && ("--module-path".equals(arg) || "-p".equals(arg)); } /** @@ -755,22 +663,19 @@ private boolean isLongModulePathArgument( String arg ) * * @return {@code true} when a java binary is being executed. */ - private boolean isJavaExec() - { - if ( forceJava ) - { + private boolean isJavaExec() { + if (forceJava) { return true; } - if ( this.executable.contains( "%JAVA_HOME" ) - || this.executable.contains( "${JAVA_HOME}" ) - || this.executable.contains( "$JAVA_HOME" ) ) - { + if (this.executable.contains("%JAVA_HOME") + || this.executable.contains("${JAVA_HOME}") + || this.executable.contains("$JAVA_HOME")) { // also applies to *most* other tools. return true; } - return ENDS_WITH_JAVA.matcher( this.executable ).matches(); + return ENDS_WITH_JAVA.matcher(this.executable).matches(); } /** @@ -782,14 +687,12 @@ private boolean isJavaExec() * default classpath will be used) * @return a platform specific String representation of the classpath */ - private String computeClasspathString( AbstractPath specifiedClasspath ) - { - List resultList = computePath( specifiedClasspath ); + private String computeClasspathString(AbstractPath specifiedClasspath) { + List resultList = computePath(specifiedClasspath); StringBuffer theClasspath = new StringBuffer(); - for ( String str : resultList ) - { - addToClasspath( theClasspath, str ); + for (String str : resultList) { + addToClasspath(theClasspath, str); } return theClasspath.toString(); @@ -804,55 +707,46 @@ private String computeClasspathString( AbstractPath specifiedClasspath ) * default classpath will be used) * @return a list of class path elements */ - private List computePath( AbstractPath specifiedClasspath ) - { + private List computePath(AbstractPath specifiedClasspath) { List artifacts = new ArrayList<>(); List theClasspathFiles = new ArrayList<>(); List resultList = new ArrayList<>(); - collectProjectArtifactsAndClasspath( artifacts, theClasspathFiles ); + collectProjectArtifactsAndClasspath(artifacts, theClasspathFiles); - if ( ( specifiedClasspath != null ) && ( specifiedClasspath.getDependencies() != null ) ) - { - artifacts = filterArtifacts( artifacts, specifiedClasspath.getDependencies() ); + if ((specifiedClasspath != null) && (specifiedClasspath.getDependencies() != null)) { + artifacts = filterArtifacts(artifacts, specifiedClasspath.getDependencies()); } - for ( Path f : theClasspathFiles ) - { - resultList.add( f.toAbsolutePath().toString() ); + for (Path f : theClasspathFiles) { + resultList.add(f.toAbsolutePath().toString()); } - for ( Artifact artifact : artifacts ) - { - getLog().debug( "dealing with " + artifact ); - resultList.add( artifact.getFile().getAbsolutePath() ); + for (Artifact artifact : artifacts) { + getLog().debug("dealing with " + artifact); + resultList.add(artifact.getFile().getAbsolutePath()); } return resultList; } - private static void addToClasspath( StringBuffer theClasspath, String toAdd ) - { - if ( theClasspath.length() > 0 ) - { - theClasspath.append( File.pathSeparator ); + private static void addToClasspath(StringBuffer theClasspath, String toAdd) { + if (theClasspath.length() > 0) { + theClasspath.append(File.pathSeparator); } - theClasspath.append( toAdd ); + theClasspath.append(toAdd); } - private List filterArtifacts( List artifacts, Collection dependencies ) - { + private List filterArtifacts(List artifacts, Collection dependencies) { AndArtifactFilter filter = new AndArtifactFilter(); - filter.add( new IncludesArtifactFilter( new ArrayList( dependencies ) ) ); // gosh + filter.add(new IncludesArtifactFilter(new ArrayList(dependencies))); // gosh List filteredArtifacts = new ArrayList(); - for ( Artifact artifact : artifacts ) - { - if ( filter.include( artifact ) ) - { - getLog().debug( "filtering in " + artifact ); - filteredArtifacts.add( artifact ); + for (Artifact artifact : artifacts) { + if (filter.include(artifact)) { + getLog().debug("filtering in " + artifact); + filteredArtifacts.add(artifact); } } return filteredArtifacts; @@ -860,188 +754,149 @@ private List filterArtifacts( List artifacts, Collection enviro, File dir ) - { - File execFile = new File( executable ); + CommandLine getExecutablePath(Map enviro, File dir) { + File execFile = new File(executable); String exec = null; - if ( execFile.isFile() ) - { - getLog().debug( "Toolchains are ignored, 'executable' parameter is set to " + executable ); + if (execFile.isFile()) { + getLog().debug("Toolchains are ignored, 'executable' parameter is set to " + executable); exec = execFile.getAbsolutePath(); } - if ( exec == null ) - { + if (exec == null) { Toolchain tc = getToolchain(); // if the file doesn't exist & toolchain is null, the exec is probably in the PATH... // we should probably also test for isFile and canExecute, but the second one is only // available in SDK 6. - if ( tc != null ) - { - getLog().info( "Toolchain in exec-maven-plugin: " + tc ); - exec = tc.findTool( executable ); - } - else - { - if ( OS.isFamilyWindows() ) - { - List paths = this.getExecutablePaths( enviro ); - paths.add( 0, dir.getAbsolutePath() ); - - exec = findExecutable( executable, paths ); + if (tc != null) { + getLog().info("Toolchain in exec-maven-plugin: " + tc); + exec = tc.findTool(executable); + } else { + if (OS.isFamilyWindows()) { + List paths = this.getExecutablePaths(enviro); + paths.add(0, dir.getAbsolutePath()); + + exec = findExecutable(executable, paths); } } } - if ( exec == null ) - { + if (exec == null) { exec = executable; } CommandLine toRet; - if ( OS.isFamilyWindows() && !hasNativeExtension( exec ) && hasExecutableExtension( exec ) ) - { + if (OS.isFamilyWindows() && !hasNativeExtension(exec) && hasExecutableExtension(exec)) { // run the windows batch script in isolation and exit at the end - final String comSpec = System.getenv( "ComSpec" ); - toRet = new CommandLine( comSpec == null ? "cmd" : comSpec ); - toRet.addArgument( "/c" ); - toRet.addArgument( exec ); - } - else - { - toRet = new CommandLine( exec ); + final String comSpec = System.getenv("ComSpec"); + toRet = new CommandLine(comSpec == null ? "cmd" : comSpec); + toRet.addArgument("/c"); + toRet.addArgument(exec); + } else { + toRet = new CommandLine(exec); } return toRet; } - static String findExecutable( final String executable, final List paths ) - { + static String findExecutable(final String executable, final List paths) { File f = null; - search: for ( final String path : paths ) - { - f = new File( path, executable ); - if ( !OS.isFamilyWindows() && f.isFile() ) - break; + search: + for (final String path : paths) { + f = new File(path, executable); + if (!OS.isFamilyWindows() && f.isFile()) break; else - for ( final String extension : getExecutableExtensions() ) - { - f = new File( path, executable + extension ); - if ( f.isFile() ) - break search; + for (final String extension : getExecutableExtensions()) { + f = new File(path, executable + extension); + if (f.isFile()) break search; } } - if ( f == null || !f.exists() ) - return null; + if (f == null || !f.exists()) return null; return f.getAbsolutePath(); } - private static boolean hasNativeExtension( final String exec ) - { + private static boolean hasNativeExtension(final String exec) { final String lowerCase = exec.toLowerCase(); - return lowerCase.endsWith( ".exe" ) || lowerCase.endsWith( ".com" ); + return lowerCase.endsWith(".exe") || lowerCase.endsWith(".com"); } - private static boolean hasExecutableExtension( final String exec ) - { + private static boolean hasExecutableExtension(final String exec) { final String lowerCase = exec.toLowerCase(); - for ( final String ext : getExecutableExtensions() ) - if ( lowerCase.endsWith( ext ) ) - return true; + for (final String ext : getExecutableExtensions()) if (lowerCase.endsWith(ext)) return true; return false; } - private static List getExecutableExtensions() - { - final String pathExt = System.getenv( "PATHEXT" ); - return pathExt == null ? Arrays.asList( ".bat", ".cmd" ) - : Arrays.asList( StringUtils.split( pathExt.toLowerCase(), File.pathSeparator ) ); + private static List getExecutableExtensions() { + final String pathExt = System.getenv("PATHEXT"); + return pathExt == null + ? Arrays.asList(".bat", ".cmd") + : Arrays.asList(StringUtils.split(pathExt.toLowerCase(), File.pathSeparator)); } - private List getExecutablePaths( Map enviro ) - { + private List getExecutablePaths(Map enviro) { List paths = new ArrayList(); - paths.add( "" ); + paths.add(""); - String path = enviro.get( "PATH" ); - if ( path != null ) - { - paths.addAll( Arrays.asList( StringUtils.split( path, File.pathSeparator ) ) ); + String path = enviro.get("PATH"); + if (path != null) { + paths.addAll(Arrays.asList(StringUtils.split(path, File.pathSeparator))); } return paths; } - protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, - OutputStream out, OutputStream err ) - throws ExecuteException, IOException - { + protected int executeCommandLine( + Executor exec, CommandLine commandLine, Map enviro, OutputStream out, OutputStream err) + throws ExecuteException, IOException { // note: don't use BufferedOutputStream here since it delays the outputs MEXEC-138 - PumpStreamHandler psh = new PumpStreamHandler( out, err, System.in ); - return executeCommandLine( exec, commandLine, enviro, psh ); + PumpStreamHandler psh = new PumpStreamHandler(out, err, System.in); + return executeCommandLine(exec, commandLine, enviro, psh); } - protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, - FileOutputStream outputFile ) - throws ExecuteException, IOException - { - BufferedOutputStream bos = new BufferedOutputStream( outputFile ); - PumpStreamHandler psh = new PumpStreamHandler( bos ); - return executeCommandLine( exec, commandLine, enviro, psh ); + protected int executeCommandLine( + Executor exec, CommandLine commandLine, Map enviro, FileOutputStream outputFile) + throws ExecuteException, IOException { + BufferedOutputStream bos = new BufferedOutputStream(outputFile); + PumpStreamHandler psh = new PumpStreamHandler(bos); + return executeCommandLine(exec, commandLine, enviro, psh); } - protected int executeCommandLine( Executor exec, final CommandLine commandLine, Map enviro, - final PumpStreamHandler psh ) - throws ExecuteException, IOException - { - exec.setStreamHandler( psh ); + protected int executeCommandLine( + Executor exec, final CommandLine commandLine, Map enviro, final PumpStreamHandler psh) + throws ExecuteException, IOException { + exec.setStreamHandler(psh); int result; - try - { + try { psh.start(); - if ( async ) - { - if ( asyncDestroyOnShutdown ) - { - exec.setProcessDestroyer( getProcessDestroyer() ); + if (async) { + if (asyncDestroyOnShutdown) { + exec.setProcessDestroyer(getProcessDestroyer()); } - exec.execute( commandLine, enviro, new ExecuteResultHandler() - { - public void onProcessFailed( ExecuteException e ) - { - getLog().error( "Async process failed for: " + commandLine, e ); + exec.execute(commandLine, enviro, new ExecuteResultHandler() { + public void onProcessFailed(ExecuteException e) { + getLog().error("Async process failed for: " + commandLine, e); } - public void onProcessComplete( int exitValue ) - { - getLog().info( "Async process complete, exit value = " + exitValue + " for: " + commandLine ); - try - { + public void onProcessComplete(int exitValue) { + getLog().info("Async process complete, exit value = " + exitValue + " for: " + commandLine); + try { psh.stop(); - } - catch ( IOException e ) - { - getLog().error( "Error stopping async process stream handler for: " + commandLine, e ); + } catch (IOException e) { + getLog().error("Error stopping async process stream handler for: " + commandLine, e); } } - } ); + }); result = 0; + } else { + result = exec.execute(commandLine, enviro); } - else - { - result = exec.execute( commandLine, enviro ); - } - } - finally - { - if ( !async ) - { + } finally { + if (!async) { psh.stop(); } } @@ -1052,79 +907,63 @@ public void onProcessComplete( int exitValue ) // methods used for tests purposes - allow mocking and simulate automatic setters // - void setExecutable( String executable ) - { + void setExecutable(String executable) { this.executable = executable; } - String getExecutable() - { + String getExecutable() { return executable; } - void setWorkingDirectory( String workingDir ) - { - setWorkingDirectory( new File( workingDir ) ); + void setWorkingDirectory(String workingDir) { + setWorkingDirectory(new File(workingDir)); } - void setWorkingDirectory( File workingDir ) - { + void setWorkingDirectory(File workingDir) { this.workingDirectory = workingDir; } - void setArguments( List arguments ) - { + void setArguments(List arguments) { this.arguments = arguments; } - void setBasedir( File basedir ) - { + void setBasedir(File basedir) { this.basedir = basedir; } - void setProject( MavenProject project ) - { + void setProject(MavenProject project) { this.project = project; } - protected String getSystemProperty( String key ) - { - return System.getProperty( key ); + protected String getSystemProperty(String key) { + return System.getProperty(key); } - public void setSuccessCodes( Integer... list ) - { + public void setSuccessCodes(Integer... list) { this.successCodes = new int[list.length]; - for ( int index = 0; index < list.length; index++ ) - { + for (int index = 0; index < list.length; index++) { successCodes[index] = list[index]; } } - public int[] getSuccessCodes() - { + public int[] getSuccessCodes() { return successCodes; } - private Toolchain getToolchain() - { + private Toolchain getToolchain() { Toolchain tc = null; - try - { - if ( session != null ) // session is null in tests.. + try { + if (session != null) // session is null in tests.. { ToolchainManager toolchainManager = - (ToolchainManager) session.getContainer().lookup( ToolchainManager.ROLE ); + (ToolchainManager) session.getContainer().lookup(ToolchainManager.ROLE); - if ( toolchainManager != null ) - { - tc = toolchainManager.getToolchainFromBuildContext( toolchain, session ); + if (toolchainManager != null) { + tc = toolchainManager.getToolchainFromBuildContext(toolchain, session); } } - } - catch ( ComponentLookupException componentLookupException ) - { + } catch (ComponentLookupException componentLookupException) { // just ignore, could happen in pre-2.0.9 builds.. } return tc; @@ -1138,165 +977,134 @@ private Toolchain getToolchain() * @return * @throws IOException */ - private File createJar( List classPath, String mainClass ) - throws IOException - { - File file = File.createTempFile( "maven-exec", ".jar" ); + private File createJar(List classPath, String mainClass) throws IOException { + File file = File.createTempFile("maven-exec", ".jar"); file.deleteOnExit(); - FileOutputStream fos = new FileOutputStream( file ); - JarOutputStream jos = new JarOutputStream( fos ); - jos.setLevel( JarOutputStream.STORED ); - JarEntry je = new JarEntry( "META-INF/MANIFEST.MF" ); - jos.putNextEntry( je ); + FileOutputStream fos = new FileOutputStream(file); + JarOutputStream jos = new JarOutputStream(fos); + jos.setLevel(JarOutputStream.STORED); + JarEntry je = new JarEntry("META-INF/MANIFEST.MF"); + jos.putNextEntry(je); Manifest man = new Manifest(); // we can't use StringUtils.join here since we need to add a '/' to // the end of directory entries - otherwise the jvm will ignore them. StringBuilder cp = new StringBuilder(); - for ( String el : classPath ) - { + for (String el : classPath) { // NOTE: if File points to a directory, this entry MUST end in '/'. - cp.append( new URL( new File( el ).toURI().toASCIIString() ).toExternalForm() + " " ); + cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " "); } - man.getMainAttributes().putValue( "Manifest-Version", "1.0" ); - man.getMainAttributes().putValue( "Class-Path", cp.toString().trim() ); - man.getMainAttributes().putValue( "Main-Class", mainClass ); + man.getMainAttributes().putValue("Manifest-Version", "1.0"); + man.getMainAttributes().putValue("Class-Path", cp.toString().trim()); + man.getMainAttributes().putValue("Main-Class", mainClass); - man.write( jos ); + man.write(jos); jos.close(); return file; } - private void createArgFile( String filePath, List lines ) - throws IOException - { - final String EOL = System.getProperty( "line.separator", "\\n" ); + private void createArgFile(String filePath, List lines) throws IOException { + final String EOL = System.getProperty("line.separator", "\\n"); FileWriter writer = null; - try - { - writer = new FileWriter( filePath ); - for ( String line : lines ) - { - writer.append( line ).append( EOL ); + try { + writer = new FileWriter(filePath); + for (String line : lines) { + writer.append(line).append(EOL); } - } - finally - { - IOUtil.close( writer ); + } finally { + IOUtil.close(writer); } } - protected Map createEnvs( File envScriptFile ) - throws MojoExecutionException - { + protected Map createEnvs(File envScriptFile) throws MojoExecutionException { Map results = null; File tmpEnvExecFile = null; - try - { - tmpEnvExecFile = this.createEnvWrapperFile( envScriptFile ); - - Commandline cl = new Commandline();// commons-exec instead? - cl.setExecutable( tmpEnvExecFile.getAbsolutePath() ); - if ( !OS.isFamilyWindows() ) - { - cl.setExecutable( "sh" ); - cl.createArg().setFile( tmpEnvExecFile ); + try { + tmpEnvExecFile = this.createEnvWrapperFile(envScriptFile); + + Commandline cl = new Commandline(); // commons-exec instead? + cl.setExecutable(tmpEnvExecFile.getAbsolutePath()); + if (!OS.isFamilyWindows()) { + cl.setExecutable("sh"); + cl.createArg().setFile(tmpEnvExecFile); } // pickup the initial env vars so that the env script can used if necessary - if ( environmentVariables != null ) - { - for ( Map.Entry item : environmentVariables.entrySet() ) - { - cl.addEnvironment( item.getKey(), item.getValue() ); + if (environmentVariables != null) { + for (Map.Entry item : environmentVariables.entrySet()) { + cl.addEnvironment(item.getKey(), item.getValue()); } } EnvStreamConsumer stdout = new EnvStreamConsumer(); StreamConsumer stderr = new DefaultConsumer(); - CommandLineUtils.executeCommandLine( cl, stdout, stderr ); + CommandLineUtils.executeCommandLine(cl, stdout, stderr); - if(!stdout.getUnparsedLines().isEmpty()) - { - getLog().warn( "The following lines could not be parsed into environment variables :" ); - for ( String line : stdout.getUnparsedLines() ) - { - getLog().warn( line ); + if (!stdout.getUnparsedLines().isEmpty()) { + getLog().warn("The following lines could not be parsed into environment variables :"); + for (String line : stdout.getUnparsedLines()) { + getLog().warn(line); } } results = stdout.getParsedEnv(); - } - catch ( CommandLineException e ) - { - throw new MojoExecutionException( e.getMessage() ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage() ); - } - finally - { - if ( tmpEnvExecFile != null ) - { + } catch (CommandLineException e) { + throw new MojoExecutionException(e.getMessage()); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage()); + } finally { + if (tmpEnvExecFile != null) { tmpEnvExecFile.delete(); } } return results; - } - protected File createEnvWrapperFile( File envScript ) - throws IOException - { + protected File createEnvWrapperFile(File envScript) throws IOException { PrintWriter writer = null; File tmpFile = null; - try - { - - if ( OS.isFamilyWindows() ) - { - tmpFile = File.createTempFile( "env", ".bat" ); - writer = new PrintWriter( tmpFile ); - writer.append( "@echo off" ).println(); - writer.append( "call \"" ).append( envScript.getCanonicalPath() ).append( "\"" ).println(); - writer.append( "echo " + EnvStreamConsumer.START_PARSING_INDICATOR ).println(); - writer.append( "set" ).println(); + try { + + if (OS.isFamilyWindows()) { + tmpFile = File.createTempFile("env", ".bat"); + writer = new PrintWriter(tmpFile); + writer.append("@echo off").println(); + writer.append("call \"") + .append(envScript.getCanonicalPath()) + .append("\"") + .println(); + writer.append("echo " + EnvStreamConsumer.START_PARSING_INDICATOR) + .println(); + writer.append("set").println(); writer.flush(); - } - else - { - tmpFile = File.createTempFile( "env", ".sh" ); + } else { + tmpFile = File.createTempFile("env", ".sh"); // tmpFile.setExecutable( true );//java 6 only - writer = new PrintWriter( tmpFile ); - writer.append( "#! /bin/sh" ).println(); - writer.append( ". " ).append( envScript.getCanonicalPath() ).println(); // works on all unix?? - writer.append( "echo " + EnvStreamConsumer.START_PARSING_INDICATOR ).println(); - writer.append( "env" ).println(); + writer = new PrintWriter(tmpFile); + writer.append("#! /bin/sh").println(); + writer.append(". ").append(envScript.getCanonicalPath()).println(); // works on all unix?? + writer.append("echo " + EnvStreamConsumer.START_PARSING_INDICATOR) + .println(); + writer.append("env").println(); writer.flush(); } - } - finally - { - IOUtil.close( writer ); + } finally { + IOUtil.close(writer); } return tmpFile; - } - protected ProcessDestroyer getProcessDestroyer() - { - if ( processDestroyer == null ) - { + protected ProcessDestroyer getProcessDestroyer() { + if (processDestroyer == null) { processDestroyer = new ShutdownHookProcessDestroyer(); } return processDestroyer; diff --git a/src/main/java/org/codehaus/mojo/exec/ExecutableDependency.java b/src/main/java/org/codehaus/mojo/exec/ExecutableDependency.java index d01220fe..cf4fa3e8 100644 --- a/src/main/java/org/codehaus/mojo/exec/ExecutableDependency.java +++ b/src/main/java/org/codehaus/mojo/exec/ExecutableDependency.java @@ -26,8 +26,7 @@ * ExecutableDependency class. *

*/ -public class ExecutableDependency -{ +public class ExecutableDependency { private String groupId; private String artifactId; @@ -36,11 +35,10 @@ public class ExecutableDependency *

* Getter for the field groupId. *

- * + * * @return a {@link java.lang.String} object. */ - public String getGroupId() - { + public String getGroupId() { return this.groupId; } @@ -48,11 +46,10 @@ public String getGroupId() *

* Setter for the field groupId. *

- * + * * @param groupId a {@link java.lang.String} object. */ - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } @@ -60,11 +57,10 @@ public void setGroupId( String groupId ) *

* Getter for the field artifactId. *

- * + * * @return a {@link java.lang.String} object. */ - public String getArtifactId() - { + public String getArtifactId() { return this.artifactId; } @@ -72,11 +68,10 @@ public String getArtifactId() *

* Setter for the field artifactId. *

- * + * * @param artifactId a {@link java.lang.String} object. */ - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } @@ -84,42 +79,35 @@ public void setArtifactId( String artifactId ) *

* Matches the groupId and artifactId. *

- * + * * @param artifact a {@link org.apache.maven.artifact.Artifact} object. * @return true if both math, false otherwise. */ - public boolean matches( Artifact artifact ) - { - return artifact.getGroupId().equals( this.getGroupId() ) - && artifact.getArtifactId().equals( this.getArtifactId() ); + public boolean matches(Artifact artifact) { + return artifact.getGroupId().equals(this.getGroupId()) + && artifact.getArtifactId().equals(this.getArtifactId()); } /** {@inheritDoc} */ - public String toString() - { + public String toString() { return this.groupId + ":" + this.artifactId; } /** {@inheritDoc} */ - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof ExecutableDependency ) ) - { + if (!(o instanceof ExecutableDependency)) { return false; } final ExecutableDependency that = (ExecutableDependency) o; - if ( artifactId != null ? !artifactId.equals( that.artifactId ) : that.artifactId != null ) - { + if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) { return false; } - if ( groupId != null ? !groupId.equals( that.groupId ) : that.groupId != null ) - { + if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) { return false; } @@ -127,11 +115,10 @@ public boolean equals( Object o ) } /** {@inheritDoc} */ - public int hashCode() - { + public int hashCode() { int result; - result = ( groupId != null ? groupId.hashCode() : 0 ); - result = 29 * result + ( artifactId != null ? artifactId.hashCode() : 0 ); + result = (groupId != null ? groupId.hashCode() : 0); + result = 29 * result + (artifactId != null ? artifactId.hashCode() : 0); return result; } } diff --git a/src/main/java/org/codehaus/mojo/exec/ExtendedExecutor.java b/src/main/java/org/codehaus/mojo/exec/ExtendedExecutor.java index 3da6e76c..7e57ec1a 100644 --- a/src/main/java/org/codehaus/mojo/exec/ExtendedExecutor.java +++ b/src/main/java/org/codehaus/mojo/exec/ExtendedExecutor.java @@ -19,57 +19,47 @@ * under the License. */ +import java.io.File; +import java.io.IOException; +import java.util.Map; + import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.OS; import org.apache.commons.exec.launcher.VmsCommandLauncher; -import java.io.File; -import java.io.IOException; -import java.util.Map; - /** * An executor which has the ability to use the {@link ProcessBuilder#inheritIO()} flag. * * @author Guillaume Nodet (gnodet@gmail.com) */ -public class ExtendedExecutor extends DefaultExecutor -{ +public class ExtendedExecutor extends DefaultExecutor { private final boolean inheritIo; - public ExtendedExecutor( boolean inheritIo ) - { + public ExtendedExecutor(boolean inheritIo) { this.inheritIo = inheritIo; } @Override - protected Process launch( CommandLine command, Map env, File dir ) throws IOException - { - if ( dir != null && !dir.exists() ) - { - throw new IOException( dir + " doesn't exist." ); + protected Process launch(CommandLine command, Map env, File dir) throws IOException { + if (dir != null && !dir.exists()) { + throw new IOException(dir + " doesn't exist."); } - if ( OS.isFamilyOpenVms() ) - { - return new VmsCommandLauncher().exec( command, env, dir ); - } - else - { - ProcessBuilder pb = new ProcessBuilder( command.toStrings() ); - for ( Map.Entry entry : env.entrySet() ) - { + if (OS.isFamilyOpenVms()) { + return new VmsCommandLauncher().exec(command, env, dir); + } else { + ProcessBuilder pb = new ProcessBuilder(command.toStrings()); + for (Map.Entry entry : env.entrySet()) { String key = entry.getKey() != null ? entry.getKey() : ""; String val = entry.getValue() != null ? entry.getValue() : ""; - pb.environment().put( key, val ); + pb.environment().put(key, val); } - pb.directory( dir ); - if ( inheritIo ) - { + pb.directory(dir); + if (inheritIo) { pb.inheritIO(); } return pb.start(); } } - } diff --git a/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java b/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java index f3cbb4e6..e79ff426 100644 --- a/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java +++ b/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java @@ -30,7 +30,7 @@ * redirects that line to some {@link Consumer} to act upon as it pleases. This * class is not thread safe and expects to have only one active writer consuming * it at any given time. - * + * * @since 3.0.0 */ class LineRedirectOutputStream extends OutputStream { diff --git a/src/main/java/org/codehaus/mojo/exec/Modulepath.java b/src/main/java/org/codehaus/mojo/exec/Modulepath.java index b48291da..777099d9 100644 --- a/src/main/java/org/codehaus/mojo/exec/Modulepath.java +++ b/src/main/java/org/codehaus/mojo/exec/Modulepath.java @@ -22,6 +22,4 @@ /** * @author Jerome Lacoste (jerome@coffeebreaks.org) */ -public class Modulepath extends AbstractPath -{ -} +public class Modulepath extends AbstractPath {} diff --git a/src/main/java/org/codehaus/mojo/exec/PathsToolchain.java b/src/main/java/org/codehaus/mojo/exec/PathsToolchain.java index 5a7a4f6f..2f7174a6 100644 --- a/src/main/java/org/codehaus/mojo/exec/PathsToolchain.java +++ b/src/main/java/org/codehaus/mojo/exec/PathsToolchain.java @@ -1,63 +1,56 @@ -package org.codehaus.mojo.exec; - -/* - * 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.util.List; - -import org.apache.maven.toolchain.DefaultToolchain; -import org.apache.maven.toolchain.model.ToolchainModel; -import org.codehaus.plexus.logging.Logger; - -/** - * Searches a list of configured paths for the requested tool. - * - * @author Markus KARG (markus@headcrashing.eu) - */ -class PathsToolchain - extends DefaultToolchain -{ - private List paths; - - public PathsToolchain( final ToolchainModel model, final Logger logger ) - { - super( model, "paths", logger ); // NOI18N - } - - public List getPaths() - { - return this.paths; - } - - public void setPaths( final List paths ) - { - this.paths = paths; - } - - @Override - public String toString() - { - return "Paths" + this.getPaths(); // NOI18N - } - - public String findTool( final String toolName ) - { - return ExecMojo.findExecutable( toolName, this.paths ); - } -} \ No newline at end of file +package org.codehaus.mojo.exec; + +/* + * 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.util.List; + +import org.apache.maven.toolchain.DefaultToolchain; +import org.apache.maven.toolchain.model.ToolchainModel; +import org.codehaus.plexus.logging.Logger; + +/** + * Searches a list of configured paths for the requested tool. + * + * @author Markus KARG (markus@headcrashing.eu) + */ +class PathsToolchain extends DefaultToolchain { + private List paths; + + public PathsToolchain(final ToolchainModel model, final Logger logger) { + super(model, "paths", logger); // NOI18N + } + + public List getPaths() { + return this.paths; + } + + public void setPaths(final List paths) { + this.paths = paths; + } + + @Override + public String toString() { + return "Paths" + this.getPaths(); // NOI18N + } + + public String findTool(final String toolName) { + return ExecMojo.findExecutable(toolName, this.paths); + } +} diff --git a/src/main/java/org/codehaus/mojo/exec/PathsToolchainFactory.java b/src/main/java/org/codehaus/mojo/exec/PathsToolchainFactory.java index 689ad5a6..c0db9276 100644 --- a/src/main/java/org/codehaus/mojo/exec/PathsToolchainFactory.java +++ b/src/main/java/org/codehaus/mojo/exec/PathsToolchainFactory.java @@ -1,157 +1,133 @@ -package org.codehaus.mojo.exec; - -/* - * 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.beans.IntrospectionException; -import java.beans.PropertyDescriptor; -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.maven.toolchain.MisconfiguredToolchainException; -import org.apache.maven.toolchain.RequirementMatcherFactory; -import org.apache.maven.toolchain.ToolchainFactory; -import org.apache.maven.toolchain.ToolchainPrivate; -import org.apache.maven.toolchain.model.ToolchainModel; -import org.codehaus.plexus.component.annotations.Component; -import org.codehaus.plexus.component.annotations.Requirement; -import org.codehaus.plexus.logging.Logger; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.xml.Xpp3Dom; - -/** - * Factory for {@link PathsToolchain}. - * - * @author Markus KARG (markus@headcrashing.eu) - */ -@Component( role = ToolchainFactory.class, hint = "paths" ) -class PathsToolchainFactory - implements ToolchainFactory -{ - - @Requirement - private Logger logger; - - public ToolchainPrivate createToolchain( final ToolchainModel model ) - throws MisconfiguredToolchainException - { - if ( model == null ) - return null; - - final PathsToolchain pathsToolchain = new PathsToolchain( model, this.logger ); - final Properties provides = this.getProvidesProperties( model ); - for ( final Map.Entry provide : provides.entrySet() ) - { - final String key = (String) provide.getKey(); - final String value = (String) provide.getValue(); - if ( value == null ) - throw new MisconfiguredToolchainException( "Provides token '" + key - + "' doesn't have any value configured." ); - - pathsToolchain.addProvideToken( key, RequirementMatcherFactory.createExactMatcher( value ) ); - } - - final Xpp3Dom config = (Xpp3Dom) model.getConfiguration(); - if ( config == null ) - return pathsToolchain; - - final Xpp3Dom pathDom = config.getChild( "paths" ); - if ( pathDom == null ) - return pathsToolchain; - - final Xpp3Dom[] pathDoms = pathDom.getChildren( "path" ); - if ( pathDoms == null || pathDoms.length == 0 ) - return pathsToolchain; - - final List paths = new ArrayList( pathDoms.length ); - for ( final Xpp3Dom pathdom : pathDoms ) - { - final String pathString = pathdom.getValue(); - - if ( pathString == null ) - throw new MisconfiguredToolchainException( "path element is empty" ); - - final String normalizedPath = FileUtils.normalize( pathString ); - final File file = new File( normalizedPath ); - if ( !file.exists() ) - throw new MisconfiguredToolchainException( "Non-existing path '" + file.getAbsolutePath() + "'" ); - - paths.add( normalizedPath ); - } - - pathsToolchain.setPaths( paths ); - - return pathsToolchain; - } - - public ToolchainPrivate createDefaultToolchain() - { - return null; - } - - protected Properties getProvidesProperties( final ToolchainModel model ) - { - final Object value = this.getBeanProperty( model, "provides" ); - - return value instanceof Properties ? (Properties) value : toProperties( (Xpp3Dom) value ); - } - - protected static Properties toProperties( final Xpp3Dom dom ) - { - final Properties props = new Properties(); - - final Xpp3Dom[] children = dom.getChildren(); - for ( final Xpp3Dom child : children ) - props.put( child.getName(), child.getValue() ); - - return props; - } - - protected Object getBeanProperty( final Object obj, final String property ) - { - try - { - final Method method = new PropertyDescriptor( property, obj.getClass() ).getReadMethod(); - - return method.invoke( obj ); - } - catch ( final IntrospectionException e ) - { - throw new RuntimeException( "Incompatible toolchain API", e ); - } - catch ( final IllegalAccessException e ) - { - throw new RuntimeException( "Incompatible toolchain API", e ); - } - catch ( final InvocationTargetException e ) - { - final Throwable cause = e.getCause(); - - if ( cause instanceof RuntimeException ) - throw (RuntimeException) cause; - - throw new RuntimeException( "Incompatible toolchain API", e ); - } - } -} +package org.codehaus.mojo.exec; + +/* + * 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.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.maven.toolchain.MisconfiguredToolchainException; +import org.apache.maven.toolchain.RequirementMatcherFactory; +import org.apache.maven.toolchain.ToolchainFactory; +import org.apache.maven.toolchain.ToolchainPrivate; +import org.apache.maven.toolchain.model.ToolchainModel; +import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.component.annotations.Requirement; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +/** + * Factory for {@link PathsToolchain}. + * + * @author Markus KARG (markus@headcrashing.eu) + */ +@Component(role = ToolchainFactory.class, hint = "paths") +class PathsToolchainFactory implements ToolchainFactory { + + @Requirement + private Logger logger; + + public ToolchainPrivate createToolchain(final ToolchainModel model) throws MisconfiguredToolchainException { + if (model == null) return null; + + final PathsToolchain pathsToolchain = new PathsToolchain(model, this.logger); + final Properties provides = this.getProvidesProperties(model); + for (final Map.Entry provide : provides.entrySet()) { + final String key = (String) provide.getKey(); + final String value = (String) provide.getValue(); + if (value == null) + throw new MisconfiguredToolchainException( + "Provides token '" + key + "' doesn't have any value configured."); + + pathsToolchain.addProvideToken(key, RequirementMatcherFactory.createExactMatcher(value)); + } + + final Xpp3Dom config = (Xpp3Dom) model.getConfiguration(); + if (config == null) return pathsToolchain; + + final Xpp3Dom pathDom = config.getChild("paths"); + if (pathDom == null) return pathsToolchain; + + final Xpp3Dom[] pathDoms = pathDom.getChildren("path"); + if (pathDoms == null || pathDoms.length == 0) return pathsToolchain; + + final List paths = new ArrayList(pathDoms.length); + for (final Xpp3Dom pathdom : pathDoms) { + final String pathString = pathdom.getValue(); + + if (pathString == null) throw new MisconfiguredToolchainException("path element is empty"); + + final String normalizedPath = FileUtils.normalize(pathString); + final File file = new File(normalizedPath); + if (!file.exists()) + throw new MisconfiguredToolchainException("Non-existing path '" + file.getAbsolutePath() + "'"); + + paths.add(normalizedPath); + } + + pathsToolchain.setPaths(paths); + + return pathsToolchain; + } + + public ToolchainPrivate createDefaultToolchain() { + return null; + } + + protected Properties getProvidesProperties(final ToolchainModel model) { + final Object value = this.getBeanProperty(model, "provides"); + + return value instanceof Properties ? (Properties) value : toProperties((Xpp3Dom) value); + } + + protected static Properties toProperties(final Xpp3Dom dom) { + final Properties props = new Properties(); + + final Xpp3Dom[] children = dom.getChildren(); + for (final Xpp3Dom child : children) props.put(child.getName(), child.getValue()); + + return props; + } + + protected Object getBeanProperty(final Object obj, final String property) { + try { + final Method method = new PropertyDescriptor(property, obj.getClass()).getReadMethod(); + + return method.invoke(obj); + } catch (final IntrospectionException e) { + throw new RuntimeException("Incompatible toolchain API", e); + } catch (final IllegalAccessException e) { + throw new RuntimeException("Incompatible toolchain API", e); + } catch (final InvocationTargetException e) { + final Throwable cause = e.getCause(); + + if (cause instanceof RuntimeException) throw (RuntimeException) cause; + + throw new RuntimeException("Incompatible toolchain API", e); + } + } +} diff --git a/src/main/java/org/codehaus/mojo/exec/ProjectProperties.java b/src/main/java/org/codehaus/mojo/exec/ProjectProperties.java index 8da4db81..2094c288 100644 --- a/src/main/java/org/codehaus/mojo/exec/ProjectProperties.java +++ b/src/main/java/org/codehaus/mojo/exec/ProjectProperties.java @@ -22,6 +22,4 @@ /** * Represents all project properties (to set as system properties). */ -public class ProjectProperties extends AbstractProperty -{ -} +public class ProjectProperties extends AbstractProperty {} diff --git a/src/main/java/org/codehaus/mojo/exec/Property.java b/src/main/java/org/codehaus/mojo/exec/Property.java index 096e299f..2753a8d1 100644 --- a/src/main/java/org/codehaus/mojo/exec/Property.java +++ b/src/main/java/org/codehaus/mojo/exec/Property.java @@ -21,11 +21,10 @@ /** * Wrapper class for the systemProperty argument type. - * + * * @author Kaare Nilsen (kaare.nilsen@gmail.com) */ -public class Property extends AbstractProperty -{ +public class Property extends AbstractProperty { private String key; private String value; @@ -34,11 +33,10 @@ public class Property extends AbstractProperty *

* Getter for the field key. *

- * + * * @return a {@link java.lang.String} object. */ - public String getKey() - { + public String getKey() { return key; } @@ -46,11 +44,10 @@ public String getKey() *

* Setter for the field key. *

- * + * * @param key a {@link java.lang.String} object. */ - public void setKey( String key ) - { + public void setKey(String key) { this.key = key; } @@ -58,11 +55,10 @@ public void setKey( String key ) *

* Getter for the field value. *

- * + * * @return a {@link java.lang.String} object. */ - public String getValue() - { + public String getValue() { return value; } @@ -70,11 +66,10 @@ public String getValue() *

* Setter for the field value. *

- * + * * @param value a {@link java.lang.String} object. */ - public void setValue( String value ) - { + public void setValue(String value) { this.value = value; } } diff --git a/src/main/java/org/codehaus/mojo/exec/SystemExitException.java b/src/main/java/org/codehaus/mojo/exec/SystemExitException.java index 90127be5..6fbb6cf7 100644 --- a/src/main/java/org/codehaus/mojo/exec/SystemExitException.java +++ b/src/main/java/org/codehaus/mojo/exec/SystemExitException.java @@ -2,13 +2,13 @@ /* * Copyright MojoHaus and Contributors - * + * * Licensed 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. @@ -18,21 +18,18 @@ /** * Exception to be thrown by {@link SystemExitManager} when {@link System#exit(int)} is called - * + * * @author Alexander Kriegisch */ -public class SystemExitException extends SecurityException -{ +public class SystemExitException extends SecurityException { private final int exitCode; - public SystemExitException( String s, int exitCode ) - { - super( s ); + public SystemExitException(String s, int exitCode) { + super(s); this.exitCode = exitCode; } - public int getExitCode() - { + public int getExitCode() { return exitCode; } } diff --git a/src/main/java/org/codehaus/mojo/exec/SystemExitManager.java b/src/main/java/org/codehaus/mojo/exec/SystemExitManager.java index a312b851..fa8dd0a1 100644 --- a/src/main/java/org/codehaus/mojo/exec/SystemExitManager.java +++ b/src/main/java/org/codehaus/mojo/exec/SystemExitManager.java @@ -2,13 +2,13 @@ /* * Copyright MojoHaus and Contributors - * + * * Licensed 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. @@ -21,15 +21,13 @@ /** * A special security manager (SM) passing on permission checks to the original SM it replaces, except for * {@link #checkExit(int)} - * + * * @author Alexander Kriegisch */ -public class SystemExitManager extends SecurityManager -{ +public class SystemExitManager extends SecurityManager { private final SecurityManager originalSecurityManager; - public SystemExitManager( SecurityManager originalSecurityManager ) - { + public SystemExitManager(SecurityManager originalSecurityManager) { this.originalSecurityManager = originalSecurityManager; } @@ -51,22 +49,18 @@ public SystemExitManager( SecurityManager originalSecurityManager ) * JVM with an error code. * * - * + * * @param status the exit status */ @Override - public void checkExit( int status ) - { - throw new SystemExitException( "System::exit was called with return code " + status, status ); + public void checkExit(int status) { + throw new SystemExitException("System::exit was called with return code " + status, status); } @Override - public void checkPermission( Permission perm ) - { - if ( originalSecurityManager != null ) - { - originalSecurityManager.checkPermission( perm ); + public void checkPermission(Permission perm) { + if (originalSecurityManager != null) { + originalSecurityManager.checkPermission(perm); } } - } diff --git a/src/main/java/org/codehaus/mojo/exec/SystemProperty.java b/src/main/java/org/codehaus/mojo/exec/SystemProperty.java index 26f9df77..e16a7e09 100644 --- a/src/main/java/org/codehaus/mojo/exec/SystemProperty.java +++ b/src/main/java/org/codehaus/mojo/exec/SystemProperty.java @@ -22,6 +22,4 @@ /** * Just to comply to maven configuration (object converter) and the legacy configuration. */ -public class SystemProperty extends Property -{ -} +public class SystemProperty extends Property {} diff --git a/src/main/java/org/codehaus/mojo/exec/URLClassLoaderBuilder.java b/src/main/java/org/codehaus/mojo/exec/URLClassLoaderBuilder.java index 95762e29..36a6b68b 100644 --- a/src/main/java/org/codehaus/mojo/exec/URLClassLoaderBuilder.java +++ b/src/main/java/org/codehaus/mojo/exec/URLClassLoaderBuilder.java @@ -19,8 +19,6 @@ * under the License. */ -import org.apache.maven.plugin.logging.Log; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -35,92 +33,75 @@ import java.util.Iterator; import java.util.List; +import org.apache.maven.plugin.logging.Log; + import static java.util.Arrays.asList; /** - * + * * @author Robert Scholte * @since 3.0.0 */ -class URLClassLoaderBuilder -{ +class URLClassLoaderBuilder { private Log logger; private Collection paths; private Collection exclusions; - private URLClassLoaderBuilder() - { - } + private URLClassLoaderBuilder() {} - static URLClassLoaderBuilder builder() - { + static URLClassLoaderBuilder builder() { return new URLClassLoaderBuilder(); } - URLClassLoaderBuilder setLogger(Log logger ) - { + URLClassLoaderBuilder setLogger(Log logger) { this.logger = logger; return this; } - URLClassLoaderBuilder setExclusions(Collection exclusions ) - { + URLClassLoaderBuilder setExclusions(Collection exclusions) { this.exclusions = exclusions; return this; } - URLClassLoaderBuilder setPaths(Collection paths ) - { + URLClassLoaderBuilder setPaths(Collection paths) { this.paths = paths; return this; } - URLClassLoader build() throws IOException - { - List urls = new ArrayList<>( paths.size() ); - - for ( Path dependency : paths ) - { - if ( exclusions != null && exclusions.contains( dependency.getFileName().toString() ) ) - { - if ( logger != null ) - { - logger.debug("Excluding as requested '" + dependency + "'" ); + URLClassLoader build() throws IOException { + List urls = new ArrayList<>(paths.size()); + + for (Path dependency : paths) { + if (exclusions != null + && exclusions.contains(dependency.getFileName().toString())) { + if (logger != null) { + logger.debug("Excluding as requested '" + dependency + "'"); } continue; } - try - { - urls.add( dependency.toUri().toURL() ); - } - catch ( MalformedURLException e ) - { - throw new IOException( "Error during setting up classpath", e ); + try { + urls.add(dependency.toUri().toURL()); + } catch (MalformedURLException e) { + throw new IOException("Error during setting up classpath", e); } } - return new ExecJavaClassLoader( urls.toArray( new URL[0] ) ); + return new ExecJavaClassLoader(urls.toArray(new URL[0])); } // child first strategy - private static class ExecJavaClassLoader extends URLClassLoader - { - static - { - try - { + private static class ExecJavaClassLoader extends URLClassLoader { + static { + try { registerAsParallelCapable(); - } - catch ( Exception e ) - { + } catch (Exception e) { // no-op, not that important } } private final String jre; - public ExecJavaClassLoader(URL[] urls ) - { + public ExecJavaClassLoader(URL[] urls) { super(urls); jre = getJre(); } @@ -131,49 +112,37 @@ public Class loadClass(final String name, final boolean resolve) throws Class throw new ClassNotFoundException(); } - synchronized ( getClassLoadingLock( name ) ) - { + synchronized (getClassLoadingLock(name)) { Class clazz; // if in the JVM, never override them - if ( isDirectJvmClass( name ) ) - { - try - { - clazz = getSystemClassLoader().loadClass( name ); - if ( postLoad( resolve, clazz ) ) - { + if (isDirectJvmClass(name)) { + try { + clazz = getSystemClassLoader().loadClass(name); + if (postLoad(resolve, clazz)) { return clazz; } - } - catch ( NoClassDefFoundError | ClassNotFoundException ignored ) - { + } catch (NoClassDefFoundError | ClassNotFoundException ignored) { // no-op } } // already loaded? - clazz = findLoadedClass( name ); - if ( postLoad( resolve, clazz ) ) - { + clazz = findLoadedClass(name); + if (postLoad(resolve, clazz)) { return clazz; } // look for it in this classloader - try - { - clazz = super.findClass( name ); - if (clazz != null) - { - if ( postLoad( resolve, clazz ) ) - { + try { + clazz = super.findClass(name); + if (clazz != null) { + if (postLoad(resolve, clazz)) { return clazz; } return clazz; } - } - catch ( ClassNotFoundException | NoClassDefFoundError ignored ) - { + } catch (ClassNotFoundException | NoClassDefFoundError ignored) { // try next } @@ -182,16 +151,12 @@ public Class loadClass(final String name, final boolean resolve) throws Class if (parent == null) { parent = getSystemClassLoader(); } - try - { - clazz = Class.forName( name, false, parent ); - if ( postLoad( resolve, clazz ) ) - { + try { + clazz = Class.forName(name, false, parent); + if (postLoad(resolve, clazz)) { return clazz; } - } - catch ( ClassNotFoundException ignored ) - { + } catch (ClassNotFoundException ignored) { // no-op } @@ -200,120 +165,96 @@ public Class loadClass(final String name, final boolean resolve) throws Class } @Override - public Enumeration getResources( String name ) throws IOException - { + public Enumeration getResources(String name) throws IOException { final Enumeration selfResources = findResources(name); final Enumeration parentResources = getParent().getResources(name); - if (!parentResources.hasMoreElements()) - { + if (!parentResources.hasMoreElements()) { return selfResources; } - if (!selfResources.hasMoreElements()) - { + if (!selfResources.hasMoreElements()) { return new FilteringUrlEnum(parentResources); } return new ChainedEnumerations( - asList( selfResources, new FilteringUrlEnum(parentResources) ).iterator()); + asList(selfResources, new FilteringUrlEnum(parentResources)).iterator()); } - private boolean isInJvm( URL resource ) - { + private boolean isInJvm(URL resource) { final Path path = toPath(resource); - if (path == null) - { + if (path == null) { return false; } return path.normalize().toAbsolutePath().toString().startsWith(jre); } - private String getJre() - { - final Path home = new File( System.getProperty("java.home", "") ).toPath(); - if ( "jre".equals( home.getFileName().toString() ) && home.getParent() != null && - Files.exists(home.getParent().resolve( "lib/tools.jar" ) ) ) - { + private String getJre() { + final Path home = new File(System.getProperty("java.home", "")).toPath(); + if ("jre".equals(home.getFileName().toString()) + && home.getParent() != null + && Files.exists(home.getParent().resolve("lib/tools.jar"))) { return home.getParent().toAbsolutePath().toString(); } return home.toAbsolutePath().toString(); } - private Path toPath(final URL url) - { - if ( "jar".equals( url.getProtocol()) ) - { - try - { + private Path toPath(final URL url) { + if ("jar".equals(url.getProtocol())) { + try { String spec = url.getFile(); - int separator = spec.indexOf( '!' ); - if ( separator == -1 ) { + int separator = spec.indexOf('!'); + if (separator == -1) { return null; } - return toPath( new URL( spec.substring( 0, separator + 1 ) ) ) ; - } - catch ( MalformedURLException e ) - { + return toPath(new URL(spec.substring(0, separator + 1))); + } catch (MalformedURLException e) { // no-op } - } - else if ( "file".equals( url.getProtocol() ) ) - { - String path = decode( url.getFile() ); - if (path.endsWith( "!" )) - { - path = path.substring( 0, path.length() - 1 ); + } else if ("file".equals(url.getProtocol())) { + String path = decode(url.getFile()); + if (path.endsWith("!")) { + path = path.substring(0, path.length() - 1); } return new File(path).getAbsoluteFile().toPath(); } return null; } - private String decode( String fileName ) - { - if ( fileName.indexOf( '%' ) == -1 ) - { + private String decode(String fileName) { + if (fileName.indexOf('%') == -1) { return fileName; } - final StringBuilder result = new StringBuilder( fileName.length() ); + final StringBuilder result = new StringBuilder(fileName.length()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); - for ( int i = 0; i < fileName.length(); ) - { - final char c = fileName.charAt( i ); + for (int i = 0; i < fileName.length(); ) { + final char c = fileName.charAt(i); - if ( c == '%' ) - { + if (c == '%') { out.reset(); - do - { - if ( i + 2 >= fileName.length() ) - { - throw new IllegalArgumentException( "Incomplete % sequence at: " + i ); + do { + if (i + 2 >= fileName.length()) { + throw new IllegalArgumentException("Incomplete % sequence at: " + i); } - final int d1 = Character.digit( fileName.charAt( i + 1 ), 16 ); - final int d2 = Character.digit (fileName.charAt( i + 2 ), 16 ); + final int d1 = Character.digit(fileName.charAt(i + 1), 16); + final int d2 = Character.digit(fileName.charAt(i + 2), 16); - if ( d1 == -1 || d2 == -1 ) - { + if (d1 == -1 || d2 == -1) { throw new IllegalArgumentException( - "Invalid % sequence (" + fileName.substring(i, i + 3) + ") at: " + i ); + "Invalid % sequence (" + fileName.substring(i, i + 3) + ") at: " + i); } - out.write( (byte) ( ( d1 << 4 ) + d2 ) ); + out.write((byte) ((d1 << 4) + d2)); i += 3; - } - while ( i < fileName.length() && fileName.charAt(i) == '%' ); + } while (i < fileName.length() && fileName.charAt(i) == '%'); - result.append( out.toString() ); + result.append(out.toString()); continue; - } - else - { - result.append( c ); + } else { + result.append(c); } i++; @@ -321,13 +262,10 @@ private String decode( String fileName ) return result.toString(); } - private boolean postLoad( boolean resolve, Class clazz ) - { - if ( clazz != null ) - { - if (resolve) - { - resolveClass( clazz ); + private boolean postLoad(boolean resolve, Class clazz) { + if (clazz != null) { + if (resolve) { + resolveClass(clazz); } return true; } @@ -336,162 +274,122 @@ private boolean postLoad( boolean resolve, Class clazz ) // not all jvm classes, for ex "javax" can be overriden so don't list it here private boolean isDirectJvmClass(final String name) { - if (name.startsWith( "java." ) ) - { + if (name.startsWith("java.")) { return true; } - if ( name.startsWith( "sun." ) ) - { + if (name.startsWith("sun.")) { return true; } - if ( name.startsWith( "jdk." ) ) - { + if (name.startsWith("jdk.")) { return true; } - if ( name.startsWith( "oracle." ) ) - { + if (name.startsWith("oracle.")) { return true; } - if ( name.startsWith( "javafx." ) ) - { + if (name.startsWith("javafx.")) { return true; } - if ( name.startsWith( "netscape." ) ) - { + if (name.startsWith("netscape.")) { return true; } - if ( name.startsWith( "org." ) ) - { - final String sub = name.substring( "org.".length() ); - if ( sub.startsWith( "w3c.dom." ) ) - { + if (name.startsWith("org.")) { + final String sub = name.substring("org.".length()); + if (sub.startsWith("w3c.dom.")) { return true; } - if ( sub.startsWith( "omg." ) ) - { + if (sub.startsWith("omg.")) { return true; } - if ( sub.startsWith( "xml.sax." ) ) - { + if (sub.startsWith("xml.sax.")) { return true; } - if ( sub.startsWith( "ietf.jgss." ) ) - { + if (sub.startsWith("ietf.jgss.")) { return true; } - if ( sub.startsWith( "jcp.xml.dsig.internal." ) ) - { + if (sub.startsWith("jcp.xml.dsig.internal.")) { return true; } } - if ( name.startsWith( "com." ) ) - { - final String sub = name.substring( "com.".length() ); - if ( sub.startsWith( "oracle." ) ) - { + if (name.startsWith("com.")) { + final String sub = name.substring("com.".length()); + if (sub.startsWith("oracle.")) { return true; } - if ( sub.startsWith( "sun." ) ) - { - final String subSun = sub.substring( "sun.".length() ); - if ( subSun.startsWith( "accessibility." ) ) - { + if (sub.startsWith("sun.")) { + final String subSun = sub.substring("sun.".length()); + if (subSun.startsWith("accessibility.")) { return true; } - if ( subSun.startsWith( "activation." ) ) - { + if (subSun.startsWith("activation.")) { return true; } - if ( subSun.startsWith( "awt." ) ) - { + if (subSun.startsWith("awt.")) { return true; } - if ( subSun.startsWith( "beans." ) ) - { + if (subSun.startsWith("beans.")) { return true; } - if ( subSun.startsWith( "corba.se." ) ) - { + if (subSun.startsWith("corba.se.")) { return true; } - if ( subSun.startsWith( "demo.jvmti." ) ) - { + if (subSun.startsWith("demo.jvmti.")) { return true; } - if ( subSun.startsWith( "image.codec.jpeg." ) ) - { + if (subSun.startsWith("image.codec.jpeg.")) { return true; } - if ( subSun.startsWith( "imageio." ) ) - { + if (subSun.startsWith("imageio.")) { return true; } - if ( subSun.startsWith( "istack.internal." ) ) - { + if (subSun.startsWith("istack.internal.")) { return true; } - if ( subSun.startsWith( "java." ) ) - { + if (subSun.startsWith("java.")) { return true; } - if ( subSun.startsWith( "java_cup." ) ) - { + if (subSun.startsWith("java_cup.")) { return true; } - if ( subSun.startsWith( "jmx." ) ) - { + if (subSun.startsWith("jmx.")) { return true; } - if ( subSun.startsWith( "jndi." ) ) - { + if (subSun.startsWith("jndi.")) { return true; } - if ( subSun.startsWith( "management." ) ) - { + if (subSun.startsWith("management.")) { return true; } - if ( subSun.startsWith( "media.sound." ) ) - { + if (subSun.startsWith("media.sound.")) { return true; } - if ( subSun.startsWith( "naming.internal." ) ) - { + if (subSun.startsWith("naming.internal.")) { return true; } - if ( subSun.startsWith( "net." ) ) - { + if (subSun.startsWith("net.")) { return true; } - if ( subSun.startsWith( "nio." ) ) - { + if (subSun.startsWith("nio.")) { return true; } - if ( subSun.startsWith( "org." ) ) - { + if (subSun.startsWith("org.")) { return true; } - if ( subSun.startsWith( "rmi.rmid." ) ) - { + if (subSun.startsWith("rmi.rmid.")) { return true; } - if ( subSun.startsWith( "rowset." ) ) - { + if (subSun.startsWith("rowset.")) { return true; } - if ( subSun.startsWith( "security." ) ) - { + if (subSun.startsWith("security.")) { return true; } - if ( subSun.startsWith( "swing." ) ) - { + if (subSun.startsWith("swing.")) { return true; } - if ( subSun.startsWith( "tracing." ) ) - { + if (subSun.startsWith("tracing.")) { return true; } - if ( subSun.startsWith( "xml.internal." ) ) - { + if (subSun.startsWith("xml.internal.")) { return true; } return false; @@ -500,24 +398,19 @@ private boolean isDirectJvmClass(final String name) { return false; } - private class FilteringUrlEnum implements Enumeration - { + private class FilteringUrlEnum implements Enumeration { private final Enumeration delegate; private URL next; - private FilteringUrlEnum( Enumeration delegate ) - { + private FilteringUrlEnum(Enumeration delegate) { this.delegate = delegate; } @Override - public boolean hasMoreElements() - { - while (delegate.hasMoreElements()) - { + public boolean hasMoreElements() { + while (delegate.hasMoreElements()) { next = delegate.nextElement(); - if (isInJvm(next)) - { + if (isInJvm(next)) { return true; } } @@ -525,29 +418,23 @@ public boolean hasMoreElements() } @Override - public URL nextElement() - { + public URL nextElement() { return next; } } - private static class ChainedEnumerations implements Enumeration - { + private static class ChainedEnumerations implements Enumeration { private final Iterator> enumerations; private Enumeration current; - private ChainedEnumerations( Iterator> enumerations ) - { + private ChainedEnumerations(Iterator> enumerations) { this.enumerations = enumerations; } @Override - public boolean hasMoreElements() - { - if (current == null || !current.hasMoreElements()) - { - if (!enumerations.hasNext()) - { + public boolean hasMoreElements() { + if (current == null || !current.hasMoreElements()) { + if (!enumerations.hasNext()) { return false; } current = enumerations.next(); @@ -556,8 +443,7 @@ public boolean hasMoreElements() } @Override - public URL nextElement() - { + public URL nextElement() { return current.nextElement(); } } diff --git a/src/test/java/org/codehaus/mojo/exec/DummyMain.java b/src/test/java/org/codehaus/mojo/exec/DummyMain.java index 591efa16..7619d34c 100644 --- a/src/test/java/org/codehaus/mojo/exec/DummyMain.java +++ b/src/test/java/org/codehaus/mojo/exec/DummyMain.java @@ -2,26 +2,23 @@ /** * Simple class with a main method to call from unit tests - * + * * @author Jerome Lacoste * @version $Id$ */ -public class DummyMain -{ +public class DummyMain { /** * Prints Hello followed by each argument, then a new line. Use a space character as separator. - * + * * @param args the arguments */ - public static void main( String... args ) - { - StringBuilder buffer = new StringBuilder( "Hello" ); + public static void main(String... args) { + StringBuilder buffer = new StringBuilder("Hello"); - for ( String arg : args ) - { - buffer.append( System.getProperty( "line.separator" ) ).append( arg ); + for (String arg : args) { + buffer.append(System.getProperty("line.separator")).append(arg); } - System.out.println( buffer.toString() ); + System.out.println(buffer.toString()); } } diff --git a/src/test/java/org/codehaus/mojo/exec/ExecJavaMojoTest.java b/src/test/java/org/codehaus/mojo/exec/ExecJavaMojoTest.java index f177dd2e..28daf2c9 100644 --- a/src/test/java/org/codehaus/mojo/exec/ExecJavaMojoTest.java +++ b/src/test/java/org/codehaus/mojo/exec/ExecJavaMojoTest.java @@ -15,9 +15,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -39,20 +36,21 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * @author Jerome Lacoste * @version $Id$ */ -public class ExecJavaMojoTest - extends AbstractMojoTestCase -{ +public class ExecJavaMojoTest extends AbstractMojoTestCase { @Mock private MavenSession session; - - private static final File LOCAL_REPO = new File( "src/test/repository" ); + + private static final File LOCAL_REPO = new File("src/test/repository"); private static final int JAVA_VERSION_MAJOR = - Integer.parseInt( System.getProperty( "java.version" ).replaceFirst( "[.].*", "" ) ); + Integer.parseInt(System.getProperty("java.version").replaceFirst("[.].*", "")); /* * This one won't work yet public void xxtestSimpleRunPropertiesAndArguments() throws MojoExecutionException, @@ -63,37 +61,33 @@ public class ExecJavaMojoTest /** * Check that a simple execution with no arguments and no system properties produces the expected result.
* We load the config from a pom file and fill up the MavenProject property ourselves - * + * * @throws Exception if any exception occurs */ - public void testSimpleRun() - throws Exception - { - File pom = new File( getBasedir(), "src/test/projects/project4/pom.xml" ); + public void testSimpleRun() throws Exception { + File pom = new File(getBasedir(), "src/test/projects/project4/pom.xml"); - String output = execute( pom, "java" ); + String output = execute(pom, "java"); - assertEquals( "Hello" + System.getProperty( "line.separator" ), output ); + assertEquals("Hello" + System.getProperty("line.separator"), output); } /** * MEXEC-10 Check that an execution with no arguments and an system property with no value produces the expected * result
* We load the config from a pom file and fill up the MavenProject property ourselves - * + * * @throws Exception if any exception occurs */ - public void testEmptySystemProperty() - throws Exception - { - File pom = new File( getBasedir(), "src/test/projects/project5/pom.xml" ); + public void testEmptySystemProperty() throws Exception { + File pom = new File(getBasedir(), "src/test/projects/project5/pom.xml"); - assertNull( "System property not yet created", System.getProperty( "test.name" ) ); + assertNull("System property not yet created", System.getProperty("test.name")); - assertEquals( "Hello " + System.lineSeparator(), execute( pom, "java" ) ); + assertEquals("Hello " + System.lineSeparator(), execute(pom, "java")); // ensure we get back in the original state and didn't leak the execution config - assertNull( "System property not yet created", System.getProperty( "test.name" ) ); + assertNull("System property not yet created", System.getProperty("test.name")); } /** @@ -103,25 +97,20 @@ public void testEmptySystemProperty() * @author Lukasz Cwik * @throws Exception if any exception occurs */ - public void testRunWhichThrowsExceptionIsNotWrappedInInvocationTargetException() - throws Exception - { - File pom = new File( getBasedir(), "src/test/projects/project15/pom.xml" ); + public void testRunWhichThrowsExceptionIsNotWrappedInInvocationTargetException() throws Exception { + File pom = new File(getBasedir(), "src/test/projects/project15/pom.xml"); - try - { - execute( pom, "java" ); + try { + execute(pom, "java"); - fail( "Expected Exception to be thrown but none was thrown" ); - } - catch ( Throwable e ) - { - assertTrue( e instanceof MojoExecutionException ); + fail("Expected Exception to be thrown but none was thrown"); + } catch (Throwable e) { + assertTrue(e instanceof MojoExecutionException); - assertTrue( e.getCause() instanceof IOException ); + assertTrue(e.getCause() instanceof IOException); - assertEquals( "expected IOException thrown by test", e.getCause().getMessage() ); - } + assertEquals("expected IOException thrown by test", e.getCause().getMessage()); + } } /** @@ -170,34 +159,30 @@ public void testRunWhichThrowsExceptionIsNotWrappedInInvocationTargetException() /** * For cases where the Java code spawns Threads and main returns soon. See * MEXEC-6. - * + * * @throws Exception if any exception occurs */ - public void testWaitNoDaemonThreads() - throws Exception - { - File pom = new File( getBasedir(), "src/test/projects/project7/pom.xml" ); + public void testWaitNoDaemonThreads() throws Exception { + File pom = new File(getBasedir(), "src/test/projects/project7/pom.xml"); - String output = execute( pom, "java" ); + String output = execute(pom, "java"); - assertEquals( MainWithThreads.ALL_EXITED, output.trim() ); + assertEquals(MainWithThreads.ALL_EXITED, output.trim()); } /** * For cases where the Java code spawns Threads and main returns soon, but code contains non interruptible threads. * User is required to timeout the execution, otherwise it will hang. See * MEXEC-15. - * + * * @throws Exception if any exception occurs */ - public void testWaitNonInterruptibleDaemonThreads() - throws Exception - { - File pom = new File( getBasedir(), "src/test/projects/project9/pom.xml" ); + public void testWaitNonInterruptibleDaemonThreads() throws Exception { + File pom = new File(getBasedir(), "src/test/projects/project9/pom.xml"); - String output = execute( pom, "java" ); + String output = execute(pom, "java"); - assertEquals( MainWithThreads.TIMER_IGNORED, output.trim() ); + assertEquals(MainWithThreads.TIMER_IGNORED, output.trim()); } /** @@ -205,12 +190,10 @@ public void testWaitNonInterruptibleDaemonThreads() * GitHub-391. *

* FIXME: This sometimes fails with {@code unit.framework.ComparisonFailure: expected:<...>; but was:<...3(f)>}. - * + * * @throws Exception if any exception occurs */ - public void testUncooperativeThread() - throws Exception - { + public void testUncooperativeThread() throws Exception { // FIXME: // This will fail the test, because Assume is a JUnit 4 thing, but we are running in JUnit 3 mode, because // AbstractMojoTestCase extends PlexusTestCase extends TestCase. The latter is a JUnit 3 compatibility class. @@ -219,17 +202,14 @@ public void testUncooperativeThread() // versions. In JUnit 5, we could even conveniently use @EnabledOnJre. // Assume.assumeTrue( JAVA_VERSION_MAJOR < 20 ); - File pom = new File( getBasedir(), "src/test/projects/project10/pom.xml" ); - String output = execute( pom, "java" ); + File pom = new File(getBasedir(), "src/test/projects/project10/pom.xml"); + String output = execute(pom, "java"); // note: execute() will wait a little bit before returning the output, // thereby allowing the stop()'ed thread to output the final "(f)". - if ( JAVA_VERSION_MAJOR < 20 ) - { - assertEquals( MainUncooperative.SUCCESS, output.trim() ); - } - else - { - assertEquals( MainUncooperative.INTERRUPTED_BUT_NOT_STOPPED, output.trim() ); + if (JAVA_VERSION_MAJOR < 20) { + assertEquals(MainUncooperative.SUCCESS, output.trim()); + } else { + assertEquals(MainUncooperative.INTERRUPTED_BUT_NOT_STOPPED, output.trim()); } } @@ -250,49 +230,42 @@ public void testUncooperativeThread() * Test the commandline parsing facilities of the {@link AbstractExecMojo} class * @throws Exception if any exception occurs */ - public void testRunWithArgs() - throws Exception - { + public void testRunWithArgs() throws Exception { - String resultString = execute( new File( getBasedir(), "src/test/projects/project8/pom.xml" ), "java" ); + String resultString = execute(new File(getBasedir(), "src/test/projects/project8/pom.xml"), "java"); - String LS = System.getProperty( "line.separator" ); + String LS = System.getProperty("line.separator"); String expectedResult = "Hello" + LS + "Arg1" + LS + "Arg2a Arg2b" + LS; - assertEquals( expectedResult, resultString ); + assertEquals(expectedResult, resultString); } /** * Ensures that classpath can be filtered (exclude from plugin deps or project deps) to resolve conflicts. * @throws Exception if something unexpected occurs. */ - public void testExcludedClasspathElement() throws Exception - { - String LS = System.getProperty( "line.separator" ); + public void testExcludedClasspathElement() throws Exception { + String LS = System.getProperty("line.separator"); // slf4j-simple { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - execute( - new File( getBasedir(), "src/test/projects/project16/pom.xml" ), "java", - stdout, stderr); - assertEquals( "org.slf4j.impl.SimpleLogger", stdout.toString().trim() ); + execute(new File(getBasedir(), "src/test/projects/project16/pom.xml"), "java", stdout, stderr); + assertEquals("org.slf4j.impl.SimpleLogger", stdout.toString().trim()); assertEquals( "[org.codehaus.mojo.exec.Slf4jMain.main()] INFO org.codehaus.mojo.exec.Slf4jMain - hello[]" + LS, - stderr.toString() ); + stderr.toString()); } // slf4j-jdk14 { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); - execute( - new File( getBasedir(), "src/test/projects/project17/pom.xml" ), "java", - stdout, stderr); - assertEquals( "org.slf4j.impl.JDK14LoggerAdapter", stdout.toString().trim() ); + execute(new File(getBasedir(), "src/test/projects/project17/pom.xml"), "java", stdout, stderr); + assertEquals("org.slf4j.impl.JDK14LoggerAdapter", stdout.toString().trim()); final String stderrString = stderr.toString(); // simpler check, just validate it is not simple output - assertTrue( stderrString.contains( " org.codehaus.mojo.exec.Slf4jMain main" ) ); - assertTrue( stderrString.contains( ": hello[]" ) ); + assertTrue(stderrString.contains(" org.codehaus.mojo.exec.Slf4jMain main")); + assertTrue(stderrString.contains(": hello[]")); } } @@ -301,87 +274,77 @@ public void testExcludedClasspathElement() throws Exception * * @throws Exception if any exception occurs */ - public void testProjectProperties() - throws Exception - { - File pom = new File( getBasedir(), "src/test/projects/project18/pom.xml" ); + public void testProjectProperties() throws Exception { + File pom = new File(getBasedir(), "src/test/projects/project18/pom.xml"); - String output = execute( pom, "java" ); + String output = execute(pom, "java"); - assertEquals( "Hello project18 project" + System.lineSeparator(), output ); + assertEquals("Hello project18 project" + System.lineSeparator(), output); } /** * @return output from System.out during mojo execution */ - private String execute( File pom, String goal ) - throws Exception - { - return execute( pom, goal, new ByteArrayOutputStream(), new ByteArrayOutputStream() ); + private String execute(File pom, String goal) throws Exception { + return execute(pom, goal, new ByteArrayOutputStream(), new ByteArrayOutputStream()); } /** * @return output from System.out during mojo execution */ - private String execute( File pom, String goal, ByteArrayOutputStream stringOutputStream, OutputStream stderr ) - throws Exception - { + private String execute(File pom, String goal, ByteArrayOutputStream stringOutputStream, OutputStream stderr) + throws Exception { ExecJavaMojo mojo; - mojo = (ExecJavaMojo) lookupMojo( goal, pom ); + mojo = (ExecJavaMojo) lookupMojo(goal, pom); - setUpProject( pom, mojo ); + setUpProject(pom, mojo); - MavenProject project = (MavenProject) getVariableValueFromObject( mojo, "project" ); + MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project"); // why isn't this set up by the harness based on the default-value? TODO get to bottom of this! - setVariableValueToObject( mojo, "includeProjectDependencies", Boolean.TRUE ); - setVariableValueToObject( mojo, "cleanupDaemonThreads", Boolean.TRUE ); - setVariableValueToObject( mojo, "classpathScope", "compile" ); + setVariableValueToObject(mojo, "includeProjectDependencies", Boolean.TRUE); + setVariableValueToObject(mojo, "cleanupDaemonThreads", Boolean.TRUE); + setVariableValueToObject(mojo, "classpathScope", "compile"); - assertNotNull( mojo ); - assertNotNull( project ); + assertNotNull(mojo); + assertNotNull(project); // trap System.out PrintStream out = System.out; PrintStream err = System.err; - System.setOut( new PrintStream( stringOutputStream ) ); - System.setErr( new PrintStream( stderr ) ); + System.setOut(new PrintStream(stringOutputStream)); + System.setErr(new PrintStream(stderr)); // ensure we don't log unnecessary stuff which would interfere with assessing success of tests - mojo.setLog( new DefaultLog( new ConsoleLogger( Logger.LEVEL_ERROR, "exec:java" ) ) ); + mojo.setLog(new DefaultLog(new ConsoleLogger(Logger.LEVEL_ERROR, "exec:java"))); - try - { + try { mojo.execute(); - } - finally - { + } finally { // see testUncooperativeThread() for explaination - Thread.sleep( 300 ); // time seems about right - System.setOut( out ); - System.setErr( err ); + Thread.sleep(300); // time seems about right + System.setOut(out); + System.setErr(err); } return stringOutputStream.toString(); } - private void setUpProject( File pomFile, AbstractMojo mojo ) - throws Exception - { + private void setUpProject(File pomFile, AbstractMojo mojo) throws Exception { super.setUp(); - - MockitoAnnotations.initMocks( this ); - - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + + MockitoAnnotations.initMocks(this); + + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); RepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - - ProjectBuilder builder = lookup( ProjectBuilder.class ); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + + ProjectBuilder builder = lookup(ProjectBuilder.class); - MavenProject project = builder.build( pomFile, buildingRequest ).getProject(); + MavenProject project = builder.build(pomFile, buildingRequest).getProject(); // this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test - project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() ); - setVariableValueToObject( mojo, "project", project ); + project.getBuild().setOutputDirectory(new File("target/test-classes").getAbsolutePath()); + setVariableValueToObject(mojo, "project", project); } } diff --git a/src/test/java/org/codehaus/mojo/exec/ExecMojoTest.java b/src/test/java/org/codehaus/mojo/exec/ExecMojoTest.java index 2231c7db..4e4bcbde 100644 --- a/src/test/java/org/codehaus/mojo/exec/ExecMojoTest.java +++ b/src/test/java/org/codehaus/mojo/exec/ExecMojoTest.java @@ -1,7 +1,5 @@ package org.codehaus.mojo.exec; -import static java.util.Collections.emptyMap; - /* * Copyright 2005 The Codehaus. Licensed 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 @@ -31,29 +29,27 @@ import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.mockito.Mock; +import static java.util.Collections.emptyMap; + /** * @author Jerome Lacoste * @version $Id$ */ -public class ExecMojoTest - extends AbstractMojoTestCase -{ +public class ExecMojoTest extends AbstractMojoTestCase { @Mock private MavenSession session; - - private static final File LOCAL_REPO = new File( "src/test/repository" ); - + + private static final File LOCAL_REPO = new File("src/test/repository"); + /* * Finding a file actually on disk of the test system makes some of the tests fail. - * Hence a purely random UUID is used to prevent this situation. + * Hence a purely random UUID is used to prevent this situation. */ private static final String SOME_EXECUTABLE = UUID.randomUUID().toString(); private MockExecMojo mojo; - static class MockExecMojo - extends ExecMojo - { + static class MockExecMojo extends ExecMojo { public int executeResult; public List commandLines = new ArrayList(); @@ -62,53 +58,44 @@ static class MockExecMojo public Map systemProperties = new HashMap(); - protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, OutputStream out, - OutputStream err ) - throws IOException, ExecuteException - { - commandLines.add( commandLine ); - if ( failureMsg != null ) - { - throw new ExecuteException( failureMsg, executeResult ); + protected int executeCommandLine( + Executor exec, CommandLine commandLine, Map enviro, OutputStream out, OutputStream err) + throws IOException, ExecuteException { + commandLines.add(commandLine); + if (failureMsg != null) { + throw new ExecuteException(failureMsg, executeResult); } return executeResult; } - protected String getSystemProperty( String key ) - { - return systemProperties.get( key ); + protected String getSystemProperty(String key) { + return systemProperties.get(key); } - int getAmountExecutedCommandLines() - { + int getAmountExecutedCommandLines() { return commandLines.size(); } - CommandLine getExecutedCommandline( int index ) - { - return commandLines.get( index ); + CommandLine getExecutedCommandline(int index) { + return commandLines.get(index); } } - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); mojo = new MockExecMojo(); // note: most of the tests below assume that the specified // executable path is not fully specicied. See ExecMojo#getExecutablePath - mojo.setExecutable( SOME_EXECUTABLE ); - mojo.setArguments( Arrays.asList( new String[] { "--version" } ) ); + mojo.setExecutable(SOME_EXECUTABLE); + mojo.setArguments(Arrays.asList(new String[] {"--version"})); mojo.executeResult = 0; - mojo.setBasedir( File.createTempFile( "mvn-temp", "txt" ).getParentFile() ); + mojo.setBasedir(File.createTempFile("mvn-temp", "txt").getParentFile()); } - public void testRunOK() - throws MojoExecutionException - { + public void testRunOK() throws MojoExecutionException { mojo.execute(); - checkMojo( SOME_EXECUTABLE + " --version" ); + checkMojo(SOME_EXECUTABLE + " --version"); } /* @@ -124,232 +111,205 @@ public void testRunOK() * generate a file whose contains are compared to expected output */ - // MEXEC-12, MEXEC-72 - public void testGetExecutablePath() - throws IOException - { + public void testGetExecutablePath() throws IOException { ExecMojo realMojo = new ExecMojo(); - File workdir = new File( System.getProperty( "user.dir" ) ); + File workdir = new File(System.getProperty("user.dir")); Map enviro = new HashMap(); String myJavaPath = "target" + File.separator + "javax"; - File f = new File( myJavaPath ); - assertTrue( "file created...", f.createNewFile() ); - assertTrue( "file exists...", f.exists() ); + File f = new File(myJavaPath); + assertTrue("file created...", f.createNewFile()); + assertTrue("file exists...", f.exists()); - realMojo.setExecutable( myJavaPath ); + realMojo.setExecutable(myJavaPath); - CommandLine cmd = realMojo.getExecutablePath( enviro, workdir ); - assertTrue( "File exists so path is absolute", - cmd.getExecutable().startsWith( System.getProperty( "user.dir" ) ) ); + CommandLine cmd = realMojo.getExecutablePath(enviro, workdir); + assertTrue("File exists so path is absolute", cmd.getExecutable().startsWith(System.getProperty("user.dir"))); f.delete(); - assertFalse( "file deleted...", f.exists() ); - cmd = realMojo.getExecutablePath( enviro, workdir ); - assertEquals( "File doesn't exist. Let the system find it (in that PATH?)", myJavaPath, cmd.getExecutable() ); + assertFalse("file deleted...", f.exists()); + cmd = realMojo.getExecutablePath(enviro, workdir); + assertEquals("File doesn't exist. Let the system find it (in that PATH?)", myJavaPath, cmd.getExecutable()); - if ( OS.isFamilyWindows() ) // Exec Maven Plugin only supports Batch detection and PATH search on Windows + if (OS.isFamilyWindows()) // Exec Maven Plugin only supports Batch detection and PATH search on Windows { myJavaPath = "target" + File.separator + "javax.bat"; - f = new File( myJavaPath ); - assertTrue( "file created...", f.createNewFile() ); - assertTrue( "file exists...", f.exists() ); - - final String comSpec = System.getenv( "ComSpec" ); - - realMojo.setExecutable( "javax.bat" ); - cmd = realMojo.getExecutablePath( enviro, workdir ); - assertTrue( "is bat file on windows, execute using ComSpec.", cmd.getExecutable().equals( comSpec ) ); - - enviro.put( "PATH", workdir.getAbsolutePath() + File.separator + "target" ); - cmd = realMojo.getExecutablePath( enviro, workdir ); - assertTrue( "is bat file on windows' PATH, execute using ComSpec.", cmd.getExecutable().equals( comSpec ) ); + f = new File(myJavaPath); + assertTrue("file created...", f.createNewFile()); + assertTrue("file exists...", f.exists()); + + final String comSpec = System.getenv("ComSpec"); + + realMojo.setExecutable("javax.bat"); + cmd = realMojo.getExecutablePath(enviro, workdir); + assertTrue( + "is bat file on windows, execute using ComSpec.", + cmd.getExecutable().equals(comSpec)); + + enviro.put("PATH", workdir.getAbsolutePath() + File.separator + "target"); + cmd = realMojo.getExecutablePath(enviro, workdir); + assertTrue( + "is bat file on windows' PATH, execute using ComSpec.", + cmd.getExecutable().equals(comSpec)); f.delete(); - assertFalse( "file deleted...", f.exists() ); + assertFalse("file deleted...", f.exists()); } } - + // under Windows cmd/bat files should be preferred over files with the same prefix without extension, e.g. // if there are "node" and "node.cmd" the mojo should pick "node.cmd" // see https://github.com/mojohaus/exec-maven-plugin/issues/42 - public void testGetExecutablePathPreferExecutableExtensionsOnWindows() - throws IOException - { - // this test is for Windows - if (!OS.isFamilyWindows()) { - return; - } - final ExecMojo realMojo = new ExecMojo(); - - final String tmp = System.getProperty("java.io.tmpdir"); - final File workdir = new File(tmp, "testGetExecutablePathPreferExecutableExtensionsOnWindows"); - workdir.mkdirs(); - - final Map enviro = new HashMap(); - - final File f = new File(workdir, "mycmd"); - final File fCmd = new File(workdir, "mycmd.cmd"); - f.createNewFile(); - fCmd.createNewFile(); - assertTrue( "file exists...", f.exists() ); - assertTrue( "file exists...", fCmd.exists() ); - - realMojo.setExecutable( "mycmd" ); - - final CommandLine cmd = realMojo.getExecutablePath( enviro, workdir ); - // cmdline argumets are: [/c, %path-to-temp%\mycmd.cmd], so check second argument - assertTrue( "File should have cmd extension", - cmd.getArguments()[1].endsWith( "mycmd.cmd" ) ); - - f.delete(); - fCmd.delete(); - assertFalse( "file deleted...", f.exists() ); - assertFalse( "file deleted...", fCmd.exists() ); - + public void testGetExecutablePathPreferExecutableExtensionsOnWindows() throws IOException { + // this test is for Windows + if (!OS.isFamilyWindows()) { + return; + } + final ExecMojo realMojo = new ExecMojo(); + + final String tmp = System.getProperty("java.io.tmpdir"); + final File workdir = new File(tmp, "testGetExecutablePathPreferExecutableExtensionsOnWindows"); + workdir.mkdirs(); + + final Map enviro = new HashMap(); + + final File f = new File(workdir, "mycmd"); + final File fCmd = new File(workdir, "mycmd.cmd"); + f.createNewFile(); + fCmd.createNewFile(); + assertTrue("file exists...", f.exists()); + assertTrue("file exists...", fCmd.exists()); + + realMojo.setExecutable("mycmd"); + + final CommandLine cmd = realMojo.getExecutablePath(enviro, workdir); + // cmdline argumets are: [/c, %path-to-temp%\mycmd.cmd], so check second argument + assertTrue("File should have cmd extension", cmd.getArguments()[1].endsWith("mycmd.cmd")); + + f.delete(); + fCmd.delete(); + assertFalse("file deleted...", f.exists()); + assertFalse("file deleted...", fCmd.exists()); } - public void testRunFailure() - { + public void testRunFailure() { mojo.executeResult = 1; - try - { + try { mojo.execute(); - fail( "expected failure" ); - } - catch ( MojoExecutionException e ) - { - assertEquals( "Result of " + mojo.getExecutedCommandline( 0 ) + " execution is: '1'.", e.getMessage() ); + fail("expected failure"); + } catch (MojoExecutionException e) { + assertEquals("Result of " + mojo.getExecutedCommandline(0) + " execution is: '1'.", e.getMessage()); } - checkMojo( SOME_EXECUTABLE + " --version" ); + checkMojo(SOME_EXECUTABLE + " --version"); } - public void testRunError() - { + public void testRunError() { mojo.failureMsg = "simulated failure"; - try - { + try { mojo.execute(); - fail( "expected failure" ); - } - catch ( MojoExecutionException e ) - { - assertEquals( "Command execution failed.", e.getMessage() ); + fail("expected failure"); + } catch (MojoExecutionException e) { + assertEquals("Command execution failed.", e.getMessage()); } - checkMojo( SOME_EXECUTABLE + " --version" ); + checkMojo(SOME_EXECUTABLE + " --version"); } - public void testOverrides() - throws MojoExecutionException - { - mojo.systemProperties.put( "exec.args", "-f pom.xml" ); + public void testOverrides() throws MojoExecutionException { + mojo.systemProperties.put("exec.args", "-f pom.xml"); mojo.execute(); - checkMojo( SOME_EXECUTABLE + " -f pom.xml" ); + checkMojo(SOME_EXECUTABLE + " -f pom.xml"); } - public void testOverrides3() - throws MojoExecutionException - { - mojo.systemProperties.put( "exec.args", null ); + public void testOverrides3() throws MojoExecutionException { + mojo.systemProperties.put("exec.args", null); mojo.execute(); - checkMojo( SOME_EXECUTABLE + " --version" ); + checkMojo(SOME_EXECUTABLE + " --version"); mojo.commandLines.clear(); - mojo.systemProperties.put( "exec.args", "" ); + mojo.systemProperties.put("exec.args", ""); mojo.execute(); - checkMojo( SOME_EXECUTABLE + " --version" ); + checkMojo(SOME_EXECUTABLE + " --version"); } - public void testIsResultCodeAFailure() - { + public void testIsResultCodeAFailure() { ExecMojo execMojo = new ExecMojo(); - assertTrue( execMojo.isResultCodeAFailure( 1 ) ); - assertFalse( execMojo.isResultCodeAFailure( 0 ) ); - - execMojo.setSuccessCodes( new Integer[0] ); - assertTrue( execMojo.isResultCodeAFailure( 1 ) ); - assertFalse( execMojo.isResultCodeAFailure( 0 ) ); - - execMojo.setSuccessCodes( new Integer[] { Integer.valueOf( "2" ), Integer.valueOf( "5" ) } ); - assertTrue( execMojo.isResultCodeAFailure( 0 ) ); - assertTrue( execMojo.isResultCodeAFailure( 10 ) ); - assertFalse( execMojo.isResultCodeAFailure( 2 ) ); - assertFalse( execMojo.isResultCodeAFailure( 5 ) ); + assertTrue(execMojo.isResultCodeAFailure(1)); + assertFalse(execMojo.isResultCodeAFailure(0)); + + execMojo.setSuccessCodes(new Integer[0]); + assertTrue(execMojo.isResultCodeAFailure(1)); + assertFalse(execMojo.isResultCodeAFailure(0)); + + execMojo.setSuccessCodes(new Integer[] {Integer.valueOf("2"), Integer.valueOf("5")}); + assertTrue(execMojo.isResultCodeAFailure(0)); + assertTrue(execMojo.isResultCodeAFailure(10)); + assertFalse(execMojo.isResultCodeAFailure(2)); + assertFalse(execMojo.isResultCodeAFailure(5)); } // MEXEC-81 - public void testParseCommandlineOSWin() - throws Exception - { + public void testParseCommandlineOSWin() throws Exception { ExecMojo execMojo = new ExecMojo(); final String javaHome = "C:\\Java\\jdk1.5.0_15"; // can only be set by expression or plugin-configuration - setVariableValueToObject( execMojo, "commandlineArgs", javaHome ); + setVariableValueToObject(execMojo, "commandlineArgs", javaHome); String[] args = execMojo.parseCommandlineArgs(); - assertEquals( javaHome, args[0] ); + assertEquals(javaHome, args[0]); } - - public void test_exec_receives_all_parameters() throws MojoExecutionException - { + public void test_exec_receives_all_parameters() throws MojoExecutionException { // given ExecMojo execMojo = new ExecMojo(); - execMojo.setExecutable( "mkdir" ); - execMojo.setArguments( Arrays.asList( "-p", "dist/mails" ) ); - execMojo.setBasedir( new File("target") ); + execMojo.setExecutable("mkdir"); + execMojo.setArguments(Arrays.asList("-p", "dist/mails")); + execMojo.setBasedir(new File("target")); // when - final CommandLine commandLine = execMojo.getExecutablePath( emptyMap(), new File( "target" ) ); + final CommandLine commandLine = execMojo.getExecutablePath(emptyMap(), new File("target")); execMojo.execute(); // then - assertTrue( "dir should have been created", - Paths.get( "target", "dist", "mails" ).toFile().exists() ); + assertTrue( + "dir should have been created", + Paths.get("target", "dist", "mails").toFile().exists()); } - private void checkMojo( String expectedCommandLine ) - { - assertEquals( 1, mojo.getAmountExecutedCommandLines() ); - CommandLine commandline = mojo.getExecutedCommandline( 0 ); + private void checkMojo(String expectedCommandLine) { + assertEquals(1, mojo.getAmountExecutedCommandLines()); + CommandLine commandline = mojo.getExecutedCommandline(0); // do NOT depend on Commandline toString() - assertEquals( expectedCommandLine, getCommandLineAsString( commandline ) ); + assertEquals(expectedCommandLine, getCommandLineAsString(commandline)); } - private String getCommandLineAsString( CommandLine commandline ) - { + private String getCommandLineAsString(CommandLine commandline) { // for the sake of the test comparisons, cut out the eventual // cmd /c *.bat conversion String result = commandline.getExecutable(); boolean isCmd = false; - if ( OS.isFamilyWindows() && result.equals( "cmd" ) ) - { + if (OS.isFamilyWindows() && result.equals("cmd")) { result = ""; isCmd = true; } String[] arguments = commandline.getArguments(); - for ( int i = 0; i < arguments.length; i++ ) - { + for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; - if ( isCmd && i == 0 && "/c".equals( arg ) ) - { + if (isCmd && i == 0 && "/c".equals(arg)) { continue; } - if ( isCmd && i == 1 && arg.endsWith( ".bat" ) ) - { - arg = arg.substring( 0, arg.length() - ".bat".length() ); + if (isCmd && i == 1 && arg.endsWith(".bat")) { + arg = arg.substring(0, arg.length() - ".bat".length()); } - result += ( result.length() == 0 ? "" : " " ) + arg; + result += (result.length() == 0 ? "" : " ") + arg; } return result; } - } diff --git a/src/test/java/org/codehaus/mojo/exec/FindClassInClasspath.java b/src/test/java/org/codehaus/mojo/exec/FindClassInClasspath.java index 2c4915f9..f4f09612 100644 --- a/src/test/java/org/codehaus/mojo/exec/FindClassInClasspath.java +++ b/src/test/java/org/codehaus/mojo/exec/FindClassInClasspath.java @@ -3,36 +3,28 @@ /** * @author Jerome Lacoste */ -public class FindClassInClasspath -{ +public class FindClassInClasspath { public static final String FOUND_ALL = "OK"; /** * @param args the names of classes to search in the classpath prints 'OK' if all classes found **/ - public static void main( String... args ) - { - for ( String arg : args ) - { - if ( !isClassInClasspath( arg ) ) - { - System.out.println( "ERROR: class + " + arg + " not found in classpath" ); - System.exit( 1 ); + public static void main(String... args) { + for (String arg : args) { + if (!isClassInClasspath(arg)) { + System.out.println("ERROR: class + " + arg + " not found in classpath"); + System.exit(1); } } - System.out.println( FOUND_ALL ); + System.out.println(FOUND_ALL); } - private static boolean isClassInClasspath( String className ) - { - try - { - Class.forName( className ); + private static boolean isClassInClasspath(String className) { + try { + Class.forName(className); return true; - } - catch ( Exception e ) - { - System.out.println( "ERROR: " + e.getMessage() ); + } catch (Exception e) { + System.out.println("ERROR: " + e.getMessage()); return false; } } diff --git a/src/test/java/org/codehaus/mojo/exec/HelloSystemProperty.java b/src/test/java/org/codehaus/mojo/exec/HelloSystemProperty.java index 603ad753..ffc14140 100644 --- a/src/test/java/org/codehaus/mojo/exec/HelloSystemProperty.java +++ b/src/test/java/org/codehaus/mojo/exec/HelloSystemProperty.java @@ -3,16 +3,14 @@ /** * Simple class with a main method reading a system property */ -public class HelloSystemProperty -{ +public class HelloSystemProperty { /** * Print on stdout hello and the system property test.name value. - * + * * @param args the arguments */ - public static void main( String... args ) - { + public static void main(String... args) { // important: do not default on empty due to testEmptySystemProperty() - System.out.println( "Hello " + System.getProperty( "test.name" ) ); + System.out.println("Hello " + System.getProperty("test.name")); } } diff --git a/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java b/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java index f1da2c63..32d07f84 100644 --- a/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java +++ b/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java @@ -1,14 +1,14 @@ package org.codehaus.mojo.exec; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Test; - import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.function.Function; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Test; + public class LineRedirectOutputStreamTest { @Test @@ -26,7 +26,9 @@ public void givenExtendedUnicodeCharacterOutput_whenRedirectingWithIso8859Charse @Test public void givenExtendedUnicodeCharacterOutput_whenRedirectingWithCp1252_thenShouldDecodeProperly() throws IOException { - Assume.assumeTrue("The JVM does not contain the cp-1252 charset", Charset.availableCharsets().containsKey("windows-1252")); + Assume.assumeTrue( + "The JVM does not contain the cp-1252 charset", + Charset.availableCharsets().containsKey("windows-1252")); internalTestForCharset(Charset.forName("windows-1252")); } @@ -56,8 +58,9 @@ private void internalTestForCharset(Charset charset) throws IOException { internalTestForCharset(sb -> new LineRedirectOutputStream(sb::append, charset), charset); } - private void internalTestForCharset(Function lineRedirectOutputStream, - Charset charset) throws IOException { + private void internalTestForCharset( + Function lineRedirectOutputStream, Charset charset) + throws IOException { StringBuilder sb = new StringBuilder(); String firstLine = "Hello, 你好, नमस्ते, مرحبا, γεια σας, שלום, こんにちは, 안녕하세요!"; String secondLine = "🌍 Welcome to the world! 🌟✨🎉🔥"; diff --git a/src/test/java/org/codehaus/mojo/exec/MainUncooperative.java b/src/test/java/org/codehaus/mojo/exec/MainUncooperative.java index 956328d0..4a80f23a 100644 --- a/src/test/java/org/codehaus/mojo/exec/MainUncooperative.java +++ b/src/test/java/org/codehaus/mojo/exec/MainUncooperative.java @@ -4,59 +4,46 @@ * Created by IntelliJ IDEA. User: dsmiley Date: Jan 19, 2007 Time: 4:43:19 PM To change this template use File | * Settings | File Templates. */ -public class MainUncooperative - extends Thread -{ +public class MainUncooperative extends Thread { public static final String SUCCESS = "1(interrupted)(f)2(f)"; // In JDK 20+, Thread::stop has been removed and just throws an UnsupportedOperationException public static final String INTERRUPTED_BUT_NOT_STOPPED = "1(interrupted)(f)2"; - public static void main( String... args ) - throws InterruptedException - { + public static void main(String... args) throws InterruptedException { Thread daemonThread = new MainUncooperative(); - daemonThread.setDaemon( true ); + daemonThread.setDaemon(true); daemonThread.start(); - Thread.sleep( 1000 ); + Thread.sleep(1000); // returns to caller now } - final long SIMWORKTIME = 15 * 1000;// 15 seconds of work which is going to be more than exec:java wants to wait + final long SIMWORKTIME = 15 * 1000; // 15 seconds of work which is going to be more than exec:java wants to wait - public void run() - { + public void run() { boolean interruptedOnce = false; long startedTime = System.currentTimeMillis(); - for ( int lap = 1; true; lap++ ) - { - long remainingWork = SIMWORKTIME - ( System.currentTimeMillis() - startedTime ); - if ( remainingWork <= 0 ) - { - break;// done + for (int lap = 1; true; lap++) { + long remainingWork = SIMWORKTIME - (System.currentTimeMillis() - startedTime); + if (remainingWork <= 0) { + break; // done } - try - { - System.out.print( lap ); - Thread.sleep( remainingWork );// simulates doing work - System.out.print( "(done)" ); + try { + System.out.print(lap); + Thread.sleep(remainingWork); // simulates doing work + System.out.print("(done)"); break; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // We want to ensure this only gets reported once. It's possible depending on a race condition for // ExecJavaMojo.terminateThreads() to interrupt this thread a second time. - if ( !interruptedOnce ) - { - System.out.print( "(interrupted)" ); + if (!interruptedOnce) { + System.out.print("(interrupted)"); } interruptedOnce = true; // be uncooperative; don't quit and don't set interrupted status - } - finally - { - System.out.print( "(f)" );// we should see this if Thread.stop() is called + } finally { + System.out.print("(f)"); // we should see this if Thread.stop() is called } } } diff --git a/src/test/java/org/codehaus/mojo/exec/MainWithThreads.java b/src/test/java/org/codehaus/mojo/exec/MainWithThreads.java index fc6585fa..62fb768e 100644 --- a/src/test/java/org/codehaus/mojo/exec/MainWithThreads.java +++ b/src/test/java/org/codehaus/mojo/exec/MainWithThreads.java @@ -6,9 +6,7 @@ /** * @author David Smiley */ -public class MainWithThreads - extends Thread -{ +public class MainWithThreads extends Thread { public static final String ALL_EXITED = "t1(interrupted td)(cancelled timer)"; public static final String TIMER_IGNORED = "t1(interrupted td)"; @@ -18,40 +16,35 @@ public class MainWithThreads * will be interrupted right away. - if the timer is cancelled (using 'cancelTimer' as argument), the timer will die * on itself after all the other threads - if not, one must use a time out to stop joining on that unresponsive * daemon thread - * + * * @param args the arguments **/ - public static void main( String... args ) - { + public static void main(String... args) { // long run so that we interrupt it before it ends itself - Thread responsiveDaemonThread = new MainWithThreads( 60000, "td" ); - responsiveDaemonThread.setDaemon( true ); + Thread responsiveDaemonThread = new MainWithThreads(60000, "td"); + responsiveDaemonThread.setDaemon(true); responsiveDaemonThread.start(); - new MainWithThreads( 200, "t1" ).start(); + new MainWithThreads(200, "t1").start(); // Timer in Java <= 6 aren't interruptible - final Timer t = new Timer( true ); + final Timer t = new Timer(true); - if ( optionsContains( args, "cancelTimer" ) ) - { - t.schedule( new TimerTask() - { - public void run() - { - System.out.print( "(cancelled timer)" ); - t.cancel(); - } - }, 400 ); + if (optionsContains(args, "cancelTimer")) { + t.schedule( + new TimerTask() { + public void run() { + System.out.print("(cancelled timer)"); + t.cancel(); + } + }, + 400); } } - private static boolean optionsContains( String[] args, String option ) - { - for ( String arg : args ) - { - if ( arg.equals( option ) ) - { + private static boolean optionsContains(String[] args, String option) { + for (String arg : args) { + if (arg.equals(option)) { return true; } } @@ -62,23 +55,19 @@ private static boolean optionsContains( String[] args, String option ) private String message; - public MainWithThreads( int millisecsToSleep, String message ) - { + public MainWithThreads(int millisecsToSleep, String message) { this.millisecsToSleep = millisecsToSleep; this.message = message; } - public void run() - { - try - { - Thread.sleep( millisecsToSleep ); - } - catch ( InterruptedException e ) // IE's are a way to cancel a thread + public void run() { + try { + Thread.sleep(millisecsToSleep); + } catch (InterruptedException e) // IE's are a way to cancel a thread { - System.out.print( "(interrupted " + message + ")" ); + System.out.print("(interrupted " + message + ")"); return; } - System.out.print( message ); + System.out.print(message); } } diff --git a/src/test/java/org/codehaus/mojo/exec/NoMain.java b/src/test/java/org/codehaus/mojo/exec/NoMain.java index dc694298..9635eec7 100644 --- a/src/test/java/org/codehaus/mojo/exec/NoMain.java +++ b/src/test/java/org/codehaus/mojo/exec/NoMain.java @@ -20,12 +20,7 @@ * @author Jerome Lacoste * @version $Id$ */ -public class NoMain -{ +public class NoMain { // MEXEC-29 wrong interface for main method causes NPE - public static void main() - throws Exception - { - - } + public static void main() throws Exception {} } diff --git a/src/test/java/org/codehaus/mojo/exec/Slf4jMain.java b/src/test/java/org/codehaus/mojo/exec/Slf4jMain.java index 142580b8..64a92f4e 100644 --- a/src/test/java/org/codehaus/mojo/exec/Slf4jMain.java +++ b/src/test/java/org/codehaus/mojo/exec/Slf4jMain.java @@ -8,18 +8,16 @@ /** * Simple class with a main method to call from unit tests */ -public class Slf4jMain -{ +public class Slf4jMain { /** * Print on stdout the logger class (slf4j binding) and then * logs at info level args with Hello as suffix. - * + * * @param args the arguments */ - public static void main( String... args ) - { - final Logger logger = LoggerFactory.getLogger( Slf4jMain.class ); - System.out.println( logger.getClass().getName() ); - logger.info( "hello" + asList( args ) ); + public static void main(String... args) { + final Logger logger = LoggerFactory.getLogger(Slf4jMain.class); + System.out.println(logger.getClass().getName()); + logger.info("hello" + asList(args)); } } diff --git a/src/test/java/org/codehaus/mojo/exec/ThrowingMain.java b/src/test/java/org/codehaus/mojo/exec/ThrowingMain.java index 04d91371..6e91f156 100644 --- a/src/test/java/org/codehaus/mojo/exec/ThrowingMain.java +++ b/src/test/java/org/codehaus/mojo/exec/ThrowingMain.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.codehaus.mojo.exec; import java.io.IOException; @@ -23,12 +22,8 @@ * * @author Lukasz Cwik */ -public class ThrowingMain -{ - public static void main( String... args ) - throws Exception - { - throw new IOException( "expected IOException thrown by test" ); +public class ThrowingMain { + public static void main(String... args) throws Exception { + throw new IOException("expected IOException thrown by test"); } } - diff --git a/src/test/java/org/codehaus/mojo/exec/URLClassLoaderBuilderTest.java b/src/test/java/org/codehaus/mojo/exec/URLClassLoaderBuilderTest.java index ff0898b8..946c6c05 100644 --- a/src/test/java/org/codehaus/mojo/exec/URLClassLoaderBuilderTest.java +++ b/src/test/java/org/codehaus/mojo/exec/URLClassLoaderBuilderTest.java @@ -19,49 +19,43 @@ * under the License. */ -import org.junit.Test; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; +import org.junit.Test; + import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; /** * Basic tests about the custom classloader we set to execute the project. */ -public class URLClassLoaderBuilderTest -{ +public class URLClassLoaderBuilderTest { @Test - public void childFirst() throws Exception - { + public void childFirst() throws Exception { ByteArrayOutputStream stderr = new ByteArrayOutputStream(); PrintStream originalStderr = System.err; Thread thread = Thread.currentThread(); ClassLoader testLoader = thread.getContextClassLoader(); - try ( URLClassLoader loader = URLClassLoaderBuilder.builder() - .setPaths( asList( - Paths.get( "target/test-dependencies/slf4j-api.jar" ), - Paths.get( "target/test-dependencies/slf4j-jdk14.jar" ) - ) ) - .build(); - PrintStream tmpStderr = new PrintStream( stderr ) ) - { - System.setErr( tmpStderr ); - assertEquals( tmpStderr, System.err ); - thread.setContextClassLoader( loader ); - Class lf = loader.loadClass( "org.slf4j.LoggerFactory" ); - Object logger = lf.getMethod( "getLogger", Class.class ).invoke( null, String.class ); - assertEquals( "org.slf4j.impl.JDK14LoggerAdapter", logger.getClass().getName() ); - } - finally - { - thread.setContextClassLoader( testLoader ); + try (URLClassLoader loader = URLClassLoaderBuilder.builder() + .setPaths(asList( + Paths.get("target/test-dependencies/slf4j-api.jar"), + Paths.get("target/test-dependencies/slf4j-jdk14.jar"))) + .build(); + PrintStream tmpStderr = new PrintStream(stderr)) { + System.setErr(tmpStderr); + assertEquals(tmpStderr, System.err); + thread.setContextClassLoader(loader); + Class lf = loader.loadClass("org.slf4j.LoggerFactory"); + Object logger = lf.getMethod("getLogger", Class.class).invoke(null, String.class); + assertEquals("org.slf4j.impl.JDK14LoggerAdapter", logger.getClass().getName()); + } finally { + thread.setContextClassLoader(testLoader); } - assertEquals("", new String( stderr.toByteArray(), StandardCharsets.UTF_8 ) ); - System.setErr( originalStderr ); + assertEquals("", new String(stderr.toByteArray(), StandardCharsets.UTF_8)); + System.setErr(originalStderr); } } diff --git a/src/test/java/org/codehaus/plexus/util/interpolation/Interpolator.java b/src/test/java/org/codehaus/plexus/util/interpolation/Interpolator.java index 4f6c9d02..1c54fd73 100644 --- a/src/test/java/org/codehaus/plexus/util/interpolation/Interpolator.java +++ b/src/test/java/org/codehaus/plexus/util/interpolation/Interpolator.java @@ -3,12 +3,9 @@ /** * COPIED FROM plexus-utils-1.5.15 TO SATISFY TESTS Interpolator interface. Based on existing RegexBasedInterpolator * interface. - * + * * @author cstamas * @deprecated Use plexus-interpolation APIs instead. * @version $Id$ */ -public interface Interpolator - extends org.codehaus.plexus.interpolation.Interpolator -{ -} +public interface Interpolator extends org.codehaus.plexus.interpolation.Interpolator {} diff --git a/src/test/java/org/codehaus/plexus/util/interpolation/RegexBasedInterpolator.java b/src/test/java/org/codehaus/plexus/util/interpolation/RegexBasedInterpolator.java index 4622be30..4c151c8a 100644 --- a/src/test/java/org/codehaus/plexus/util/interpolation/RegexBasedInterpolator.java +++ b/src/test/java/org/codehaus/plexus/util/interpolation/RegexBasedInterpolator.java @@ -4,41 +4,33 @@ /** * COPIED FROM plexus-utils-1.5.15 TO SATISFY TESTS - * + * * @version $Id$ * @deprecated Use plexus-interpolation APIs instead. */ -public class RegexBasedInterpolator - extends org.codehaus.plexus.interpolation.RegexBasedInterpolator - implements Interpolator -{ - public RegexBasedInterpolator() - { +public class RegexBasedInterpolator extends org.codehaus.plexus.interpolation.RegexBasedInterpolator + implements Interpolator { + public RegexBasedInterpolator() { super(); } - public RegexBasedInterpolator( List valueSources ) - { - super( valueSources ); + public RegexBasedInterpolator(List valueSources) { + super(valueSources); } - public RegexBasedInterpolator( String startRegex, String endRegex, List valueSources ) - { - super( startRegex, endRegex, valueSources ); + public RegexBasedInterpolator(String startRegex, String endRegex, List valueSources) { + super(startRegex, endRegex, valueSources); } - public RegexBasedInterpolator( String startRegex, String endRegex ) - { - super( startRegex, endRegex ); + public RegexBasedInterpolator(String startRegex, String endRegex) { + super(startRegex, endRegex); } - public void addValueSource( ValueSource valueSource ) - { - super.addValueSource( valueSource ); + public void addValueSource(ValueSource valueSource) { + super.addValueSource(valueSource); } - public void removeValuesSource( ValueSource valueSource ) - { - super.removeValuesSource( valueSource ); + public void removeValuesSource(ValueSource valueSource) { + super.removeValuesSource(valueSource); } } diff --git a/src/test/java/org/codehaus/plexus/util/interpolation/ValueSource.java b/src/test/java/org/codehaus/plexus/util/interpolation/ValueSource.java index a68a2680..d7cf5e5e 100644 --- a/src/test/java/org/codehaus/plexus/util/interpolation/ValueSource.java +++ b/src/test/java/org/codehaus/plexus/util/interpolation/ValueSource.java @@ -2,13 +2,9 @@ /** * COPIED FROM plexus-utils-1.5.15 TO SATISFY TESTS - * + * * @author jdcasey * @deprecated Use plexus-interpolation APIs instead. * @version $Id$ */ -public interface ValueSource - extends org.codehaus.plexus.interpolation.ValueSource -{ - -} +public interface ValueSource extends org.codehaus.plexus.interpolation.ValueSource {}