You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by ol...@apache.org on 2022/12/15 00:52:24 UTC
[maven-invoker-plugin] branch master updated: upgrade to parent 39 (#157)
This is an automated email from the ASF dual-hosted git repository.
olamy pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-invoker-plugin.git
The following commit(s) were added to refs/heads/master by this push:
new 6ed7f00 upgrade to parent 39 (#157)
6ed7f00 is described below
commit 6ed7f00e123397185d87e88b15baf6f312d7d005
Author: Olivier Lamy <ol...@apache.org>
AuthorDate: Thu Dec 15 10:52:20 2022 +1000
upgrade to parent 39 (#157)
Signed-off-by: Olivier Lamy <ol...@apache.org>
Signed-off-by: Olivier Lamy <ol...@apache.org>
---
pom.xml | 32 +-
.../maven/plugins/invoker/AbstractInvokerMojo.java | 1953 ++++++++------------
.../apache/maven/plugins/invoker/CompositeMap.java | 128 +-
.../apache/maven/plugins/invoker/FileLogger.java | 36 +-
.../apache/maven/plugins/invoker/InstallMojo.java | 467 ++---
.../maven/plugins/invoker/IntegrationTestMojo.java | 33 +-
.../apache/maven/plugins/invoker/InvokerMojo.java | 60 +-
.../maven/plugins/invoker/InvokerProperties.java | 408 ++--
.../maven/plugins/invoker/InvokerReport.java | 242 ++-
.../maven/plugins/invoker/InvokerSession.java | 236 ++-
.../maven/plugins/invoker/InvokerToolchain.java | 35 +-
.../apache/maven/plugins/invoker/JobExecutor.java | 78 +-
.../maven/plugins/invoker/MetadataUtils.java | 155 +-
.../org/apache/maven/plugins/invoker/PomUtils.java | 43 +-
.../apache/maven/plugins/invoker/ReportUtils.java | 40 +-
.../maven/plugins/invoker/RunFailureException.java | 40 +-
.../org/apache/maven/plugins/invoker/Selector.java | 70 +-
.../maven/plugins/invoker/SelectorUtils.java | 243 +--
.../plugins/invoker/SystemPropertyPrinter.java | 30 +-
.../apache/maven/plugins/invoker/VerifyMojo.java | 102 +-
.../plugins/invoker/ExtendedMavenProjectStub.java | 38 +-
.../maven/plugins/invoker/InterpolationTest.java | 104 +-
.../maven/plugins/invoker/InvokerMojoTest.java | 169 +-
.../plugins/invoker/InvokerPropertiesTest.java | 699 ++++---
.../maven/plugins/invoker/InvokerSessionTest.java | 55 +-
.../maven/plugins/invoker/JobExecutorTest.java | 147 +-
.../apache/maven/plugins/invoker/SelectorTest.java | 80 +-
.../maven/plugins/invoker/SelectorUtilsTest.java | 183 +-
28 files changed, 2742 insertions(+), 3164 deletions(-)
diff --git a/pom.xml b/pom.xml
index 1a30a4b..de951bb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,5 +1,4 @@
-<?xml version='1.0' encoding='UTF-8'?>
-
+<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@@ -18,14 +17,13 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
- <artifactId>maven-plugins</artifactId>
<groupId>org.apache.maven.plugins</groupId>
- <version>37</version>
+ <artifactId>maven-plugins</artifactId>
+ <version>39</version>
<relativePath />
</parent>
@@ -34,10 +32,8 @@ under the License.
<packaging>maven-plugin</packaging>
<name>Apache Maven Invoker Plugin</name>
- <description>
- The Maven Invoker Plugin is used to run a set of Maven projects. The plugin can determine whether each project
- execution is successful, and optionally can verify the output generated from a given project execution.
- </description>
+ <description>The Maven Invoker Plugin is used to run a set of Maven projects. The plugin can determine whether each project
+ execution is successful, and optionally can verify the output generated from a given project execution.</description>
<prerequisites>
<maven>${mavenVersion}</maven>
@@ -46,8 +42,8 @@ under the License.
<scm>
<connection>scm:git:https://gitbox.apache.org/repos/asf/maven-invoker-plugin.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/maven-invoker-plugin.git</developerConnection>
- <url>https://github.com/apache/maven-invoker-plugin/tree/${project.scm.tag}</url>
<tag>HEAD</tag>
+ <url>https://github.com/apache/maven-invoker-plugin/tree/${project.scm.tag}</url>
</scm>
<issueManagement>
<system>jira</system>
@@ -268,8 +264,8 @@ under the License.
<scope>test</scope>
<exclusions>
<exclusion>
- <artifactId>plexus-container-default</artifactId>
<groupId>org.codehaus.plexus</groupId>
+ <artifactId>plexus-container-default</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -330,6 +326,12 @@ under the License.
<plugin>
<groupId>org.codehaus.modello</groupId>
<artifactId>modello-maven-plugin</artifactId>
+ <configuration>
+ <models>
+ <model>src/main/mdo/invocation.mdo</model>
+ </models>
+ <version>1.0.0</version>
+ </configuration>
<executions>
<execution>
<id>standard</id>
@@ -344,18 +346,12 @@ under the License.
</execution>
<execution>
<id>site-docs</id>
- <phase>pre-site</phase>
<goals>
<goal>xdoc</goal>
</goals>
+ <phase>pre-site</phase>
</execution>
</executions>
- <configuration>
- <models>
- <model>src/main/mdo/invocation.mdo</model>
- </models>
- <version>1.0.0</version>
- </configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
diff --git a/src/main/java/org/apache/maven/plugins/invoker/AbstractInvokerMojo.java b/src/main/java/org/apache/maven/plugins/invoker/AbstractInvokerMojo.java
index f8518c4..68d81bd 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/AbstractInvokerMojo.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/AbstractInvokerMojo.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -111,9 +129,7 @@ import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
* @author Stephen Connolly
* @since 15-Aug-2009 09:09:29
*/
-public abstract class AbstractInvokerMojo
- extends AbstractMojo
-{
+public abstract class AbstractInvokerMojo extends AbstractMojo {
/**
* The zero-based column index where to print the invoker result.
*/
@@ -124,7 +140,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.1
*/
- @Parameter( property = "invoker.skip", defaultValue = "false" )
+ @Parameter(property = "invoker.skip", defaultValue = "false")
private boolean skipInvocation;
/**
@@ -135,7 +151,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( defaultValue = "false" )
+ @Parameter(defaultValue = "false")
protected boolean suppressSummaries;
/**
@@ -143,7 +159,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.streamLogs", defaultValue = "false" )
+ @Parameter(property = "invoker.streamLogs", defaultValue = "false")
private boolean streamLogs;
/**
@@ -153,7 +169,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.localRepositoryPath", defaultValue = "${settings.localRepository}" )
+ @Parameter(property = "invoker.localRepositoryPath", defaultValue = "${settings.localRepository}")
private File localRepositoryPath;
/**
@@ -161,7 +177,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.projectsDirectory", defaultValue = "${basedir}/src/it/" )
+ @Parameter(property = "invoker.projectsDirectory", defaultValue = "${basedir}/src/it/")
private File projectsDirectory;
/**
@@ -171,7 +187,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.4
*/
- @Parameter( property = "invoker.reportsDirectory", defaultValue = "${project.build.directory}/invoker-reports" )
+ @Parameter(property = "invoker.reportsDirectory", defaultValue = "${project.build.directory}/invoker-reports")
private File reportsDirectory;
/**
@@ -179,7 +195,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.4
*/
- @Parameter( property = "invoker.disableReports", defaultValue = "false" )
+ @Parameter(property = "invoker.disableReports", defaultValue = "false")
private boolean disableReports;
/**
@@ -191,7 +207,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.1
*/
- @Parameter( property = "invoker.cloneProjectsTo" )
+ @Parameter(property = "invoker.cloneProjectsTo")
private File cloneProjectsTo;
// CHECKSTYLE_OFF: LineLength
@@ -205,7 +221,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.2
*/
- @Parameter( defaultValue = "false" )
+ @Parameter(defaultValue = "false")
private boolean cloneAllFiles;
// CHECKSTYLE_ON: LineLength
@@ -214,7 +230,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.6
*/
- @Parameter( defaultValue = "true" )
+ @Parameter(defaultValue = "true")
private boolean cloneClean;
/**
@@ -222,7 +238,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.pom" )
+ @Parameter(property = "invoker.pom")
private File pom;
/**
@@ -238,7 +254,7 @@ public abstract class AbstractInvokerMojo
* @since 1.0
*/
@Parameter
- private List<String> pomIncludes = Collections.singletonList( "*/pom.xml" );
+ private List<String> pomIncludes = Collections.singletonList("*/pom.xml");
/**
* Exclude patterns for searching the integration test directory. This parameter is meant to be set from the POM. By
@@ -260,7 +276,7 @@ public abstract class AbstractInvokerMojo
* @since 1.3
*/
@Parameter
- private List<String> setupIncludes = Collections.singletonList( "setup*/pom.xml" );
+ private List<String> setupIncludes = Collections.singletonList("setup*/pom.xml");
/**
* The list of goals to execute on each project. Default value is: <code>package</code>.
@@ -268,7 +284,7 @@ public abstract class AbstractInvokerMojo
* @since 1.0
*/
@Parameter
- private List<String> goals = Collections.singletonList( "package" );
+ private List<String> goals = Collections.singletonList("package");
/**
* Relative path of a selector script to run prior in order to decide if the build should be executed. This script
@@ -282,7 +298,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.5
*/
- @Parameter( property = "invoker.selectorScript", defaultValue = "selector" )
+ @Parameter(property = "invoker.selectorScript", defaultValue = "selector")
private String selectorScript;
/**
@@ -295,7 +311,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.preBuildHookScript", defaultValue = "prebuild" )
+ @Parameter(property = "invoker.preBuildHookScript", defaultValue = "prebuild")
private String preBuildHookScript;
/**
@@ -307,7 +323,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.postBuildHookScript", defaultValue = "postbuild" )
+ @Parameter(property = "invoker.postBuildHookScript", defaultValue = "postbuild")
private String postBuildHookScript;
/**
@@ -315,7 +331,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.testPropertiesFile", defaultValue = "test.properties" )
+ @Parameter(property = "invoker.testPropertiesFile", defaultValue = "test.properties")
private String testPropertiesFile;
/**
@@ -331,7 +347,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.showErrors", defaultValue = "false" )
+ @Parameter(property = "invoker.showErrors", defaultValue = "false")
private boolean showErrors;
/**
@@ -339,7 +355,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.debug", defaultValue = "false" )
+ @Parameter(property = "invoker.debug", defaultValue = "false")
private boolean debug;
/**
@@ -347,7 +363,7 @@ public abstract class AbstractInvokerMojo
*
* @since 3.3.0
*/
- @Parameter( property = "invoker.quiet", defaultValue = "false" )
+ @Parameter(property = "invoker.quiet", defaultValue = "false")
private boolean quiet;
/**
@@ -355,7 +371,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.0
*/
- @Parameter( property = "invoker.noLog", defaultValue = "false" )
+ @Parameter(property = "invoker.noLog", defaultValue = "false")
private boolean noLog;
/**
@@ -394,7 +410,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.1 (exclusion since 1.8)
*/
- @Parameter( property = "invoker.test" )
+ @Parameter(property = "invoker.test")
private String invokerTest;
/**
@@ -404,7 +420,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.2
*/
- @Parameter( property = "invoker.settingsFile" )
+ @Parameter(property = "invoker.settingsFile")
private File settingsFile;
/**
@@ -413,7 +429,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.2
*/
- @Parameter( property = "invoker.mavenOpts" )
+ @Parameter(property = "invoker.mavenOpts")
private String mavenOpts;
/**
@@ -422,7 +438,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.3
*/
- @Parameter( property = "invoker.mavenHome" )
+ @Parameter(property = "invoker.mavenHome")
private File mavenHome;
/**
@@ -431,7 +447,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.8
*/
- @Parameter( property = "invoker.mavenExecutable" )
+ @Parameter(property = "invoker.mavenExecutable")
private File mavenExecutable;
/**
@@ -440,7 +456,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.3
*/
- @Parameter( property = "invoker.javaHome" )
+ @Parameter(property = "invoker.javaHome")
private File javaHome;
/**
@@ -448,7 +464,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.2
*/
- @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" )
+ @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}")
private String encoding;
/**
@@ -460,7 +476,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.2
*/
- @Parameter( property = "invoker.addTestClassPath", defaultValue = "false" )
+ @Parameter(property = "invoker.addTestClassPath", defaultValue = "false")
private boolean addTestClassPath;
/**
@@ -604,7 +620,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.2
*/
- @Parameter( property = "invoker.invokerPropertiesFile", defaultValue = "invoker.properties" )
+ @Parameter(property = "invoker.invokerPropertiesFile", defaultValue = "invoker.properties")
private String invokerPropertiesFile;
/**
@@ -612,7 +628,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.4
*/
- @Parameter( property = "invoker.showVersion", defaultValue = "false" )
+ @Parameter(property = "invoker.showVersion", defaultValue = "false")
private boolean showVersion;
/**
@@ -624,7 +640,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.6
*/
- @Parameter( property = "invoker.parallelThreads", defaultValue = "1" )
+ @Parameter(property = "invoker.parallelThreads", defaultValue = "1")
private String parallelThreads;
/**
@@ -633,7 +649,7 @@ public abstract class AbstractInvokerMojo
*
* @since 1.6
*/
- @Parameter( property = "invoker.mergeUserSettings", defaultValue = "false" )
+ @Parameter(property = "invoker.mergeUserSettings", defaultValue = "false")
private boolean mergeUserSettings;
/**
@@ -656,30 +672,30 @@ public abstract class AbstractInvokerMojo
*
* @since 3.0.2
*/
- @Parameter( defaultValue = "0", property = "invoker.timeoutInSeconds" )
+ @Parameter(defaultValue = "0", property = "invoker.timeoutInSeconds")
private int timeoutInSeconds;
/**
* Write test result in junit format.
* @since 3.1.2
*/
- @Parameter( defaultValue = "false", property = "invoker.writeJunitReport" )
+ @Parameter(defaultValue = "false", property = "invoker.writeJunitReport")
private boolean writeJunitReport;
/**
* The package name use in junit report
* @since 3.1.2
*/
- @Parameter( defaultValue = "maven.invoker.it", property = "invoker.junitPackageName" )
+ @Parameter(defaultValue = "maven.invoker.it", property = "invoker.junitPackageName")
private String junitPackageName = "maven.invoker.it";
/**
* Only invoke maven projects if their sources have been modified since
* they were last built. Only works in conjunction with <code>cloneProjectsTo</code>.
-
+ *
* @since 3.2.2
*/
- @Parameter( defaultValue = "false", property = "invoker.updateOnly" )
+ @Parameter(defaultValue = "false", property = "invoker.updateOnly")
private boolean updateOnly = false;
/**
@@ -688,7 +704,7 @@ public abstract class AbstractInvokerMojo
*
* @since 3.4.0
*/
- @Parameter( defaultValue = "false", property = "invoker.updateSnapshots" )
+ @Parameter(defaultValue = "false", property = "invoker.updateSnapshots")
private boolean updateSnapshots;
// internal state variables
@@ -708,7 +724,7 @@ public abstract class AbstractInvokerMojo
/**
* The format for elapsed build time.
*/
- private final DecimalFormat secFormat = new DecimalFormat( "(0.0 s)", new DecimalFormatSymbols( Locale.ENGLISH ) );
+ private final DecimalFormat secFormat = new DecimalFormat("(0.0 s)", new DecimalFormatSymbols(Locale.ENGLISH));
/**
* The version of Maven which is used to run the builds
@@ -717,22 +733,22 @@ public abstract class AbstractInvokerMojo
// used components - readonly parameters
- @Parameter( property = "plugin.artifacts", required = true, readonly = true )
+ @Parameter(property = "plugin.artifacts", required = true, readonly = true)
private List<Artifact> pluginArtifacts;
- @Parameter( defaultValue = "${project.testClasspathElements}", readonly = true )
+ @Parameter(defaultValue = "${project.testClasspathElements}", readonly = true)
private List<String> testClassPath;
- @Parameter( defaultValue = "${mojoExecution}", readonly = true, required = true )
+ @Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true)
private MojoExecution mojoExecution;
- @Parameter( defaultValue = "${project}", readonly = true, required = true )
+ @Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
- @Parameter( defaultValue = "${session}", readonly = true, required = true )
+ @Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
- @Parameter( defaultValue = "${settings}", readonly = true, required = true )
+ @Parameter(defaultValue = "${settings}", readonly = true, required = true)
private Settings settings;
@Component
@@ -750,61 +766,49 @@ public abstract class AbstractInvokerMojo
* @throws org.apache.maven.plugin.MojoExecutionException If the goal encountered severe errors.
* @throws org.apache.maven.plugin.MojoFailureException If any of the Maven builds failed.
*/
- public void execute()
- throws MojoExecutionException, MojoFailureException
- {
- if ( skipInvocation )
- {
- getLog().info( "Skipping invocation per configuration."
- + " If this is incorrect, ensure the skipInvocation parameter is not set to true." );
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ if (skipInvocation) {
+ getLog().info("Skipping invocation per configuration."
+ + " If this is incorrect, ensure the skipInvocation parameter is not set to true.");
return;
}
- if ( StringUtils.isEmpty( encoding ) )
- {
- getLog().warn( "File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING
- + ", i.e. build is platform dependent!" );
+ if (StringUtils.isEmpty(encoding)) {
+ getLog().warn("File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING
+ + ", i.e. build is platform dependent!");
}
// done it here to prevent issues with concurrent access in case of parallel run
- if ( !disableReports )
- {
+ if (!disableReports) {
setupReportsFolder();
}
List<BuildJob> buildJobs;
- if ( pom == null )
- {
- try
- {
+ if (pom == null) {
+ try {
buildJobs = getBuildJobs();
- }
- catch ( final IOException e )
- {
- throw new MojoExecutionException( "Error retrieving POM list from includes, "
- + "excludes, and projects directory. Reason: " + e.getMessage(), e );
- }
- }
- else
- {
- try
- {
+ } catch (final IOException e) {
+ throw new MojoExecutionException(
+ "Error retrieving POM list from includes, " + "excludes, and projects directory. Reason: "
+ + e.getMessage(),
+ e);
+ }
+ } else {
+ try {
projectsDirectory = pom.getCanonicalFile().getParentFile();
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to discover projectsDirectory from "
- + "pom File parameter. Reason: " + e.getMessage(), e );
+ } catch (IOException e) {
+ throw new MojoExecutionException(
+ "Failed to discover projectsDirectory from " + "pom File parameter. Reason: " + e.getMessage(),
+ e);
}
- buildJobs = Collections.singletonList( new BuildJob( pom.getName() ) );
+ buildJobs = Collections.singletonList(new BuildJob(pom.getName()));
}
- if ( buildJobs.isEmpty() )
- {
+ if (buildJobs.isEmpty()) {
doFailIfNoProjects();
- getLog().info( "No projects were selected for execution." );
+ getLog().info("No projects were selected for execution.");
return;
}
@@ -813,98 +817,74 @@ public abstract class AbstractInvokerMojo
handleScriptRunnerWithScriptClassPath();
Collection<String> collectedProjects = new LinkedHashSet<>();
- for ( BuildJob buildJob : buildJobs )
- {
- collectProjects( projectsDirectory, buildJob.getProject(), collectedProjects, true );
+ for (BuildJob buildJob : buildJobs) {
+ collectProjects(projectsDirectory, buildJob.getProject(), collectedProjects, true);
}
File projectsDir = projectsDirectory;
- if ( cloneProjectsTo == null && "maven-plugin".equals( project.getPackaging() ) )
- {
- cloneProjectsTo = new File( project.getBuild().getDirectory(), "its" );
+ if (cloneProjectsTo == null && "maven-plugin".equals(project.getPackaging())) {
+ cloneProjectsTo = new File(project.getBuild().getDirectory(), "its");
}
- if ( updateOnly )
- {
- if ( cloneProjectsTo == null )
- {
- getLog().warn( "updateOnly functionality is not supported without cloning the projects" );
- }
- else if ( lastModifiedRecursive( projectsDirectory ) <= lastModifiedRecursive( cloneProjectsTo ) )
- {
- getLog().debug( "Skipping invocation as cloned projects are up-to-date "
- + "and updateOnly parameter is set to true." );
+ if (updateOnly) {
+ if (cloneProjectsTo == null) {
+ getLog().warn("updateOnly functionality is not supported without cloning the projects");
+ } else if (lastModifiedRecursive(projectsDirectory) <= lastModifiedRecursive(cloneProjectsTo)) {
+ getLog().debug("Skipping invocation as cloned projects are up-to-date "
+ + "and updateOnly parameter is set to true.");
return;
- }
- else
- {
- getLog().debug( "Cloned projects are out of date" );
+ } else {
+ getLog().debug("Cloned projects are out of date");
}
}
- if ( cloneProjectsTo != null )
- {
- cloneProjects( collectedProjects );
+ if (cloneProjectsTo != null) {
+ cloneProjects(collectedProjects);
projectsDir = cloneProjectsTo;
- }
- else
- {
- getLog().warn( "Filtering of parent/child POMs is not supported without cloning the projects" );
+ } else {
+ getLog().warn("Filtering of parent/child POMs is not supported without cloning the projects");
}
// First run setup jobs.
- List<BuildJob> setupBuildJobs = getSetupJobs( buildJobs );
+ List<BuildJob> setupBuildJobs = getSetupJobs(buildJobs);
- if ( !setupBuildJobs.isEmpty() )
- {
+ if (!setupBuildJobs.isEmpty()) {
// Run setup jobs in single thread mode.
//
// Jobs are ordered according to ordinal value from invoker.properties
- getLog().info( "Running " + setupBuildJobs.size() + " setup job"
- + ( ( setupBuildJobs.size() < 2 ) ? "" : "s" ) + ":" );
- runBuilds( projectsDir, setupBuildJobs, 1 );
- getLog().info( "Setup done." );
+ getLog().info("Running " + setupBuildJobs.size() + " setup job" + ((setupBuildJobs.size() < 2) ? "" : "s")
+ + ":");
+ runBuilds(projectsDir, setupBuildJobs, 1);
+ getLog().info("Setup done.");
}
+ List<BuildJob> nonSetupBuildJobs = getNonSetupJobs(buildJobs);
- List<BuildJob> nonSetupBuildJobs = getNonSetupJobs( buildJobs );
-
- if ( setupBuildJobs.isEmpty() || setupBuildJobs.stream().allMatch( BuildJob::isNotError ) )
- {
+ if (setupBuildJobs.isEmpty() || setupBuildJobs.stream().allMatch(BuildJob::isNotError)) {
// We will run the non setup jobs with the configured
// parallelThreads number.
- runBuilds( projectsDir, nonSetupBuildJobs, getParallelThreadsCount() );
- }
- else
- {
- for ( BuildJob buildJob : nonSetupBuildJobs )
- {
- buildJob.setResult( BuildJob.Result.SKIPPED );
- buildJob.setFailureMessage( "Skipped due to setup job(s) failure" );
- writeBuildReport( buildJob );
+ runBuilds(projectsDir, nonSetupBuildJobs, getParallelThreadsCount());
+ } else {
+ for (BuildJob buildJob : nonSetupBuildJobs) {
+ buildJob.setResult(BuildJob.Result.SKIPPED);
+ buildJob.setFailureMessage("Skipped due to setup job(s) failure");
+ writeBuildReport(buildJob);
}
}
- writeSummaryFile( buildJobs );
- processResults( new InvokerSession( buildJobs ) );
+ writeSummaryFile(buildJobs);
+ processResults(new InvokerSession(buildJobs));
}
- private void setupActualMavenVersion() throws MojoExecutionException
- {
- if ( mavenHome != null )
- {
- try
- {
- actualMavenVersion = SelectorUtils.getMavenVersion( mavenHome );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( e.getMessage(), e );
+ private void setupActualMavenVersion() throws MojoExecutionException {
+ if (mavenHome != null) {
+ try {
+ actualMavenVersion = SelectorUtils.getMavenVersion(mavenHome);
+ } catch (IOException e) {
+ throw new MojoExecutionException(e.getMessage(), e);
}
- }
- else
- {
+ } else {
actualMavenVersion = SelectorUtils.getMavenVersion();
}
}
@@ -915,17 +895,14 @@ public abstract class AbstractInvokerMojo
* @param file the root file to check.
* @return the latest lastModified time found.
*/
- private long lastModifiedRecursive( File file )
- {
+ private long lastModifiedRecursive(File file) {
long lastModified = file.lastModified();
final File[] entries = file.listFiles();
- if ( entries != null )
- {
- for ( File entry : entries )
- {
- lastModified = Math.max( lastModified, lastModifiedRecursive( entry ) );
+ if (entries != null) {
+ for (File entry : entries) {
+ lastModified = Math.max(lastModified, lastModifiedRecursive(entry));
}
}
@@ -937,102 +914,77 @@ public abstract class AbstractInvokerMojo
*
* @throws MojoExecutionException in case of failure during creation of the reports folder.
*/
- private void setupReportsFolder()
- throws MojoExecutionException
- {
+ private void setupReportsFolder() throws MojoExecutionException {
// If it exists from previous run...
- if ( reportsDirectory.exists() )
- {
- try
- {
- FileUtils.deleteDirectory( reportsDirectory );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failure while trying to delete "
- + reportsDirectory.getAbsolutePath(), e );
+ if (reportsDirectory.exists()) {
+ try {
+ FileUtils.deleteDirectory(reportsDirectory);
+ } catch (IOException e) {
+ throw new MojoExecutionException(
+ "Failure while trying to delete " + reportsDirectory.getAbsolutePath(), e);
}
}
- if ( !reportsDirectory.mkdirs() )
- {
- throw new MojoExecutionException( "Failure while creating the " + reportsDirectory.getAbsolutePath() );
+ if (!reportsDirectory.mkdirs()) {
+ throw new MojoExecutionException("Failure while creating the " + reportsDirectory.getAbsolutePath());
}
}
- private List<BuildJob> getSetupJobs( List<BuildJob> buildJobs )
- {
- return buildJobs.stream().
- filter( buildJob -> buildJob.getType().equals( BuildJob.Type.SETUP ) ).
- collect( Collectors.toList() );
+ private List<BuildJob> getSetupJobs(List<BuildJob> buildJobs) {
+ return buildJobs.stream()
+ .filter(buildJob -> buildJob.getType().equals(BuildJob.Type.SETUP))
+ .collect(Collectors.toList());
}
- private List<BuildJob> getNonSetupJobs( List<BuildJob> buildJobs )
- {
- return buildJobs.stream().
- filter( buildJob -> !buildJob.getType().equals( BuildJob.Type.SETUP ) ).
- collect( Collectors.toList() );
+ private List<BuildJob> getNonSetupJobs(List<BuildJob> buildJobs) {
+ return buildJobs.stream()
+ .filter(buildJob -> !buildJob.getType().equals(BuildJob.Type.SETUP))
+ .collect(Collectors.toList());
}
- private void handleScriptRunnerWithScriptClassPath()
- {
+ private void handleScriptRunnerWithScriptClassPath() {
final List<String> scriptClassPath;
- if ( addTestClassPath )
- {
- scriptClassPath = new ArrayList<>( testClassPath );
- for ( Artifact pluginArtifact : pluginArtifacts )
- {
- scriptClassPath.remove( pluginArtifact.getFile().getAbsolutePath() );
+ if (addTestClassPath) {
+ scriptClassPath = new ArrayList<>(testClassPath);
+ for (Artifact pluginArtifact : pluginArtifacts) {
+ scriptClassPath.remove(pluginArtifact.getFile().getAbsolutePath());
}
- }
- else
- {
+ } else {
scriptClassPath = null;
}
- scriptRunner = new ScriptRunner( );
- scriptRunner.setScriptEncoding( encoding );
- scriptRunner.setGlobalVariable( "localRepositoryPath", localRepositoryPath );
- scriptRunner.setGlobalVariable( "mavenVersion", actualMavenVersion );
- if ( scriptVariables != null )
- {
- scriptVariables.forEach( ( key, value ) -> scriptRunner.setGlobalVariable( key, value ) );
+ scriptRunner = new ScriptRunner();
+ scriptRunner.setScriptEncoding(encoding);
+ scriptRunner.setGlobalVariable("localRepositoryPath", localRepositoryPath);
+ scriptRunner.setGlobalVariable("mavenVersion", actualMavenVersion);
+ if (scriptVariables != null) {
+ scriptVariables.forEach((key, value) -> scriptRunner.setGlobalVariable(key, value));
}
- scriptRunner.setClassPath( scriptClassPath );
+ scriptRunner.setClassPath(scriptClassPath);
}
- private void writeSummaryFile( List<BuildJob> buildJobs )
- throws MojoExecutionException
- {
-
- File summaryReportFile = new File( reportsDirectory, "invoker-summary.txt" );
-
- try ( Writer writer = new BufferedWriter( new FileWriter( summaryReportFile ) ) )
- {
- for ( BuildJob buildJob : buildJobs )
- {
- if ( !BuildJob.Result.SUCCESS.equals( buildJob.getResult() ) )
- {
- writer.append( buildJob.getResult() );
- writer.append( " [" );
- writer.append( buildJob.getProject() );
- writer.append( "] " );
- if ( buildJob.getFailureMessage() != null )
- {
- writer.append( " " );
- writer.append( buildJob.getFailureMessage() );
+ private void writeSummaryFile(List<BuildJob> buildJobs) throws MojoExecutionException {
+
+ File summaryReportFile = new File(reportsDirectory, "invoker-summary.txt");
+
+ try (Writer writer = new BufferedWriter(new FileWriter(summaryReportFile))) {
+ for (BuildJob buildJob : buildJobs) {
+ if (!BuildJob.Result.SUCCESS.equals(buildJob.getResult())) {
+ writer.append(buildJob.getResult());
+ writer.append(" [");
+ writer.append(buildJob.getProject());
+ writer.append("] ");
+ if (buildJob.getFailureMessage() != null) {
+ writer.append(" ");
+ writer.append(buildJob.getFailureMessage());
}
- writer.append( "\n" );
+ writer.append("\n");
}
}
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to write summary report " + summaryReportFile, e );
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to write summary report " + summaryReportFile, e);
}
}
- protected void doFailIfNoProjects()
- throws MojoFailureException
- {
+ protected void doFailIfNoProjects() throws MojoFailureException {
// should only be used during run and verify
}
@@ -1043,8 +995,7 @@ public abstract class AbstractInvokerMojo
* @throws MojoFailureException If the mojo had failed as a result of invoking the build jobs.
* @since 1.4
*/
- abstract void processResults( InvokerSession invokerSession )
- throws MojoFailureException;
+ abstract void processResults(InvokerSession invokerSession) throws MojoFailureException;
/**
* Collects all projects locally reachable from the specified project. The method will as such try to read the POM
@@ -1060,74 +1011,59 @@ public abstract class AbstractInvokerMojo
* corresponding POM.
* @throws org.apache.maven.plugin.MojoExecutionException If the project tree could not be traversed.
*/
- private void collectProjects( File projectsDir, String projectPath, Collection<String> projectPaths,
- boolean included )
- throws MojoExecutionException
- {
- projectPath = projectPath.replace( '\\', '/' );
- File pomFile = new File( projectsDir, projectPath );
- if ( pomFile.isDirectory() )
- {
- pomFile = new File( pomFile, "pom.xml" );
- if ( !pomFile.exists() )
- {
- if ( included )
- {
- projectPaths.add( projectPath );
+ private void collectProjects(
+ File projectsDir, String projectPath, Collection<String> projectPaths, boolean included)
+ throws MojoExecutionException {
+ projectPath = projectPath.replace('\\', '/');
+ File pomFile = new File(projectsDir, projectPath);
+ if (pomFile.isDirectory()) {
+ pomFile = new File(pomFile, "pom.xml");
+ if (!pomFile.exists()) {
+ if (included) {
+ projectPaths.add(projectPath);
}
return;
}
- if ( !projectPath.endsWith( "/" ) )
- {
+ if (!projectPath.endsWith("/")) {
projectPath += '/';
}
projectPath += "pom.xml";
- }
- else if ( !pomFile.isFile() )
- {
+ } else if (!pomFile.isFile()) {
return;
}
- if ( !projectPaths.add( projectPath ) )
- {
+ if (!projectPaths.add(projectPath)) {
return;
}
- getLog().debug( "Collecting parent/child projects of " + projectPath );
+ getLog().debug("Collecting parent/child projects of " + projectPath);
- Model model = PomUtils.loadPom( pomFile );
+ Model model = PomUtils.loadPom(pomFile);
- try
- {
+ try {
String projectsRoot = projectsDir.getCanonicalPath();
String projectDir = pomFile.getParent();
String parentPath = "../pom.xml";
- if ( model.getParent() != null && StringUtils.isNotEmpty( model.getParent().getRelativePath() ) )
- {
+ if (model.getParent() != null
+ && StringUtils.isNotEmpty(model.getParent().getRelativePath())) {
parentPath = model.getParent().getRelativePath();
}
- String parent = relativizePath( new File( projectDir, parentPath ), projectsRoot );
- if ( parent != null )
- {
- collectProjects( projectsDir, parent, projectPaths, false );
+ String parent = relativizePath(new File(projectDir, parentPath), projectsRoot);
+ if (parent != null) {
+ collectProjects(projectsDir, parent, projectPaths, false);
}
- Collection<String> modulePaths = new LinkedHashSet<>( model.getModules() );
-
- model.getProfiles().forEach( profile -> modulePaths.addAll( profile.getModules() ) );
+ Collection<String> modulePaths = new LinkedHashSet<>(model.getModules());
+ model.getProfiles().forEach(profile -> modulePaths.addAll(profile.getModules()));
- for ( String modulePath : modulePaths )
- {
- String module = relativizePath( new File( projectDir, modulePath ), projectsRoot );
- if ( module != null )
- {
- collectProjects( projectsDir, module, projectPaths, false );
+ for (String modulePath : modulePaths) {
+ String module = relativizePath(new File(projectDir, modulePath), projectsRoot);
+ if (module != null) {
+ collectProjects(projectsDir, module, projectPaths, false);
}
}
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to analyze POM: " + pomFile, e );
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to analyze POM: " + pomFile, e);
}
}
@@ -1139,113 +1075,91 @@ public abstract class AbstractInvokerMojo
* <code>null</code> nor contain <code>null</code> elements.
* @throws org.apache.maven.plugin.MojoExecutionException If the the projects could not be copied/filtered.
*/
- private void cloneProjects( Collection<String> projectPaths )
- throws MojoExecutionException
- {
- if ( !cloneProjectsTo.mkdirs() && cloneClean )
- {
- try
- {
- FileUtils.cleanDirectory( cloneProjectsTo );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Could not clean the cloneProjectsTo directory. Reason: "
- + e.getMessage(), e );
+ private void cloneProjects(Collection<String> projectPaths) throws MojoExecutionException {
+ if (!cloneProjectsTo.mkdirs() && cloneClean) {
+ try {
+ FileUtils.cleanDirectory(cloneProjectsTo);
+ } catch (IOException e) {
+ throw new MojoExecutionException(
+ "Could not clean the cloneProjectsTo directory. Reason: " + e.getMessage(), e);
}
}
// determine project directories to clone
Collection<String> dirs = new LinkedHashSet<>();
- for ( String projectPath : projectPaths )
- {
- if ( !new File( projectsDirectory, projectPath ).isDirectory() )
- {
- projectPath = getParentPath( projectPath );
+ for (String projectPath : projectPaths) {
+ if (!new File(projectsDirectory, projectPath).isDirectory()) {
+ projectPath = getParentPath(projectPath);
}
- dirs.add( projectPath );
+ dirs.add(projectPath);
}
boolean filter;
// clone project directories
- try
- {
- filter = !cloneProjectsTo.getCanonicalFile().equals( projectsDirectory.getCanonicalFile() );
+ try {
+ filter = !cloneProjectsTo.getCanonicalFile().equals(projectsDirectory.getCanonicalFile());
List<String> clonedSubpaths = new ArrayList<>();
- for ( String subpath : dirs )
- {
+ for (String subpath : dirs) {
// skip this project if its parent directory is also scheduled for cloning
- if ( !".".equals( subpath ) && dirs.contains( getParentPath( subpath ) ) )
- {
+ if (!".".equals(subpath) && dirs.contains(getParentPath(subpath))) {
continue;
}
// avoid copying subdirs that are already cloned.
- if ( !alreadyCloned( subpath, clonedSubpaths ) )
- {
+ if (!alreadyCloned(subpath, clonedSubpaths)) {
// avoid creating new files that point to dir/.
- if ( ".".equals( subpath ) )
- {
- String cloneSubdir = relativizePath( cloneProjectsTo, projectsDirectory.getCanonicalPath() );
+ if (".".equals(subpath)) {
+ String cloneSubdir = relativizePath(cloneProjectsTo, projectsDirectory.getCanonicalPath());
// avoid infinite recursion if the cloneTo path is a subdirectory.
- if ( cloneSubdir != null )
- {
- File temp = Files.createTempDirectory( "pre-invocation-clone." ).toFile();
+ if (cloneSubdir != null) {
+ File temp = Files.createTempDirectory("pre-invocation-clone.")
+ .toFile();
- copyDirectoryStructure( projectsDirectory, temp );
+ copyDirectoryStructure(projectsDirectory, temp);
- FileUtils.deleteDirectory( new File( temp, cloneSubdir ) );
+ FileUtils.deleteDirectory(new File(temp, cloneSubdir));
- copyDirectoryStructure( temp, cloneProjectsTo );
- }
- else
- {
- copyDirectoryStructure( projectsDirectory, cloneProjectsTo );
+ copyDirectoryStructure(temp, cloneProjectsTo);
+ } else {
+ copyDirectoryStructure(projectsDirectory, cloneProjectsTo);
}
- }
- else
- {
- File srcDir = new File( projectsDirectory, subpath );
- File dstDir = new File( cloneProjectsTo, subpath );
- copyDirectoryStructure( srcDir, dstDir );
+ } else {
+ File srcDir = new File(projectsDirectory, subpath);
+ File dstDir = new File(cloneProjectsTo, subpath);
+ copyDirectoryStructure(srcDir, dstDir);
}
- clonedSubpaths.add( subpath );
+ clonedSubpaths.add(subpath);
}
}
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to clone projects from: " + projectsDirectory + " to: "
- + cloneProjectsTo + ". Reason: " + e.getMessage(), e );
+ } catch (IOException e) {
+ throw new MojoExecutionException(
+ "Failed to clone projects from: " + projectsDirectory + " to: " + cloneProjectsTo + ". Reason: "
+ + e.getMessage(),
+ e);
}
// filter cloned POMs
- if ( filter )
- {
- for ( String projectPath : projectPaths )
- {
- File pomFile = new File( cloneProjectsTo, projectPath );
- if ( pomFile.isFile() )
- {
- buildInterpolatedFile( pomFile, pomFile );
+ if (filter) {
+ for (String projectPath : projectPaths) {
+ File pomFile = new File(cloneProjectsTo, projectPath);
+ if (pomFile.isFile()) {
+ buildInterpolatedFile(pomFile, pomFile);
}
// MINVOKER-186
// The following is a temporary solution to support Maven 3.3.1 (.mvn/extensions.xml) filtering
// Will be replaced by MINVOKER-117 with general filtering mechanism
File baseDir = pomFile.getParentFile();
- File mvnDir = new File( baseDir, ".mvn" );
- if ( mvnDir.isDirectory() )
- {
- File extensionsFile = new File( mvnDir, "extensions.xml" );
- if ( extensionsFile.isFile() )
- {
- buildInterpolatedFile( extensionsFile, extensionsFile );
+ File mvnDir = new File(baseDir, ".mvn");
+ if (mvnDir.isDirectory()) {
+ File extensionsFile = new File(mvnDir, "extensions.xml");
+ if (extensionsFile.isFile()) {
+ buildInterpolatedFile(extensionsFile, extensionsFile);
}
}
// END MINVOKER-186
@@ -1260,10 +1174,9 @@ public abstract class AbstractInvokerMojo
* @param path The relative path whose parent should be retrieved, must not be <code>null</code>.
* @return The parent path or "." if the specified path has no parent, never <code>null</code>.
*/
- private String getParentPath( String path )
- {
- int lastSep = Math.max( path.lastIndexOf( '/' ), path.lastIndexOf( '\\' ) );
- return ( lastSep < 0 ) ? "." : path.substring( 0, lastSep );
+ private String getParentPath(String path) {
+ int lastSep = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
+ return (lastSep < 0) ? "." : path.substring(0, lastSep);
}
/**
@@ -1273,13 +1186,10 @@ public abstract class AbstractInvokerMojo
* @param destDir The target directory to copy to, must not be <code>null</code>.
* @throws java.io.IOException If the directory structure could not be copied.
*/
- private void copyDirectoryStructure( File sourceDir, File destDir )
- throws IOException
- {
+ private void copyDirectoryStructure(File sourceDir, File destDir) throws IOException {
DirectoryScanner scanner = new DirectoryScanner();
- scanner.setBasedir( sourceDir );
- if ( !cloneAllFiles )
- {
+ scanner.setBasedir(sourceDir);
+ if (!cloneAllFiles) {
scanner.addDefaultExcludes();
}
scanner.scan();
@@ -1289,16 +1199,15 @@ public abstract class AbstractInvokerMojo
*/
destDir.mkdirs();
// Create all the directories, including any symlinks present in source
- FileUtils.mkDirs( sourceDir, scanner.getIncludedDirectories(), destDir );
+ FileUtils.mkDirs(sourceDir, scanner.getIncludedDirectories(), destDir);
- for ( String includedFile : scanner.getIncludedFiles() )
- {
- File sourceFile = new File( sourceDir, includedFile );
- File destFile = new File( destDir, includedFile );
- FileUtils.copyFile( sourceFile, destFile );
+ for (String includedFile : scanner.getIncludedFiles()) {
+ File sourceFile = new File(sourceDir, includedFile);
+ File destFile = new File(destDir, includedFile);
+ FileUtils.copyFile(sourceFile, destFile);
// ensure clone project must be writable for additional changes
- destFile.setWritable( true );
+ destFile.setWritable(true);
}
}
@@ -1311,12 +1220,9 @@ public abstract class AbstractInvokerMojo
* <code>null</code> elements.
* @return <code>true</code> if the specified path has already been cloned, <code>false</code> otherwise.
*/
- static boolean alreadyCloned( String subpath, List<String> clonedSubpaths )
- {
- for ( String path : clonedSubpaths )
- {
- if ( ".".equals( path ) || subpath.equals( path ) || subpath.startsWith( path + File.separator ) )
- {
+ static boolean alreadyCloned(String subpath, List<String> clonedSubpaths) {
+ for (String path : clonedSubpaths) {
+ if (".".equals(path) || subpath.equals(path) || subpath.startsWith(path + File.separator)) {
return true;
}
}
@@ -1331,11 +1237,9 @@ public abstract class AbstractInvokerMojo
* @param buildJobs The build jobs to run must not be <code>null</code> nor contain <code>null</code> elements.
* @throws org.apache.maven.plugin.MojoExecutionException If any build could not be launched.
*/
- private void runBuilds( final File projectsDir, List<BuildJob> buildJobs, int runWithParallelThreads )
- throws MojoExecutionException
- {
- if ( !localRepositoryPath.exists() )
- {
+ private void runBuilds(final File projectsDir, List<BuildJob> buildJobs, int runWithParallelThreads)
+ throws MojoExecutionException {
+ if (!localRepositoryPath.exists()) {
localRepositoryPath.mkdirs();
}
@@ -1343,132 +1247,107 @@ public abstract class AbstractInvokerMojo
// interpolate settings file
// -----------------------------------------------
- File interpolatedSettingsFile = interpolateSettings( settingsFile );
+ File interpolatedSettingsFile = interpolateSettings(settingsFile);
- final File mergedSettingsFile = mergeSettings( interpolatedSettingsFile );
+ final File mergedSettingsFile = mergeSettings(interpolatedSettingsFile);
final CharSequence actualJreVersion;
// @todo if ( javaVersions ) ... to be picked up from toolchains
- if ( javaHome != null )
- {
+ if (javaHome != null) {
actualJreVersion = resolveExternalJreVersion();
- }
- else
- {
+ } else {
actualJreVersion = SelectorUtils.getJreVersion();
}
final Path projectsPath = this.projectsDirectory.toPath();
Set<Path> folderGroupSet = new HashSet<>();
- folderGroupSet.add( Paths.get( "." ) );
- for ( BuildJob buildJob : buildJobs )
- {
- Path p = Paths.get( buildJob.getProject() );
+ folderGroupSet.add(Paths.get("."));
+ for (BuildJob buildJob : buildJobs) {
+ Path p = Paths.get(buildJob.getProject());
- if ( Files.isRegularFile( projectsPath.resolve( p ) ) )
- {
+ if (Files.isRegularFile(projectsPath.resolve(p))) {
p = p.getParent();
}
- if ( p != null )
- {
+ if (p != null) {
p = p.getParent();
}
- while ( p != null && folderGroupSet.add( p ) )
- {
+ while (p != null && folderGroupSet.add(p)) {
p = p.getParent();
}
}
- List<Path> folderGroup = new ArrayList<>( folderGroupSet );
- Collections.sort( folderGroup );
+ List<Path> folderGroup = new ArrayList<>(folderGroupSet);
+ Collections.sort(folderGroup);
final Map<Path, Properties> globalInvokerProperties = new HashMap<>();
- for ( Path path : folderGroup )
- {
- Properties ancestorProperties = globalInvokerProperties.get( projectsPath.resolve( path ).getParent() );
+ for (Path path : folderGroup) {
+ Properties ancestorProperties =
+ globalInvokerProperties.get(projectsPath.resolve(path).getParent());
- Path currentInvokerProperties = projectsPath.resolve( path ).resolve( invokerPropertiesFile );
+ Path currentInvokerProperties = projectsPath.resolve(path).resolve(invokerPropertiesFile);
Properties currentProperties;
- if ( Files.isRegularFile( currentInvokerProperties ) )
- {
- if ( ancestorProperties != null )
- {
- currentProperties = new Properties( ancestorProperties );
+ if (Files.isRegularFile(currentInvokerProperties)) {
+ if (ancestorProperties != null) {
+ currentProperties = new Properties(ancestorProperties);
- }
- else
- {
+ } else {
currentProperties = new Properties();
}
- }
- else
- {
+ } else {
currentProperties = ancestorProperties;
}
- if ( Files.isRegularFile( currentInvokerProperties ) )
- {
- try ( InputStream in = new FileInputStream( currentInvokerProperties.toFile() ) )
- {
- currentProperties.load( in );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to read invoker properties: "
- + currentInvokerProperties );
+ if (Files.isRegularFile(currentInvokerProperties)) {
+ try (InputStream in = new FileInputStream(currentInvokerProperties.toFile())) {
+ currentProperties.load(in);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to read invoker properties: " + currentInvokerProperties);
}
}
- if ( currentProperties != null )
- {
- globalInvokerProperties.put( projectsPath.resolve( path ).normalize(), currentProperties );
+ if (currentProperties != null) {
+ globalInvokerProperties.put(projectsPath.resolve(path).normalize(), currentProperties);
}
}
- try
- {
- if ( runWithParallelThreads > 1 )
- {
- getLog().info( "use parallelThreads " + runWithParallelThreads );
+ try {
+ if (runWithParallelThreads > 1) {
+ getLog().info("use parallelThreads " + runWithParallelThreads);
}
- JobExecutor jobExecutor = new JobExecutor( buildJobs, runWithParallelThreads );
- jobExecutor.forEach( job ->
- {
- Path ancestorFolder = getAncestorFolder( projectsPath.resolve( job.getProject() ) );
+ JobExecutor jobExecutor = new JobExecutor(buildJobs, runWithParallelThreads);
+ jobExecutor.forEach(job -> {
+ Path ancestorFolder = getAncestorFolder(projectsPath.resolve(job.getProject()));
- runBuild( projectsDir, job, mergedSettingsFile, javaHome, actualJreVersion,
- globalInvokerProperties.get( ancestorFolder ) );
-
- } );
- }
- finally
- {
- if ( interpolatedSettingsFile != null && cloneProjectsTo == null )
- {
+ runBuild(
+ projectsDir,
+ job,
+ mergedSettingsFile,
+ javaHome,
+ actualJreVersion,
+ globalInvokerProperties.get(ancestorFolder));
+ });
+ } finally {
+ if (interpolatedSettingsFile != null && cloneProjectsTo == null) {
interpolatedSettingsFile.delete();
}
- if ( mergedSettingsFile != null && mergedSettingsFile.exists() )
- {
+ if (mergedSettingsFile != null && mergedSettingsFile.exists()) {
mergedSettingsFile.delete();
}
}
}
- private Path getAncestorFolder( Path p )
- {
+ private Path getAncestorFolder(Path p) {
Path ancestor = p;
- if ( Files.isRegularFile( ancestor ) )
- {
+ if (Files.isRegularFile(ancestor)) {
ancestor = ancestor.getParent();
}
- if ( ancestor != null )
- {
+ if (ancestor != null) {
ancestor = ancestor.getParent();
}
return ancestor;
@@ -1481,22 +1360,16 @@ public abstract class AbstractInvokerMojo
* @return The interpolated settings.xml file.
* @throws MojoExecutionException in case of a problem.
*/
- private File interpolateSettings( File settingsFile )
- throws MojoExecutionException
- {
+ private File interpolateSettings(File settingsFile) throws MojoExecutionException {
File interpolatedSettingsFile = null;
- if ( settingsFile != null )
- {
- if ( cloneProjectsTo != null )
- {
- interpolatedSettingsFile = new File( cloneProjectsTo, "interpolated-" + settingsFile.getName() );
- }
- else
- {
+ if (settingsFile != null) {
+ if (cloneProjectsTo != null) {
+ interpolatedSettingsFile = new File(cloneProjectsTo, "interpolated-" + settingsFile.getName());
+ } else {
interpolatedSettingsFile =
- new File( settingsFile.getParentFile(), "interpolated-" + settingsFile.getName() );
+ new File(settingsFile.getParentFile(), "interpolated-" + settingsFile.getName());
}
- buildInterpolatedFile( settingsFile, interpolatedSettingsFile );
+ buildInterpolatedFile(settingsFile, interpolatedSettingsFile);
}
return interpolatedSettingsFile;
}
@@ -1508,136 +1381,105 @@ public abstract class AbstractInvokerMojo
* @return The merged settings file.
* @throws MojoExecutionException Fail the build in case the merged settings file can't be created.
*/
- private File mergeSettings( File interpolatedSettingsFile )
- throws MojoExecutionException
- {
+ private File mergeSettings(File interpolatedSettingsFile) throws MojoExecutionException {
File mergedSettingsFile;
Settings mergedSettings = this.settings;
- if ( mergeUserSettings )
- {
- if ( interpolatedSettingsFile != null )
- {
+ if (mergeUserSettings) {
+ if (interpolatedSettingsFile != null) {
// Have to merge the specified settings file (dominant) and the one of the invoking Maven process
- try
- {
+ try {
SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
- request.setGlobalSettingsFile( interpolatedSettingsFile );
+ request.setGlobalSettingsFile(interpolatedSettingsFile);
- Settings dominantSettings = settingsBuilder.build( request ).getEffectiveSettings();
+ Settings dominantSettings = settingsBuilder.build(request).getEffectiveSettings();
Settings recessiveSettings = cloneSettings();
- SettingsUtils.merge( dominantSettings, recessiveSettings, TrackableBase.USER_LEVEL );
+ SettingsUtils.merge(dominantSettings, recessiveSettings, TrackableBase.USER_LEVEL);
mergedSettings = dominantSettings;
- getLog().debug( "Merged specified settings file with settings of invoking process" );
- }
- catch ( SettingsBuildingException e )
- {
- throw new MojoExecutionException( "Could not read specified settings file", e );
+ getLog().debug("Merged specified settings file with settings of invoking process");
+ } catch (SettingsBuildingException e) {
+ throw new MojoExecutionException("Could not read specified settings file", e);
}
}
}
- if ( this.settingsFile != null && !mergeUserSettings )
- {
+ if (this.settingsFile != null && !mergeUserSettings) {
mergedSettingsFile = interpolatedSettingsFile;
- }
- else
- {
- try
- {
- mergedSettingsFile = writeMergedSettingsFile( mergedSettings );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Could not create temporary file for invoker settings.xml", e );
+ } else {
+ try {
+ mergedSettingsFile = writeMergedSettingsFile(mergedSettings);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Could not create temporary file for invoker settings.xml", e);
}
}
return mergedSettingsFile;
}
- private File writeMergedSettingsFile( Settings mergedSettings )
- throws IOException
- {
+ private File writeMergedSettingsFile(Settings mergedSettings) throws IOException {
File mergedSettingsFile;
- mergedSettingsFile = File.createTempFile( "invoker-settings", ".xml" );
+ mergedSettingsFile = File.createTempFile("invoker-settings", ".xml");
SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer();
-
- try ( FileWriter fileWriter = new FileWriter( mergedSettingsFile ) )
- {
- settingsWriter.write( fileWriter, mergedSettings );
+ try (FileWriter fileWriter = new FileWriter(mergedSettingsFile)) {
+ settingsWriter.write(fileWriter, mergedSettings);
}
- if ( getLog().isDebugEnabled() )
- {
- getLog().debug( "Created temporary file for invoker settings.xml: "
- + mergedSettingsFile.getAbsolutePath() );
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("Created temporary file for invoker settings.xml: " + mergedSettingsFile.getAbsolutePath());
}
return mergedSettingsFile;
}
- private Settings cloneSettings()
- {
- Settings recessiveSettings = SettingsUtils.copySettings( this.settings );
+ private Settings cloneSettings() {
+ Settings recessiveSettings = SettingsUtils.copySettings(this.settings);
// MINVOKER-133: reset sourceLevelSet
- resetSourceLevelSet( recessiveSettings );
- for ( org.apache.maven.settings.Mirror mirror : recessiveSettings.getMirrors() )
- {
- resetSourceLevelSet( mirror );
+ resetSourceLevelSet(recessiveSettings);
+ for (org.apache.maven.settings.Mirror mirror : recessiveSettings.getMirrors()) {
+ resetSourceLevelSet(mirror);
}
- for ( org.apache.maven.settings.Server server : recessiveSettings.getServers() )
- {
- resetSourceLevelSet( server );
+ for (org.apache.maven.settings.Server server : recessiveSettings.getServers()) {
+ resetSourceLevelSet(server);
}
- for ( org.apache.maven.settings.Proxy proxy : recessiveSettings.getProxies() )
- {
- resetSourceLevelSet( proxy );
+ for (org.apache.maven.settings.Proxy proxy : recessiveSettings.getProxies()) {
+ resetSourceLevelSet(proxy);
}
- for ( org.apache.maven.settings.Profile profile : recessiveSettings.getProfiles() )
- {
- resetSourceLevelSet( profile );
+ for (org.apache.maven.settings.Profile profile : recessiveSettings.getProfiles()) {
+ resetSourceLevelSet(profile);
}
return recessiveSettings;
}
- private void resetSourceLevelSet( org.apache.maven.settings.TrackableBase trackable )
- {
- try
- {
- ReflectionUtils.setVariableValueInObject( trackable, "sourceLevelSet", Boolean.FALSE );
- getLog().debug( "sourceLevelSet: "
- + ReflectionUtils.getValueIncludingSuperclasses( "sourceLevelSet", trackable ) );
- }
- catch ( IllegalAccessException e )
- {
+ private void resetSourceLevelSet(org.apache.maven.settings.TrackableBase trackable) {
+ try {
+ ReflectionUtils.setVariableValueInObject(trackable, "sourceLevelSet", Boolean.FALSE);
+ getLog().debug("sourceLevelSet: "
+ + ReflectionUtils.getValueIncludingSuperclasses("sourceLevelSet", trackable));
+ } catch (IllegalAccessException e) {
// noop
}
}
- private CharSequence resolveExternalJreVersion()
- {
- Artifact pluginArtifact = mojoExecution.getMojoDescriptor().getPluginDescriptor().getPluginArtifact();
+ private CharSequence resolveExternalJreVersion() {
+ Artifact pluginArtifact =
+ mojoExecution.getMojoDescriptor().getPluginDescriptor().getPluginArtifact();
pluginArtifact.getFile();
Commandline commandLine = new Commandline();
- commandLine.setExecutable( new File( javaHome, "bin/java" ).getAbsolutePath() );
- commandLine.createArg().setValue( "-cp" );
- commandLine.createArg().setFile( pluginArtifact.getFile() );
- commandLine.createArg().setValue( SystemPropertyPrinter.class.getName() );
- commandLine.createArg().setValue( "java.version" );
+ commandLine.setExecutable(new File(javaHome, "bin/java").getAbsolutePath());
+ commandLine.createArg().setValue("-cp");
+ commandLine.createArg().setFile(pluginArtifact.getFile());
+ commandLine.createArg().setValue(SystemPropertyPrinter.class.getName());
+ commandLine.createArg().setValue("java.version");
final StringBuilder actualJreVersion = new StringBuilder();
StreamConsumer consumer = actualJreVersion::append;
- try
- {
- CommandLineUtils.executeCommandLine( commandLine, consumer, null );
- }
- catch ( CommandLineException e )
- {
- getLog().warn( e.getMessage() );
+ try {
+ CommandLineUtils.executeCommandLine(commandLine, consumer, null);
+ } catch (CommandLineException e) {
+ getLog().warn(e.getMessage());
}
return actualJreVersion;
}
@@ -1651,19 +1493,13 @@ public abstract class AbstractInvokerMojo
* will be returned.
* @throws MojoExecutionException
*/
- private File interpolatePomFile( File pomFile, File basedir )
- throws MojoExecutionException
- {
+ private File interpolatePomFile(File pomFile, File basedir) throws MojoExecutionException {
File interpolatedPomFile = null;
- if ( pomFile != null )
- {
- if ( StringUtils.isNotEmpty( filteredPomPrefix ) )
- {
- interpolatedPomFile = new File( basedir, filteredPomPrefix + pomFile.getName() );
- buildInterpolatedFile( pomFile, interpolatedPomFile );
- }
- else
- {
+ if (pomFile != null) {
+ if (StringUtils.isNotEmpty(filteredPomPrefix)) {
+ interpolatedPomFile = new File(basedir, filteredPomPrefix + pomFile.getName());
+ buildInterpolatedFile(pomFile, interpolatedPomFile);
+ } else {
interpolatedPomFile = pomFile;
}
}
@@ -1680,176 +1516,141 @@ public abstract class AbstractInvokerMojo
* @param globalInvokerProperties
* @throws org.apache.maven.plugin.MojoExecutionException If the project could not be launched.
*/
- private void runBuild( File projectsDir, BuildJob buildJob, File settingsFile, File actualJavaHome,
- CharSequence actualJreVersion, Properties globalInvokerProperties )
- throws MojoExecutionException
- {
+ private void runBuild(
+ File projectsDir,
+ BuildJob buildJob,
+ File settingsFile,
+ File actualJavaHome,
+ CharSequence actualJreVersion,
+ Properties globalInvokerProperties)
+ throws MojoExecutionException {
// FIXME: Think about the following code part -- START
- File pomFile = new File( projectsDir, buildJob.getProject() );
+ File pomFile = new File(projectsDir, buildJob.getProject());
File basedir;
- if ( pomFile.isDirectory() )
- {
+ if (pomFile.isDirectory()) {
basedir = pomFile;
- pomFile = new File( basedir, "pom.xml" );
- if ( !pomFile.exists() )
- {
+ pomFile = new File(basedir, "pom.xml");
+ if (!pomFile.exists()) {
pomFile = null;
+ } else {
+ buildJob.setProject(buildJob.getProject() + File.separator + "pom.xml");
}
- else
- {
- buildJob.setProject( buildJob.getProject() + File.separator + "pom.xml" );
- }
- }
- else
- {
+ } else {
basedir = pomFile.getParentFile();
}
- File interpolatedPomFile = interpolatePomFile( pomFile, basedir );
+ File interpolatedPomFile = interpolatePomFile(pomFile, basedir);
// FIXME: Think about the following code part -- ^^^^^^^ END
- getLog().info( buffer().a( "Building: " ).strong( buildJob.getProject() ).toString() );
+ getLog().info(buffer().a("Building: ").strong(buildJob.getProject()).toString());
- InvokerProperties invokerProperties = getInvokerProperties( basedir, globalInvokerProperties );
+ InvokerProperties invokerProperties = getInvokerProperties(basedir, globalInvokerProperties);
// let's set what details we can
- buildJob.setName( invokerProperties.getJobName() );
- buildJob.setDescription( invokerProperties.getJobDescription() );
-
- try
- {
- int selection = getSelection( invokerProperties, actualJreVersion );
- if ( selection == 0 )
- {
+ buildJob.setName(invokerProperties.getJobName());
+ buildJob.setDescription(invokerProperties.getJobDescription());
+
+ try {
+ int selection = getSelection(invokerProperties, actualJreVersion);
+ if (selection == 0) {
long milliseconds = System.currentTimeMillis();
boolean executed;
- FileLogger buildLogger = setupBuildLogFile( basedir );
- if ( buildLogger != null )
- {
- buildJob.setBuildlog( buildLogger.getOutputFile().getAbsolutePath() );
+ FileLogger buildLogger = setupBuildLogFile(basedir);
+ if (buildLogger != null) {
+ buildJob.setBuildlog(buildLogger.getOutputFile().getAbsolutePath());
}
- try
- {
- executed = runBuild( basedir, interpolatedPomFile, settingsFile, actualJavaHome,
- invokerProperties, buildLogger );
- }
- finally
- {
+ try {
+ executed = runBuild(
+ basedir, interpolatedPomFile, settingsFile, actualJavaHome, invokerProperties, buildLogger);
+ } finally {
milliseconds = System.currentTimeMillis() - milliseconds;
- buildJob.setTime( milliseconds / 1000.0 );
+ buildJob.setTime(milliseconds / 1000.0);
- if ( buildLogger != null )
- {
+ if (buildLogger != null) {
buildLogger.close();
}
}
- if ( executed )
- {
- buildJob.setResult( BuildJob.Result.SUCCESS );
+ if (executed) {
+ buildJob.setResult(BuildJob.Result.SUCCESS);
- if ( !suppressSummaries )
- {
- getLog().info( pad( buildJob ).success( "SUCCESS" ).a( ' ' )
- + formatTime( buildJob.getTime() ) );
+ if (!suppressSummaries) {
+ getLog().info(pad(buildJob).success("SUCCESS").a(' ') + formatTime(buildJob.getTime()));
}
- }
- else
- {
- buildJob.setResult( BuildJob.Result.SKIPPED );
-
- if ( !suppressSummaries )
- {
- getLog().info( pad( buildJob ).warning( "SKIPPED" ).a( ' ' )
- + formatTime( buildJob.getTime() ) );
+ } else {
+ buildJob.setResult(BuildJob.Result.SKIPPED);
+
+ if (!suppressSummaries) {
+ getLog().info(pad(buildJob).warning("SKIPPED").a(' ') + formatTime(buildJob.getTime()));
}
}
- }
- else
- {
- buildJob.setResult( BuildJob.Result.SKIPPED );
+ } else {
+ buildJob.setResult(BuildJob.Result.SKIPPED);
List<String> messages = new ArrayList<>();
- if ( selection == Selector.SELECTOR_MULTI )
- {
- messages.add( "non-matching selectors" );
- }
- else
- {
- if ( ( selection & Selector.SELECTOR_MAVENVERSION ) != 0 )
- {
- messages.add( "Maven version" );
+ if (selection == Selector.SELECTOR_MULTI) {
+ messages.add("non-matching selectors");
+ } else {
+ if ((selection & Selector.SELECTOR_MAVENVERSION) != 0) {
+ messages.add("Maven version");
}
- if ( ( selection & Selector.SELECTOR_JREVERSION ) != 0 )
- {
- messages.add( "JRE version" );
+ if ((selection & Selector.SELECTOR_JREVERSION) != 0) {
+ messages.add("JRE version");
}
- if ( ( selection & Selector.SELECTOR_OSFAMILY ) != 0 )
- {
- messages.add( "OS" );
+ if ((selection & Selector.SELECTOR_OSFAMILY) != 0) {
+ messages.add("OS");
}
- if ( ( selection & Selector.SELECTOR_TOOLCHAIN ) != 0 )
- {
- messages.add( "Toolchain" );
+ if ((selection & Selector.SELECTOR_TOOLCHAIN) != 0) {
+ messages.add("Toolchain");
}
}
- String message = String.join( ", ", messages );
- if ( !suppressSummaries )
- {
- getLog().info( pad( buildJob ).warning( "SKIPPED" ) + " due to " + message );
+ String message = String.join(", ", messages);
+ if (!suppressSummaries) {
+ getLog().info(pad(buildJob).warning("SKIPPED") + " due to " + message);
}
// Abuse failureMessage, the field in the report which should contain the reason for skipping
// Consider skipCode + I18N
- buildJob.setFailureMessage( "Skipped due to " + message );
+ buildJob.setFailureMessage("Skipped due to " + message);
}
- }
- catch ( RunFailureException e )
- {
- buildJob.setResult( e.getType() );
- buildJob.setFailureMessage( e.getMessage() );
+ } catch (RunFailureException e) {
+ buildJob.setResult(e.getType());
+ buildJob.setFailureMessage(e.getMessage());
- if ( !suppressSummaries )
- {
- getLog().info( " " + e.getMessage() );
- getLog().info( pad( buildJob ).failure( "FAILED" ).a( ' ' ) + formatTime( buildJob.getTime() ) );
+ if (!suppressSummaries) {
+ getLog().info(" " + e.getMessage());
+ getLog().info(pad(buildJob).failure("FAILED").a(' ') + formatTime(buildJob.getTime()));
}
- }
- finally
- {
- deleteInterpolatedPomFile( interpolatedPomFile );
- writeBuildReport( buildJob );
+ } finally {
+ deleteInterpolatedPomFile(interpolatedPomFile);
+ writeBuildReport(buildJob);
}
}
- private MessageBuilder pad( BuildJob buildJob )
- {
- MessageBuilder buffer = buffer( 128 );
+ private MessageBuilder pad(BuildJob buildJob) {
+ MessageBuilder buffer = buffer(128);
- buffer.a( " " );
- buffer.a( buildJob.getProject() );
+ buffer.a(" ");
+ buffer.a(buildJob.getProject());
int l = 10 + buildJob.getProject().length();
- if ( l < RESULT_COLUMN )
- {
- buffer.a( ' ' );
+ if (l < RESULT_COLUMN) {
+ buffer.a(' ');
l++;
- if ( l < RESULT_COLUMN )
- {
- for ( int i = RESULT_COLUMN - l; i > 0; i-- )
- {
- buffer.a( '.' );
+ if (l < RESULT_COLUMN) {
+ for (int i = RESULT_COLUMN - l; i > 0; i--) {
+ buffer.a('.');
}
}
}
- return buffer.a( ' ' );
+ return buffer.a(' ');
}
/**
@@ -1857,10 +1658,8 @@ public abstract class AbstractInvokerMojo
*
* @param interpolatedPomFile The interpolated pom file.
*/
- private void deleteInterpolatedPomFile( File interpolatedPomFile )
- {
- if ( interpolatedPomFile != null && StringUtils.isNotEmpty( filteredPomPrefix ) )
- {
+ private void deleteInterpolatedPomFile(File interpolatedPomFile) {
+ if (interpolatedPomFile != null && StringUtils.isNotEmpty(filteredPomPrefix)) {
interpolatedPomFile.delete();
}
}
@@ -1872,15 +1671,13 @@ public abstract class AbstractInvokerMojo
* @return <code>0</code> if the job corresponding to the properties should be run, otherwise a bitwise value
* representing the reason why it should be skipped.
*/
- private int getSelection( InvokerProperties invokerProperties, CharSequence actualJreVersion )
- {
- return new Selector( actualMavenVersion, actualJreVersion.toString(),
- getToolchainPrivateManager() ).getSelection( invokerProperties );
+ private int getSelection(InvokerProperties invokerProperties, CharSequence actualJreVersion) {
+ return new Selector(actualMavenVersion, actualJreVersion.toString(), getToolchainPrivateManager())
+ .getSelection(invokerProperties);
}
- private ToolchainPrivateManager getToolchainPrivateManager()
- {
- return new ToolchainPrivateManager( toolchainManagerPrivate, session );
+ private ToolchainPrivateManager getToolchainPrivateManager() {
+ return new ToolchainPrivateManager(toolchainManagerPrivate, session);
}
/**
@@ -1889,109 +1686,90 @@ public abstract class AbstractInvokerMojo
* @param buildJob The build job whose report should be written, must not be <code>null</code>.
* @throws org.apache.maven.plugin.MojoExecutionException If the report could not be written.
*/
- private void writeBuildReport( BuildJob buildJob )
- throws MojoExecutionException
- {
- if ( disableReports )
- {
+ private void writeBuildReport(BuildJob buildJob) throws MojoExecutionException {
+ if (disableReports) {
return;
}
- String safeFileName = buildJob.getProject().replace( '/', '_' ).replace( '\\', '_' ).replace( ' ', '_' );
- if ( safeFileName.endsWith( "_pom.xml" ) )
- {
- safeFileName = safeFileName.substring( 0, safeFileName.length() - "_pom.xml".length() );
+ String safeFileName =
+ buildJob.getProject().replace('/', '_').replace('\\', '_').replace(' ', '_');
+ if (safeFileName.endsWith("_pom.xml")) {
+ safeFileName = safeFileName.substring(0, safeFileName.length() - "_pom.xml".length());
}
- File reportFile = new File( reportsDirectory, "BUILD-" + safeFileName + ".xml" );
- try ( FileOutputStream fos = new FileOutputStream( reportFile );
- Writer osw = new OutputStreamWriter( fos, buildJob.getModelEncoding() ) )
- {
+ File reportFile = new File(reportsDirectory, "BUILD-" + safeFileName + ".xml");
+ try (FileOutputStream fos = new FileOutputStream(reportFile);
+ Writer osw = new OutputStreamWriter(fos, buildJob.getModelEncoding())) {
BuildJobXpp3Writer writer = new BuildJobXpp3Writer();
- writer.write( osw, buildJob );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to write build report " + reportFile, e );
+ writer.write(osw, buildJob);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to write build report " + reportFile, e);
}
- if ( writeJunitReport )
- {
- writeJunitReport( buildJob, safeFileName );
+ if (writeJunitReport) {
+ writeJunitReport(buildJob, safeFileName);
}
}
- private void writeJunitReport( BuildJob buildJob, String safeFileName )
- throws MojoExecutionException
- {
- File reportFile = new File( reportsDirectory, "TEST-" + safeFileName + ".xml" );
- Xpp3Dom testsuite = new Xpp3Dom( "testsuite" );
- testsuite.setAttribute( "name", junitPackageName + "." + safeFileName );
- testsuite.setAttribute( "time", Double.toString( buildJob.getTime() ) );
+ private void writeJunitReport(BuildJob buildJob, String safeFileName) throws MojoExecutionException {
+ File reportFile = new File(reportsDirectory, "TEST-" + safeFileName + ".xml");
+ Xpp3Dom testsuite = new Xpp3Dom("testsuite");
+ testsuite.setAttribute("name", junitPackageName + "." + safeFileName);
+ testsuite.setAttribute("time", Double.toString(buildJob.getTime()));
// set default value for required attributes
- testsuite.setAttribute( "tests", "1" );
- testsuite.setAttribute( "errors", "0" );
- testsuite.setAttribute( "skipped", "0" );
- testsuite.setAttribute( "failures", "0" );
-
- Xpp3Dom testcase = new Xpp3Dom( "testcase" );
- testsuite.addChild( testcase );
- switch ( buildJob.getResult() )
- {
+ testsuite.setAttribute("tests", "1");
+ testsuite.setAttribute("errors", "0");
+ testsuite.setAttribute("skipped", "0");
+ testsuite.setAttribute("failures", "0");
+
+ Xpp3Dom testcase = new Xpp3Dom("testcase");
+ testsuite.addChild(testcase);
+ switch (buildJob.getResult()) {
case BuildJob.Result.SUCCESS:
break;
case BuildJob.Result.SKIPPED:
- testsuite.setAttribute( "skipped", "1" );
+ testsuite.setAttribute("skipped", "1");
// adding the failure element
- Xpp3Dom skipped = new Xpp3Dom( "skipped" );
- testcase.addChild( skipped );
- skipped.setValue( buildJob.getFailureMessage() );
+ Xpp3Dom skipped = new Xpp3Dom("skipped");
+ testcase.addChild(skipped);
+ skipped.setValue(buildJob.getFailureMessage());
break;
case BuildJob.Result.ERROR:
- testsuite.setAttribute( "errors", "1" );
+ testsuite.setAttribute("errors", "1");
break;
default:
- testsuite.setAttribute( "failures", "1" );
+ testsuite.setAttribute("failures", "1");
// adding the failure element
- Xpp3Dom failure = new Xpp3Dom( "failure" );
- testcase.addChild( failure );
- failure.setAttribute( "message", buildJob.getFailureMessage() );
+ Xpp3Dom failure = new Xpp3Dom("failure");
+ testcase.addChild(failure);
+ failure.setAttribute("message", buildJob.getFailureMessage());
}
- testcase.setAttribute( "classname", junitPackageName + "." + safeFileName );
- testcase.setAttribute( "name", safeFileName );
- testcase.setAttribute( "time", Double.toString( buildJob.getTime() ) );
- Xpp3Dom systemOut = new Xpp3Dom( "system-out" );
- testcase.addChild( systemOut );
-
+ testcase.setAttribute("classname", junitPackageName + "." + safeFileName);
+ testcase.setAttribute("name", safeFileName);
+ testcase.setAttribute("time", Double.toString(buildJob.getTime()));
+ Xpp3Dom systemOut = new Xpp3Dom("system-out");
+ testcase.addChild(systemOut);
- File buildLogFile = buildJob.getBuildlog() != null ? new File( buildJob.getBuildlog() ) : null;
+ File buildLogFile = buildJob.getBuildlog() != null ? new File(buildJob.getBuildlog()) : null;
- if ( buildLogFile != null && buildLogFile.exists() )
- {
- getLog().debug( "fileLogger:" + buildLogFile );
- try
- {
- systemOut.setValue( FileUtils.fileRead( buildLogFile ) );
+ if (buildLogFile != null && buildLogFile.exists()) {
+ getLog().debug("fileLogger:" + buildLogFile);
+ try {
+ systemOut.setValue(FileUtils.fileRead(buildLogFile));
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to read logfile " + buildLogFile, e);
}
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to read logfile " + buildLogFile, e );
- }
- }
- else
- {
- getLog().debug( safeFileName + "not exists buildLogFile = " + buildLogFile );
+ } else {
+ getLog().debug(safeFileName + "not exists buildLogFile = " + buildLogFile);
}
- try ( FileOutputStream fos = new FileOutputStream( reportFile );
- Writer osw = new OutputStreamWriter( fos, buildJob.getModelEncoding() ) )
- {
- Xpp3DomWriter.write( osw, testsuite );
- } catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to write JUnit build report " + reportFile, e );
+ try (FileOutputStream fos = new FileOutputStream(reportFile);
+ Writer osw = new OutputStreamWriter(fos, buildJob.getModelEncoding())) {
+ Xpp3DomWriter.write(osw, testsuite);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to write JUnit build report " + reportFile, e);
}
}
@@ -2001,9 +1779,8 @@ public abstract class AbstractInvokerMojo
* @param seconds The duration of the build.
* @return The formatted time, never <code>null</code>.
*/
- private String formatTime( double seconds )
- {
- return secFormat.format( seconds );
+ private String formatTime(double seconds) {
+ return secFormat.format(seconds);
}
/**
@@ -2021,18 +1798,20 @@ public abstract class AbstractInvokerMojo
* @throws RunFailureException If either a hook script or the build itself
* failed.
*/
- private boolean runBuild( File basedir, File pomFile, File settingsFile, File actualJavaHome,
- InvokerProperties invokerProperties, FileLogger logger )
- throws MojoExecutionException, RunFailureException
- {
- if ( getLog().isDebugEnabled() && !invokerProperties.getProperties().isEmpty() )
- {
+ private boolean runBuild(
+ File basedir,
+ File pomFile,
+ File settingsFile,
+ File actualJavaHome,
+ InvokerProperties invokerProperties,
+ FileLogger logger)
+ throws MojoExecutionException, RunFailureException {
+ if (getLog().isDebugEnabled() && !invokerProperties.getProperties().isEmpty()) {
Properties props = invokerProperties.getProperties();
- getLog().debug( "Using invoker properties:" );
- for ( String key : new TreeSet<>( props.stringPropertyNames() ) )
- {
- String value = props.getProperty( key );
- getLog().debug( " " + key + " = " + value );
+ getLog().debug("Using invoker properties:");
+ for (String key : new TreeSet<>(props.stringPropertyNames())) {
+ String value = props.getProperty(key);
+ getLog().debug(" " + key + " = " + value);
}
}
@@ -2040,148 +1819,111 @@ public abstract class AbstractInvokerMojo
boolean selectorResult = true;
- try
- {
- try
- {
- scriptRunner.run( "selector script", basedir, selectorScript, context, logger );
- }
- catch ( ScriptReturnException e )
- {
+ try {
+ try {
+ scriptRunner.run("selector script", basedir, selectorScript, context, logger);
+ } catch (ScriptReturnException e) {
selectorResult = false;
return false;
- }
- catch ( ScriptException e )
- {
- throw new RunFailureException( BuildJob.Result.ERROR, e );
+ } catch (ScriptException e) {
+ throw new RunFailureException(BuildJob.Result.ERROR, e);
}
- try
- {
- scriptRunner.run( "pre-build script", basedir, preBuildHookScript, context, logger );
- }
- catch ( ScriptException e )
- {
- throw new RunFailureException( BuildJob.Result.FAILURE_PRE_HOOK, e );
+ try {
+ scriptRunner.run("pre-build script", basedir, preBuildHookScript, context, logger);
+ } catch (ScriptException e) {
+ throw new RunFailureException(BuildJob.Result.FAILURE_PRE_HOOK, e);
}
- for ( int invocationIndex = 1;; invocationIndex++ )
- {
- if ( invocationIndex > 1 && !invokerProperties.isInvocationDefined( invocationIndex ) )
- {
+ for (int invocationIndex = 1; ; invocationIndex++) {
+ if (invocationIndex > 1 && !invokerProperties.isInvocationDefined(invocationIndex)) {
break;
}
final InvocationRequest request = new DefaultInvocationRequest();
- request.setBatchMode( true );
+ request.setBatchMode(true);
// values only from Mojo configurations
- request.setLocalRepositoryDirectory( localRepositoryPath );
- request.setShowErrors( showErrors );
- request.setShowVersion( showVersion );
- request.setJavaHome( actualJavaHome );
- request.setMavenHome( mavenHome );
- setupLoggerForBuildJob( logger, request );
-
- request.setBaseDirectory( basedir );
- request.setPomFile( pomFile );
-
- String customSettingsFile = invokerProperties.getSettingsFile( invocationIndex );
- if ( customSettingsFile != null )
- {
- File interpolateSettingsFile = interpolateSettings( new File( customSettingsFile ) );
- File mergeSettingsFile = mergeSettings( interpolateSettingsFile );
-
- request.setUserSettingsFile( mergeSettingsFile );
- }
- else
- {
- request.setUserSettingsFile( settingsFile );
+ request.setLocalRepositoryDirectory(localRepositoryPath);
+ request.setShowErrors(showErrors);
+ request.setShowVersion(showVersion);
+ request.setJavaHome(actualJavaHome);
+ request.setMavenHome(mavenHome);
+ setupLoggerForBuildJob(logger, request);
+
+ request.setBaseDirectory(basedir);
+ request.setPomFile(pomFile);
+
+ String customSettingsFile = invokerProperties.getSettingsFile(invocationIndex);
+ if (customSettingsFile != null) {
+ File interpolateSettingsFile = interpolateSettings(new File(customSettingsFile));
+ File mergeSettingsFile = mergeSettings(interpolateSettingsFile);
+
+ request.setUserSettingsFile(mergeSettingsFile);
+ } else {
+ request.setUserSettingsFile(settingsFile);
}
Properties systemProperties =
- getSystemProperties( basedir, invokerProperties.getSystemPropertiesFile( invocationIndex ) );
- request.setProperties( systemProperties );
+ getSystemProperties(basedir, invokerProperties.getSystemPropertiesFile(invocationIndex));
+ request.setProperties(systemProperties);
- invokerProperties.configureInvocation( request, invocationIndex );
+ invokerProperties.configureInvocation(request, invocationIndex);
- if ( getLog().isDebugEnabled() )
- {
- try
- {
- getLog().debug( "Using MAVEN_OPTS: " + request.getMavenOpts() );
- getLog().debug( "Executing: " + new MavenCommandLineBuilder().build( request ) );
- }
- catch ( CommandLineConfigurationException e )
- {
- getLog().debug( "Failed to display command line: " + e.getMessage() );
+ if (getLog().isDebugEnabled()) {
+ try {
+ getLog().debug("Using MAVEN_OPTS: " + request.getMavenOpts());
+ getLog().debug("Executing: " + new MavenCommandLineBuilder().build(request));
+ } catch (CommandLineConfigurationException e) {
+ getLog().debug("Failed to display command line: " + e.getMessage());
}
}
- try
- {
- InvocationResult result = invoker.execute( request );
- verify( result, invocationIndex, invokerProperties, logger );
- }
- catch ( final MavenInvocationException e )
- {
- getLog().debug( "Error invoking Maven: " + e.getMessage(), e );
- throw new RunFailureException( "Maven invocation failed. " + e.getMessage(),
- BuildJob.Result.FAILURE_BUILD );
+ try {
+ InvocationResult result = invoker.execute(request);
+ verify(result, invocationIndex, invokerProperties, logger);
+ } catch (final MavenInvocationException e) {
+ getLog().debug("Error invoking Maven: " + e.getMessage(), e);
+ throw new RunFailureException(
+ "Maven invocation failed. " + e.getMessage(), BuildJob.Result.FAILURE_BUILD);
}
}
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( e.getMessage(), e );
- }
- finally
- {
- if ( selectorResult )
- {
- runPostBuildHook( basedir, context, logger );
+ } catch (IOException e) {
+ throw new MojoExecutionException(e.getMessage(), e);
+ } finally {
+ if (selectorResult) {
+ runPostBuildHook(basedir, context, logger);
}
}
return true;
}
- int getParallelThreadsCount()
- {
- if ( parallelThreads.endsWith( "C" ) )
- {
- double parallelThreadsMultiple = Double.parseDouble(
- parallelThreads.substring( 0, parallelThreads.length() - 1 ) );
- return (int) ( parallelThreadsMultiple * Runtime.getRuntime().availableProcessors() );
- }
- else
- {
- return Integer.parseInt( parallelThreads );
+ int getParallelThreadsCount() {
+ if (parallelThreads.endsWith("C")) {
+ double parallelThreadsMultiple =
+ Double.parseDouble(parallelThreads.substring(0, parallelThreads.length() - 1));
+ return (int) (parallelThreadsMultiple * Runtime.getRuntime().availableProcessors());
+ } else {
+ return Integer.parseInt(parallelThreads);
}
}
- private void runPostBuildHook( File basedir, Map<String, Object> context, FileLogger logger )
- throws MojoExecutionException, RunFailureException
- {
- try
- {
- scriptRunner.run( "post-build script", basedir, postBuildHookScript, context, logger );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( e.getMessage(), e );
- }
- catch ( ScriptException e )
- {
- throw new RunFailureException( e.getMessage(), BuildJob.Result.FAILURE_POST_HOOK, e );
+ private void runPostBuildHook(File basedir, Map<String, Object> context, FileLogger logger)
+ throws MojoExecutionException, RunFailureException {
+ try {
+ scriptRunner.run("post-build script", basedir, postBuildHookScript, context, logger);
+ } catch (IOException e) {
+ throw new MojoExecutionException(e.getMessage(), e);
+ } catch (ScriptException e) {
+ throw new RunFailureException(e.getMessage(), BuildJob.Result.FAILURE_POST_HOOK, e);
}
}
- private void setupLoggerForBuildJob( final FileLogger logger, final InvocationRequest request )
- {
- if ( logger != null )
- {
- request.setErrorHandler( logger );
- request.setOutputHandler( logger );
+
+ private void setupLoggerForBuildJob(final FileLogger logger, final InvocationRequest request) {
+ if (logger != null) {
+ request.setErrorHandler(logger);
+ request.setOutputHandler(logger);
}
}
@@ -2193,45 +1935,33 @@ public abstract class AbstractInvokerMojo
* @return The build logger or <code>null</code> if logging has been disabled.
* @throws org.apache.maven.plugin.MojoExecutionException If the log file could not be created.
*/
- private FileLogger setupBuildLogFile( File basedir )
- throws MojoExecutionException
- {
+ private FileLogger setupBuildLogFile(File basedir) throws MojoExecutionException {
FileLogger logger = null;
- if ( !noLog )
- {
+ if (!noLog) {
Path projectLogDirectory;
- if ( logDirectory == null )
- {
+ if (logDirectory == null) {
projectLogDirectory = basedir.toPath();
- }
- else if ( cloneProjectsTo != null )
- {
+ } else if (cloneProjectsTo != null) {
projectLogDirectory =
- logDirectory.toPath().resolve( cloneProjectsTo.toPath().relativize( basedir.toPath() ) );
- }
- else
- {
+ logDirectory.toPath().resolve(cloneProjectsTo.toPath().relativize(basedir.toPath()));
+ } else {
projectLogDirectory =
- logDirectory.toPath().resolve( projectsDirectory.toPath().relativize( basedir.toPath() ) );
+ logDirectory.toPath().resolve(projectsDirectory.toPath().relativize(basedir.toPath()));
}
- try
- {
- if ( streamLogs )
- {
- logger = new FileLogger( projectLogDirectory.resolve( "build.log" ).toFile(), getLog() );
- }
- else
- {
- logger = new FileLogger( projectLogDirectory.resolve( "build.log" ).toFile() );
+ try {
+ if (streamLogs) {
+ logger = new FileLogger(
+ projectLogDirectory.resolve("build.log").toFile(), getLog());
+ } else {
+ logger = new FileLogger(
+ projectLogDirectory.resolve("build.log").toFile());
}
- getLog().debug( "Build log initialized in: " + projectLogDirectory );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Error initializing build logfile in: " + projectLogDirectory, e );
+ getLog().debug("Build log initialized in: " + projectLogDirectory);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Error initializing build logfile in: " + projectLogDirectory, e);
}
}
@@ -2247,45 +1977,33 @@ public abstract class AbstractInvokerMojo
* @return The system properties to use, may be empty but never <code>null</code>.
* @throws org.apache.maven.plugin.MojoExecutionException If the properties file exists but could not be read.
*/
- private Properties getSystemProperties( final File basedir, final String filename )
- throws MojoExecutionException
- {
+ private Properties getSystemProperties(final File basedir, final String filename) throws MojoExecutionException {
Properties collectedTestProperties = new Properties();
- if ( properties != null )
- {
+ if (properties != null) {
// MINVOKER-118: property can have empty value, which is not accepted by collectedTestProperties
- for ( Map.Entry<String, String> entry : properties.entrySet() )
- {
- if ( entry.getValue() != null )
- {
- collectedTestProperties.put( entry.getKey(), entry.getValue() );
+ for (Map.Entry<String, String> entry : properties.entrySet()) {
+ if (entry.getValue() != null) {
+ collectedTestProperties.put(entry.getKey(), entry.getValue());
}
}
}
File propertiesFile = null;
- if ( filename != null )
- {
- propertiesFile = new File( basedir, filename );
- }
- else if ( testPropertiesFile != null )
- {
- propertiesFile = new File( basedir, testPropertiesFile );
+ if (filename != null) {
+ propertiesFile = new File(basedir, filename);
+ } else if (testPropertiesFile != null) {
+ propertiesFile = new File(basedir, testPropertiesFile);
}
- if ( propertiesFile != null && propertiesFile.isFile() )
- {
+ if (propertiesFile != null && propertiesFile.isFile()) {
- try ( InputStream fin = new FileInputStream( propertiesFile ) )
- {
+ try (InputStream fin = new FileInputStream(propertiesFile)) {
Properties loadedProperties = new Properties();
- loadedProperties.load( fin );
- collectedTestProperties.putAll( loadedProperties );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Error reading system properties from " + propertiesFile );
+ loadedProperties.load(fin);
+ collectedTestProperties.putAll(loadedProperties);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Error reading system properties from " + propertiesFile);
}
}
@@ -2300,84 +2018,69 @@ public abstract class AbstractInvokerMojo
* @param invokerProperties The invoker properties used to check the exit code, must not be <code>null</code>.
* @param logger The build logger, may be <code>null</code> if logging is disabled.
*/
- private void verify( InvocationResult result, int invocationIndex, InvokerProperties invokerProperties,
- FileLogger logger )
- throws RunFailureException
- {
- if ( result.getExecutionException() != null )
- {
- throw new RunFailureException( "The Maven invocation failed. "
- + result.getExecutionException().getMessage(), BuildJob.Result.ERROR );
- }
- else if ( !invokerProperties.isExpectedResult( result.getExitCode(), invocationIndex ) )
- {
- StringBuilder buffer = new StringBuilder( 256 );
- buffer.append( "The build exited with code " ).append( result.getExitCode() ).append( ". " );
- if ( logger != null )
- {
- buffer.append( "See " );
- buffer.append( logger.getOutputFile().getAbsolutePath() );
- buffer.append( " for details." );
- }
- else
- {
- buffer.append( "See console output for details." );
- }
- throw new RunFailureException( buffer.toString(), BuildJob.Result.FAILURE_BUILD );
+ private void verify(
+ InvocationResult result, int invocationIndex, InvokerProperties invokerProperties, FileLogger logger)
+ throws RunFailureException {
+ if (result.getExecutionException() != null) {
+ throw new RunFailureException(
+ "The Maven invocation failed. "
+ + result.getExecutionException().getMessage(),
+ BuildJob.Result.ERROR);
+ } else if (!invokerProperties.isExpectedResult(result.getExitCode(), invocationIndex)) {
+ StringBuilder buffer = new StringBuilder(256);
+ buffer.append("The build exited with code ")
+ .append(result.getExitCode())
+ .append(". ");
+ if (logger != null) {
+ buffer.append("See ");
+ buffer.append(logger.getOutputFile().getAbsolutePath());
+ buffer.append(" for details.");
+ } else {
+ buffer.append("See console output for details.");
+ }
+ throw new RunFailureException(buffer.toString(), BuildJob.Result.FAILURE_BUILD);
}
}
- private List<String> calculateIncludes()
- {
- if ( invokerTest != null )
- {
- String[] testRegexes = StringUtils.split( invokerTest, "," );
- return Arrays.stream( testRegexes )
- .map( String::trim )
- .filter( s -> !s.isEmpty() )
- .filter( s -> !s.startsWith( "!" ) )
- .collect( Collectors.toList() );
- }
- else
- {
+ private List<String> calculateIncludes() {
+ if (invokerTest != null) {
+ String[] testRegexes = StringUtils.split(invokerTest, ",");
+ return Arrays.stream(testRegexes)
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .filter(s -> !s.startsWith("!"))
+ .collect(Collectors.toList());
+ } else {
Set<String> uniqueIncludes = new HashSet<>();
- uniqueIncludes.addAll( pomIncludes );
- uniqueIncludes.addAll( setupIncludes );
- return new ArrayList<>( uniqueIncludes );
+ uniqueIncludes.addAll(pomIncludes);
+ uniqueIncludes.addAll(setupIncludes);
+ return new ArrayList<>(uniqueIncludes);
}
}
- private List<String> calculateExcludes()
- throws IOException
- {
+ private List<String> calculateExcludes() throws IOException {
List<String> excludes;
- if ( invokerTest != null )
- {
- String[] testRegexes = StringUtils.split( invokerTest, "," );
- excludes = Arrays.stream( testRegexes )
- .map( String::trim )
- .filter( s -> !s.isEmpty() )
- .filter( s -> s.startsWith( "!" ) )
- .map( s -> s.substring( 1 ) )
- .collect( Collectors.toList() );
- }
- else
- {
- excludes = pomExcludes != null ? new ArrayList<>( pomExcludes ) : new ArrayList<>();
- }
-
- if ( this.settingsFile != null )
- {
- String exclude = relativizePath( this.settingsFile, projectsDirectory.getCanonicalPath() );
- if ( exclude != null )
- {
- excludes.add( exclude.replace( '\\', '/' ) );
- getLog().debug( "Automatically excluded " + exclude + " from project scanning" );
+ if (invokerTest != null) {
+ String[] testRegexes = StringUtils.split(invokerTest, ",");
+ excludes = Arrays.stream(testRegexes)
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .filter(s -> s.startsWith("!"))
+ .map(s -> s.substring(1))
+ .collect(Collectors.toList());
+ } else {
+ excludes = pomExcludes != null ? new ArrayList<>(pomExcludes) : new ArrayList<>();
+ }
+
+ if (this.settingsFile != null) {
+ String exclude = relativizePath(this.settingsFile, projectsDirectory.getCanonicalPath());
+ if (exclude != null) {
+ excludes.add(exclude.replace('\\', '/'));
+ getLog().debug("Automatically excluded " + exclude + " from project scanning");
}
}
return excludes;
-
}
/**
@@ -2386,33 +2089,26 @@ public abstract class AbstractInvokerMojo
* @return The build jobs to process, may be empty but never <code>null</code>.
* @throws java.io.IOException If the projects directory could not be scanned.
*/
- List<BuildJob> getBuildJobs()
- throws IOException, MojoExecutionException
- {
+ List<BuildJob> getBuildJobs() throws IOException, MojoExecutionException {
List<String> includes = calculateIncludes();
List<String> excludes = calculateExcludes();
- List<BuildJob> buildJobsAll = scanProjectsDirectory( includes, excludes );
- List<BuildJob> buildJobsSetup = scanProjectsDirectory( setupIncludes, excludes );
+ List<BuildJob> buildJobsAll = scanProjectsDirectory(includes, excludes);
+ List<BuildJob> buildJobsSetup = scanProjectsDirectory(setupIncludes, excludes);
- List<String> setupProjects = buildJobsSetup.stream()
- .map( BuildJob::getProject )
- .collect( Collectors.toList() );
+ List<String> setupProjects =
+ buildJobsSetup.stream().map(BuildJob::getProject).collect(Collectors.toList());
-
- for ( BuildJob job : buildJobsAll )
- {
- if ( setupProjects.contains( job.getProject() ) )
- {
- job.setType( BuildJob.Type.SETUP );
+ for (BuildJob job : buildJobsAll) {
+ if (setupProjects.contains(job.getProject())) {
+ job.setType(BuildJob.Type.SETUP);
}
InvokerProperties invokerProperties =
- getInvokerProperties( new File( projectsDirectory, job.getProject() ).getParentFile(),
- null );
- job.setOrdinal( invokerProperties.getOrdinal() );
+ getInvokerProperties(new File(projectsDirectory, job.getProject()).getParentFile(), null);
+ job.setOrdinal(invokerProperties.getOrdinal());
}
- relativizeProjectPaths( buildJobsAll );
+ relativizeProjectPaths(buildJobsAll);
return buildJobsAll;
}
@@ -2428,53 +2124,42 @@ public abstract class AbstractInvokerMojo
* @return The build jobs matching the patterns, never <code>null</code>.
* @throws java.io.IOException If the project directory could not be scanned.
*/
- private List<BuildJob> scanProjectsDirectory( List<String> includes, List<String> excludes )
- throws IOException
- {
- if ( !projectsDirectory.isDirectory() )
- {
+ private List<BuildJob> scanProjectsDirectory(List<String> includes, List<String> excludes) throws IOException {
+ if (!projectsDirectory.isDirectory()) {
return Collections.emptyList();
}
DirectoryScanner scanner = new DirectoryScanner();
- scanner.setBasedir( projectsDirectory.getCanonicalFile() );
- scanner.setFollowSymlinks( false );
- if ( includes != null )
- {
- scanner.setIncludes( includes.toArray( new String[0] ) );
- }
- if ( excludes != null )
- {
- if ( ( includes == null || includes.isEmpty() ) && !excludes.isEmpty() )
- {
- scanner.setIncludes( new String[] { "*" } );
+ scanner.setBasedir(projectsDirectory.getCanonicalFile());
+ scanner.setFollowSymlinks(false);
+ if (includes != null) {
+ scanner.setIncludes(includes.toArray(new String[0]));
+ }
+ if (excludes != null) {
+ if ((includes == null || includes.isEmpty()) && !excludes.isEmpty()) {
+ scanner.setIncludes(new String[] {"*"});
}
- scanner.setExcludes( excludes.toArray( new String[0] ) );
+ scanner.setExcludes(excludes.toArray(new String[0]));
}
scanner.addDefaultExcludes();
scanner.scan();
Map<String, BuildJob> matches = new LinkedHashMap<>();
- for ( String includedFile : scanner.getIncludedFiles() )
- {
- matches.put( includedFile, new BuildJob( includedFile ) );
+ for (String includedFile : scanner.getIncludedFiles()) {
+ matches.put(includedFile, new BuildJob(includedFile));
}
- for ( String includedDir : scanner.getIncludedDirectories() )
- {
+ for (String includedDir : scanner.getIncludedDirectories()) {
String includedFile = includedDir + File.separatorChar + "pom.xml";
- if ( new File( scanner.getBasedir(), includedFile ).isFile() )
- {
- matches.put( includedFile, new BuildJob( includedFile ) );
- }
- else
- {
- matches.put( includedDir, new BuildJob( includedDir ) );
+ if (new File(scanner.getBasedir(), includedFile).isFile()) {
+ matches.put(includedFile, new BuildJob(includedFile));
+ } else {
+ matches.put(includedDir, new BuildJob(includedDir));
}
}
- return new ArrayList<>( matches.values() );
+ return new ArrayList<>(matches.values());
}
/**
@@ -2486,30 +2171,25 @@ public abstract class AbstractInvokerMojo
* contain <code>null</code> elements.
* @throws java.io.IOException If any path could not be relativized.
*/
- private void relativizeProjectPaths( List<BuildJob> buildJobs )
- throws IOException
- {
+ private void relativizeProjectPaths(List<BuildJob> buildJobs) throws IOException {
String projectsDirPath = projectsDirectory.getCanonicalPath();
- for ( BuildJob buildJob : buildJobs )
- {
+ for (BuildJob buildJob : buildJobs) {
String projectPath = buildJob.getProject();
- File file = new File( projectPath );
+ File file = new File(projectPath);
- if ( !file.isAbsolute() )
- {
- file = new File( projectsDirectory, projectPath );
+ if (!file.isAbsolute()) {
+ file = new File(projectsDirectory, projectPath);
}
- String relativizedPath = relativizePath( file, projectsDirPath );
+ String relativizedPath = relativizePath(file, projectsDirPath);
- if ( relativizedPath == null )
- {
+ if (relativizedPath == null) {
relativizedPath = projectPath;
}
- buildJob.setProject( relativizedPath );
+ buildJob.setProject(relativizedPath);
}
}
@@ -2523,23 +2203,17 @@ public abstract class AbstractInvokerMojo
* base directory.
* @throws java.io.IOException If the path could not be relativized.
*/
- private String relativizePath( File path, String basedir )
- throws IOException
- {
+ private String relativizePath(File path, String basedir) throws IOException {
String relativizedPath = path.getCanonicalPath();
- if ( relativizedPath.startsWith( basedir ) )
- {
- relativizedPath = relativizedPath.substring( basedir.length() );
- if ( relativizedPath.startsWith( File.separator ) )
- {
- relativizedPath = relativizedPath.substring( File.separator.length() );
+ if (relativizedPath.startsWith(basedir)) {
+ relativizedPath = relativizedPath.substring(basedir.length());
+ if (relativizedPath.startsWith(File.separator)) {
+ relativizedPath = relativizedPath.substring(File.separator.length());
}
return relativizedPath;
- }
- else
- {
+ } else {
return null;
}
}
@@ -2552,23 +2226,20 @@ public abstract class AbstractInvokerMojo
*
* @return The map-based value source for interpolation, never <code>null</code>.
*/
- private Map<String, Object> getInterpolationValueSource( final boolean escapeXml )
- {
+ private Map<String, Object> getInterpolationValueSource(final boolean escapeXml) {
Map<String, Object> props = new HashMap<>();
- if ( filterProperties != null )
- {
- props.putAll( filterProperties );
+ if (filterProperties != null) {
+ props.putAll(filterProperties);
}
- props.put( "basedir", this.project.getBasedir().getAbsolutePath() );
- props.put( "baseurl", toUrl( this.project.getBasedir().getAbsolutePath() ) );
- if ( settings.getLocalRepository() != null )
- {
- props.put( "localRepository", settings.getLocalRepository() );
- props.put( "localRepositoryUrl", toUrl( settings.getLocalRepository() ) );
+ props.put("basedir", this.project.getBasedir().getAbsolutePath());
+ props.put("baseurl", toUrl(this.project.getBasedir().getAbsolutePath()));
+ if (settings.getLocalRepository() != null) {
+ props.put("localRepository", settings.getLocalRepository());
+ props.put("localRepositoryUrl", toUrl(settings.getLocalRepository()));
}
- return new CompositeMap( this.project, props, escapeXml );
+ return new CompositeMap(this.project, props, escapeXml);
}
/**
@@ -2578,16 +2249,14 @@ public abstract class AbstractInvokerMojo
* @param filename The filesystem path to convert, must not be <code>null</code>.
* @return The <code>file:</code> URL for the specified path, never <code>null</code>.
*/
- private static String toUrl( String filename )
- {
+ private static String toUrl(String filename) {
/*
* NOTE: Maven fails to properly handle percent-encoded "file:" URLs (WAGON-111) so don't use File.toURI() here
* as-is but use the decoded path component in the URL.
*/
- String url = "file://" + new File( filename ).toURI().getPath();
- if ( url.endsWith( "/" ) )
- {
- url = url.substring( 0, url.length() - 1 );
+ String url = "file://" + new File(filename).toURI().getPath();
+ if (url.endsWith("/")) {
+ url = url.substring(0, url.length() - 1);
}
return url;
}
@@ -2605,34 +2274,27 @@ public abstract class AbstractInvokerMojo
*
* @throws org.apache.maven.plugin.MojoExecutionException If the target file could not be created.
*/
- void buildInterpolatedFile( File originalFile, File interpolatedFile )
- throws MojoExecutionException
- {
- getLog().debug( "Interpolate " + originalFile.getPath() + " to " + interpolatedFile.getPath() );
+ void buildInterpolatedFile(File originalFile, File interpolatedFile) throws MojoExecutionException {
+ getLog().debug("Interpolate " + originalFile.getPath() + " to " + interpolatedFile.getPath());
- try
- {
+ try {
String xml;
- Map<String, Object> composite = getInterpolationValueSource( true );
+ Map<String, Object> composite = getInterpolationValueSource(true);
// interpolation with token @...@
- try ( Reader reader =
- new InterpolationFilterReader( ReaderFactory.newXmlReader( originalFile ), composite, "@", "@" ) )
- {
- xml = IOUtil.toString( reader );
+ try (Reader reader =
+ new InterpolationFilterReader(ReaderFactory.newXmlReader(originalFile), composite, "@", "@")) {
+ xml = IOUtil.toString(reader);
}
- try ( Writer writer = WriterFactory.newXmlWriter( interpolatedFile ) )
- {
+ try (Writer writer = WriterFactory.newXmlWriter(interpolatedFile)) {
interpolatedFile.getParentFile().mkdirs();
- writer.write( xml );
+ writer.write(xml);
}
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to interpolate file " + originalFile.getPath(), e );
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to interpolate file " + originalFile.getPath(), e);
}
}
@@ -2643,82 +2305,65 @@ public abstract class AbstractInvokerMojo
* @return The invoker properties, may be empty but never <code>null</code>.
* @throws org.apache.maven.plugin.MojoExecutionException If an I/O error occurred during reading the properties.
*/
- private InvokerProperties getInvokerProperties( final File projectDirectory, Properties globalInvokerProperties )
- throws MojoExecutionException
- {
+ private InvokerProperties getInvokerProperties(final File projectDirectory, Properties globalInvokerProperties)
+ throws MojoExecutionException {
Properties props;
- if ( globalInvokerProperties != null )
- {
- props = new Properties( globalInvokerProperties );
- }
- else
- {
+ if (globalInvokerProperties != null) {
+ props = new Properties(globalInvokerProperties);
+ } else {
props = new Properties();
}
- File propertiesFile = new File( projectDirectory, invokerPropertiesFile );
- if ( propertiesFile.isFile() )
- {
- try ( InputStream in = new FileInputStream( propertiesFile ) )
- {
- props.load( in );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to read invoker properties: " + propertiesFile, e );
+ File propertiesFile = new File(projectDirectory, invokerPropertiesFile);
+ if (propertiesFile.isFile()) {
+ try (InputStream in = new FileInputStream(propertiesFile)) {
+ props.load(in);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to read invoker properties: " + propertiesFile, e);
}
}
Interpolator interpolator = new RegexBasedInterpolator();
- interpolator.addValueSource( new MapBasedValueSource( getInterpolationValueSource( false ) ) );
+ interpolator.addValueSource(new MapBasedValueSource(getInterpolationValueSource(false)));
// CHECKSTYLE_OFF: LineLength
- for ( String key : props.stringPropertyNames() )
- {
- String value = props.getProperty( key );
- try
- {
- value = interpolator.interpolate( value, "" );
- }
- catch ( InterpolationException e )
- {
- throw new MojoExecutionException( "Failed to interpolate invoker properties: " + propertiesFile,
- e );
+ for (String key : props.stringPropertyNames()) {
+ String value = props.getProperty(key);
+ try {
+ value = interpolator.interpolate(value, "");
+ } catch (InterpolationException e) {
+ throw new MojoExecutionException("Failed to interpolate invoker properties: " + propertiesFile, e);
}
- props.setProperty( key, value );
+ props.setProperty(key, value);
}
- InvokerProperties invokerProperties = new InvokerProperties( props );
+ InvokerProperties invokerProperties = new InvokerProperties(props);
// set default value for Invoker - it will be used if not present in properties
- invokerProperties.setDefaultDebug( debug );
- invokerProperties.setDefaultQuiet( quiet );
- invokerProperties.setDefaultGoals( goals );
- invokerProperties.setDefaultProfiles( profiles );
- invokerProperties.setDefaultMavenExecutable( mavenExecutable );
- invokerProperties.setDefaultMavenOpts( mavenOpts );
- invokerProperties.setDefaultTimeoutInSeconds( timeoutInSeconds );
- invokerProperties.setDefaultEnvironmentVariables( environmentVariables );
- invokerProperties.setDefaultUpdateSnapshots( updateSnapshots );
-
+ invokerProperties.setDefaultDebug(debug);
+ invokerProperties.setDefaultQuiet(quiet);
+ invokerProperties.setDefaultGoals(goals);
+ invokerProperties.setDefaultProfiles(profiles);
+ invokerProperties.setDefaultMavenExecutable(mavenExecutable);
+ invokerProperties.setDefaultMavenOpts(mavenOpts);
+ invokerProperties.setDefaultTimeoutInSeconds(timeoutInSeconds);
+ invokerProperties.setDefaultEnvironmentVariables(environmentVariables);
+ invokerProperties.setDefaultUpdateSnapshots(updateSnapshots);
return invokerProperties;
}
- static class ToolchainPrivateManager
- {
+ static class ToolchainPrivateManager {
private ToolchainManagerPrivate manager;
private MavenSession session;
- ToolchainPrivateManager( ToolchainManagerPrivate manager, MavenSession session )
- {
+ ToolchainPrivateManager(ToolchainManagerPrivate manager, MavenSession session) {
this.manager = manager;
this.session = session;
}
- ToolchainPrivate[] getToolchainPrivates( String type ) throws MisconfiguredToolchainException
- {
- return manager.getToolchainsForType( type, session );
+ ToolchainPrivate[] getToolchainPrivates(String type) throws MisconfiguredToolchainException {
+ return manager.getToolchainsForType(type, session);
}
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/CompositeMap.java b/src/main/java/org/apache/maven/plugins/invoker/CompositeMap.java
index 2828201..a491809 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/CompositeMap.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/CompositeMap.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -33,9 +51,7 @@ import org.codehaus.plexus.util.introspection.ReflectionValueExtractor;
* @author Olivier Lamy
* @since 1.1
*/
-class CompositeMap
- implements Map<String, Object>
-{
+class CompositeMap implements Map<String, Object> {
/**
* The Maven project from which to extract interpolated values, never <code>null</code>.
@@ -60,11 +76,9 @@ class CompositeMap
* <code>null</code>.
* @param escapeXml {@code true}, to escape any XML special characters; {@code false}, to not perform any escaping.
*/
- protected CompositeMap( MavenProject mavenProject, Map<String, Object> properties, boolean escapeXml )
- {
- if ( mavenProject == null )
- {
- throw new IllegalArgumentException( "no project specified" );
+ protected CompositeMap(MavenProject mavenProject, Map<String, Object> properties, boolean escapeXml) {
+ if (mavenProject == null) {
+ throw new IllegalArgumentException("no project specified");
}
this.mavenProject = mavenProject;
this.properties = properties == null ? new HashMap<String, Object>() : properties;
@@ -76,8 +90,7 @@ class CompositeMap
*
* @see java.util.Map#clear()
*/
- public void clear()
- {
+ public void clear() {
// nothing here
}
@@ -86,31 +99,24 @@ class CompositeMap
*
* @see java.util.Map#containsKey(java.lang.Object)
*/
- public boolean containsKey( Object key )
- {
- if ( !( key instanceof String ) )
- {
+ public boolean containsKey(Object key) {
+ if (!(key instanceof String)) {
return false;
}
String expression = (String) key;
- if ( expression.startsWith( "project." ) || expression.startsWith( "pom." ) )
- {
- try
- {
- Object evaluated = ReflectionValueExtractor.evaluate( expression, this.mavenProject );
- if ( evaluated != null )
- {
+ if (expression.startsWith("project.") || expression.startsWith("pom.")) {
+ try {
+ Object evaluated = ReflectionValueExtractor.evaluate(expression, this.mavenProject);
+ if (evaluated != null) {
return true;
}
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
// uhm do we have to throw a RuntimeException here ?
}
}
- return properties.containsKey( key ) || mavenProject.getProperties().containsKey( key );
+ return properties.containsKey(key) || mavenProject.getProperties().containsKey(key);
}
/**
@@ -118,8 +124,7 @@ class CompositeMap
*
* @see java.util.Map#containsValue(java.lang.Object)
*/
- public boolean containsValue( Object value )
- {
+ public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
@@ -128,8 +133,7 @@ class CompositeMap
*
* @see java.util.Map#entrySet()
*/
- public Set<Entry<String, Object>> entrySet()
- {
+ public Set<Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException();
}
@@ -138,49 +142,38 @@ class CompositeMap
*
* @see java.util.Map#get(java.lang.Object)
*/
- public Object get( Object key )
- {
- if ( !( key instanceof String ) )
- {
+ public Object get(Object key) {
+ if (!(key instanceof String)) {
return null;
}
Object value = null;
String expression = (String) key;
- if ( expression.startsWith( "project." ) || expression.startsWith( "pom." ) )
- {
- try
- {
- Object evaluated = ReflectionValueExtractor.evaluate( expression, this.mavenProject );
- if ( evaluated != null )
- {
+ if (expression.startsWith("project.") || expression.startsWith("pom.")) {
+ try {
+ Object evaluated = ReflectionValueExtractor.evaluate(expression, this.mavenProject);
+ if (evaluated != null) {
value = evaluated;
}
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
// uhm do we have to throw a RuntimeException here ?
}
}
- if ( value == null )
- {
- value = properties.get( key );
+ if (value == null) {
+ value = properties.get(key);
}
- if ( value == null )
- {
- value = this.mavenProject.getProperties().get( key );
+ if (value == null) {
+ value = this.mavenProject.getProperties().get(key);
}
- if ( value != null && this.escapeXml )
- {
- value = value.toString().
- replaceAll( "\"", """ ).
- replaceAll( "<", "<" ).
- replaceAll( ">", ">" ).
- replaceAll( "&", "&" );
-
+ if (value != null && this.escapeXml) {
+ value = value.toString()
+ .replaceAll("\"", """)
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll("&", "&");
}
return value;
@@ -191,8 +184,7 @@ class CompositeMap
*
* @see java.util.Map#isEmpty()
*/
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return this.mavenProject.getProperties().isEmpty() && this.properties.isEmpty();
}
@@ -201,8 +193,7 @@ class CompositeMap
*
* @see java.util.Map#keySet()
*/
- public Set<String> keySet()
- {
+ public Set<String> keySet() {
throw new UnsupportedOperationException();
}
@@ -211,8 +202,7 @@ class CompositeMap
*
* @see java.util.Map#put(java.lang.Object, java.lang.Object)
*/
- public Object put( String key, Object value )
- {
+ public Object put(String key, Object value) {
throw new UnsupportedOperationException();
}
@@ -221,8 +211,7 @@ class CompositeMap
*
* @see java.util.Map#putAll(java.util.Map)
*/
- public void putAll( Map<? extends String, ? extends Object> t )
- {
+ public void putAll(Map<? extends String, ? extends Object> t) {
throw new UnsupportedOperationException();
}
@@ -231,8 +220,7 @@ class CompositeMap
*
* @see java.util.Map#remove(java.lang.Object)
*/
- public Object remove( Object key )
- {
+ public Object remove(Object key) {
throw new UnsupportedOperationException();
}
@@ -241,8 +229,7 @@ class CompositeMap
*
* @see java.util.Map#size()
*/
- public int size()
- {
+ public int size() {
throw new UnsupportedOperationException();
}
@@ -251,8 +238,7 @@ class CompositeMap
*
* @see java.util.Map#values()
*/
- public Collection<Object> values()
- {
+ public Collection<Object> values() {
throw new UnsupportedOperationException();
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/FileLogger.java b/src/main/java/org/apache/maven/plugins/invoker/FileLogger.java
index 4a7d3cb..059788b 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/FileLogger.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/FileLogger.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -28,10 +46,7 @@ import org.apache.maven.shared.invoker.InvocationOutputHandler;
/**
*
*/
-class FileLogger
- extends org.apache.maven.shared.scriptinterpreter.FileLogger
- implements InvocationOutputHandler
-{
+class FileLogger extends org.apache.maven.shared.scriptinterpreter.FileLogger implements InvocationOutputHandler {
/**
* Creates a new logger that writes to the specified file.
@@ -39,10 +54,8 @@ class FileLogger
* @param outputFile The path to the output file, must not be <code>null</code>.
* @throws IOException If the output file could not be created.
*/
- FileLogger( File outputFile )
- throws IOException
- {
- super( outputFile );
+ FileLogger(File outputFile) throws IOException {
+ super(outputFile);
}
/**
@@ -52,10 +65,7 @@ class FileLogger
* @param log The mojo logger to additionally output messages to, may be <code>null</code> if not used.
* @throws IOException If the output file could not be created.
*/
- FileLogger( File outputFile, final Log log )
- throws IOException
- {
- super( outputFile, log::info );
+ FileLogger(File outputFile, final Log log) throws IOException {
+ super(outputFile, log::info);
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/InstallMojo.java b/src/main/java/org/apache/maven/plugins/invoker/InstallMojo.java
index c00e41b..af82d45 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/InstallMojo.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/InstallMojo.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,7 +37,6 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
-
import java.io.File;
import java.io.IOException;
import java.util.Collection;
@@ -63,11 +80,13 @@ import org.codehaus.plexus.util.FileUtils;
*
*/
// CHECKSTYLE_OFF: LineLength
-@Mojo( name = "install", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true )
+@Mojo(
+ name = "install",
+ defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST,
+ requiresDependencyResolution = ResolutionScope.RUNTIME,
+ threadSafe = true)
// CHECKSTYLE_ON: LineLength
-public class InstallMojo
- extends AbstractMojo
-{
+public class InstallMojo extends AbstractMojo {
/**
* Maven artifact install component to copy artifacts to the local repository.
@@ -86,7 +105,7 @@ public class InstallMojo
/**
*/
- @Parameter( property = "localRepository", required = true, readonly = true )
+ @Parameter(property = "localRepository", required = true, readonly = true)
private ArtifactRepository localRepository;
/**
@@ -95,23 +114,25 @@ public class InstallMojo
* possibly broken artifacts, it is strongly recommended to use an isolated repository for the integration tests
* (e.g. <code>${project.build.directory}/it-repo</code>).
*/
- @Parameter( property = "invoker.localRepositoryPath",
- defaultValue = "${session.localRepository.basedir}", required = true )
+ @Parameter(
+ property = "invoker.localRepositoryPath",
+ defaultValue = "${session.localRepository.basedir}",
+ required = true)
private File localRepositoryPath;
/**
* The current Maven project.
*/
- @Parameter( defaultValue = "${project}", readonly = true, required = true )
+ @Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
- @Parameter( defaultValue = "${session}", readonly = true, required = true )
+ @Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
/**
* The set of Maven projects in the reactor build.
*/
- @Parameter( defaultValue = "${reactorProjects}", readonly = true )
+ @Parameter(defaultValue = "${reactorProjects}", readonly = true)
private Collection<MavenProject> reactorProjects;
/**
@@ -120,7 +141,7 @@ public class InstallMojo
*
* @since 1.4
*/
- @Parameter( property = "invoker.skip", defaultValue = "false" )
+ @Parameter(property = "invoker.skip", defaultValue = "false")
private boolean skipInstallation;
/**
@@ -161,13 +182,12 @@ public class InstallMojo
@Component
private DependencyResolver resolver;
-
/**
* if the local repository is not used as test repo, the parameter can force get artifacts from local repo
* if available instead of download the artifacts again.
* @since 3.2.1
*/
- @Parameter( property = "invoker.useLocalRepository", defaultValue = "false" )
+ @Parameter(property = "invoker.useLocalRepository", defaultValue = "false")
private boolean useLocalRepository;
private ProjectBuildingRequest projectBuildingRequest;
@@ -177,12 +197,9 @@ public class InstallMojo
*
* @throws MojoExecutionException If the artifacts could not be installed.
*/
- public void execute()
- throws MojoExecutionException
- {
- if ( skipInstallation )
- {
- getLog().info( "Skipping artifact installation per configuration." );
+ public void execute() throws MojoExecutionException {
+ if (skipInstallation) {
+ getLog().info("Skipping artifact installation per configuration.");
return;
}
@@ -191,11 +208,11 @@ public class InstallMojo
installedArtifacts = new HashSet<>();
copiedArtifacts = new HashSet<>();
- installProjectDependencies( project, reactorProjects );
- installProjectParents( project );
- installProjectArtifacts( project );
+ installProjectDependencies(project, reactorProjects);
+ installProjectParents(project);
+ installProjectArtifacts(project);
- installExtraArtifacts( extraArtifacts );
+ installExtraArtifacts(extraArtifacts);
}
/**
@@ -206,16 +223,13 @@ public class InstallMojo
*
* @throws MojoExecutionException If the repository could not be created.
*/
- private void createTestRepository()
- throws MojoExecutionException
- {
+ private void createTestRepository() throws MojoExecutionException {
- if ( !localRepositoryPath.exists() && !localRepositoryPath.mkdirs() )
- {
- throw new MojoExecutionException( "Failed to create directory: " + localRepositoryPath );
+ if (!localRepositoryPath.exists() && !localRepositoryPath.mkdirs()) {
+ throw new MojoExecutionException("Failed to create directory: " + localRepositoryPath);
}
projectBuildingRequest =
- repositoryManager.setLocalRepositoryBasedir( session.getProjectBuildingRequest(), localRepositoryPath );
+ repositoryManager.setLocalRepositoryBasedir(session.getProjectBuildingRequest(), localRepositoryPath);
}
/**
@@ -230,34 +244,23 @@ public class InstallMojo
* @param artifact The artifact to install, must not be <code>null</code>.
* @throws MojoExecutionException If the artifact could not be installed (e.g. has no associated file).
*/
- private void installArtifact( File file, Artifact artifact )
- throws MojoExecutionException
- {
- try
- {
- if ( file == null )
- {
- throw new IllegalStateException( "Artifact has no associated file: " + artifact.getId() );
+ private void installArtifact(File file, Artifact artifact) throws MojoExecutionException {
+ try {
+ if (file == null) {
+ throw new IllegalStateException("Artifact has no associated file: " + artifact.getId());
}
- if ( !file.isFile() )
- {
- throw new IllegalStateException( "Artifact is not fully assembled: " + file );
+ if (!file.isFile()) {
+ throw new IllegalStateException("Artifact is not fully assembled: " + file);
}
- if ( installedArtifacts.add( artifact.getId() ) )
- {
- artifact.setFile( file );
- installer.install( projectBuildingRequest, localRepositoryPath,
- Collections.singletonList( artifact ) );
- }
- else
- {
- getLog().debug( "Not re-installing " + artifact + ", " + file );
+ if (installedArtifacts.add(artifact.getId())) {
+ artifact.setFile(file);
+ installer.install(projectBuildingRequest, localRepositoryPath, Collections.singletonList(artifact));
+ } else {
+ getLog().debug("Not re-installing " + artifact + ", " + file);
}
- }
- catch ( Exception e )
- {
- throw new MojoExecutionException( "Failed to install artifact: " + artifact, e );
+ } catch (Exception e) {
+ throw new MojoExecutionException("Failed to install artifact: " + artifact, e);
}
}
@@ -272,50 +275,37 @@ public class InstallMojo
* @param artifact The artifact to install, must not be <code>null</code>.
* @throws MojoExecutionException If the artifact could not be installed (e.g. has no associated file).
*/
- private void copyArtifact( File file, Artifact artifact )
- throws MojoExecutionException
- {
- try
- {
- if ( file == null )
- {
- throw new IllegalStateException( "Artifact has no associated file: " + artifact.getId() );
+ private void copyArtifact(File file, Artifact artifact) throws MojoExecutionException {
+ try {
+ if (file == null) {
+ throw new IllegalStateException("Artifact has no associated file: " + artifact.getId());
}
- if ( !file.isFile() )
- {
- throw new IllegalStateException( "Artifact is not fully assembled: " + file );
+ if (!file.isFile()) {
+ throw new IllegalStateException("Artifact is not fully assembled: " + file);
}
- if ( copiedArtifacts.add( artifact.getId() ) )
- {
- File destination =
- new File( localRepositoryPath,
- repositoryManager.getPathForLocalArtifact( projectBuildingRequest, artifact ) );
+ if (copiedArtifacts.add(artifact.getId())) {
+ File destination = new File(
+ localRepositoryPath,
+ repositoryManager.getPathForLocalArtifact(projectBuildingRequest, artifact));
- getLog().debug( "Installing " + file + " to " + destination );
+ getLog().debug("Installing " + file + " to " + destination);
- copyFileIfDifferent( file, destination );
+ copyFileIfDifferent(file, destination);
- MetadataUtils.createMetadata( destination, artifact );
+ MetadataUtils.createMetadata(destination, artifact);
+ } else {
+ getLog().debug("Not re-installing " + artifact + ", " + file);
}
- else
- {
- getLog().debug( "Not re-installing " + artifact + ", " + file );
- }
- }
- catch ( Exception e )
- {
- throw new MojoExecutionException( "Failed to stage artifact: " + artifact, e );
+ } catch (Exception e) {
+ throw new MojoExecutionException("Failed to stage artifact: " + artifact, e);
}
}
- private void copyFileIfDifferent( File src, File dst )
- throws IOException
- {
- if ( src.lastModified() != dst.lastModified() || src.length() != dst.length() )
- {
- FileUtils.copyFile( src, dst );
- dst.setLastModified( src.lastModified() );
+ private void copyFileIfDifferent(File src, File dst) throws IOException {
+ if (src.lastModified() != dst.lastModified() || src.length() != dst.length()) {
+ FileUtils.copyFile(src, dst);
+ dst.setLastModified(src.lastModified());
}
}
@@ -325,31 +315,24 @@ public class InstallMojo
* @param mvnProject The project whose artifacts should be installed, must not be <code>null</code>.
* @throws MojoExecutionException If any artifact could not be installed.
*/
- private void installProjectArtifacts( MavenProject mvnProject )
- throws MojoExecutionException
- {
- try
- {
+ private void installProjectArtifacts(MavenProject mvnProject) throws MojoExecutionException {
+ try {
// Install POM (usually attached as metadata but that happens only as a side effect of the Install Plugin)
- installProjectPom( mvnProject );
+ installProjectPom(mvnProject);
// Install the main project artifact (if the project has one, e.g. has no "pom" packaging)
Artifact mainArtifact = mvnProject.getArtifact();
- if ( mainArtifact.getFile() != null )
- {
- installArtifact( mainArtifact.getFile(), mainArtifact );
+ if (mainArtifact.getFile() != null) {
+ installArtifact(mainArtifact.getFile(), mainArtifact);
}
// Install any attached project artifacts
Collection<Artifact> attachedArtifacts = mvnProject.getAttachedArtifacts();
- for ( Artifact attachedArtifact : attachedArtifacts )
- {
- installArtifact( attachedArtifact.getFile(), attachedArtifact );
+ for (Artifact attachedArtifact : attachedArtifacts) {
+ installArtifact(attachedArtifact.getFile(), attachedArtifact);
}
- }
- catch ( Exception e )
- {
- throw new MojoExecutionException( "Failed to install project artifacts: " + mvnProject, e );
+ } catch (Exception e) {
+ throw new MojoExecutionException("Failed to install project artifacts: " + mvnProject, e);
}
}
@@ -360,24 +343,17 @@ public class InstallMojo
* @param mvnProject The project whose parent POMs should be installed, must not be <code>null</code>.
* @throws MojoExecutionException If any POM could not be installed.
*/
- private void installProjectParents( MavenProject mvnProject )
- throws MojoExecutionException
- {
- try
- {
- for ( MavenProject parent = mvnProject.getParent(); parent != null; parent = parent.getParent() )
- {
- if ( parent.getFile() == null )
- {
- copyParentPoms( parent.getGroupId(), parent.getArtifactId(), parent.getVersion() );
+ private void installProjectParents(MavenProject mvnProject) throws MojoExecutionException {
+ try {
+ for (MavenProject parent = mvnProject.getParent(); parent != null; parent = parent.getParent()) {
+ if (parent.getFile() == null) {
+ copyParentPoms(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
break;
}
- installProjectPom( parent );
+ installProjectPom(parent);
}
- }
- catch ( Exception e )
- {
- throw new MojoExecutionException( "Failed to install project parents: " + mvnProject, e );
+ } catch (Exception e) {
+ throw new MojoExecutionException("Failed to install project parents: " + mvnProject, e);
}
}
@@ -387,27 +363,19 @@ public class InstallMojo
* @param mvnProject The project whose POM should be installed, must not be <code>null</code>.
* @throws MojoExecutionException If the POM could not be installed.
*/
- private void installProjectPom( MavenProject mvnProject )
- throws MojoExecutionException
- {
- try
- {
+ private void installProjectPom(MavenProject mvnProject) throws MojoExecutionException {
+ try {
Artifact pomArtifact = null;
- if ( "pom".equals( mvnProject.getPackaging() ) )
- {
+ if ("pom".equals(mvnProject.getPackaging())) {
pomArtifact = mvnProject.getArtifact();
}
- if ( pomArtifact == null )
- {
- pomArtifact =
- artifactFactory.createProjectArtifact( mvnProject.getGroupId(), mvnProject.getArtifactId(),
- mvnProject.getVersion() );
+ if (pomArtifact == null) {
+ pomArtifact = artifactFactory.createProjectArtifact(
+ mvnProject.getGroupId(), mvnProject.getArtifactId(), mvnProject.getVersion());
}
- installArtifact( mvnProject.getFile(), pomArtifact );
- }
- catch ( Exception e )
- {
- throw new MojoExecutionException( "Failed to install POM: " + mvnProject, e );
+ installArtifact(mvnProject.getFile(), pomArtifact);
+ } catch (Exception e) {
+ throw new MojoExecutionException("Failed to install POM: " + mvnProject, e);
}
}
@@ -419,21 +387,22 @@ public class InstallMojo
* @param reactorProjects The set of projects in the reactor build, must not be <code>null</code>.
* @throws MojoExecutionException If any dependency could not be installed.
*/
- private void installProjectDependencies( MavenProject mvnProject, Collection<MavenProject> reactorProjects )
- throws MojoExecutionException
- {
+ private void installProjectDependencies(MavenProject mvnProject, Collection<MavenProject> reactorProjects)
+ throws MojoExecutionException {
// ... into dependencies that were resolved from reactor projects ...
Collection<String> dependencyProjects = new LinkedHashSet<>();
- collectAllProjectReferences( mvnProject, dependencyProjects );
+ collectAllProjectReferences(mvnProject, dependencyProjects);
// index available reactor projects
- Map<String, MavenProject> projects = new HashMap<>( reactorProjects.size() );
- for ( MavenProject reactorProject : reactorProjects )
- {
- String projectId =
- reactorProject.getGroupId() + ':' + reactorProject.getArtifactId() + ':' + reactorProject.getVersion();
-
- projects.put( projectId, reactorProject );
+ Map<String, MavenProject> projects = new HashMap<>(reactorProjects.size());
+ for (MavenProject reactorProject : reactorProjects) {
+ String projectId = reactorProject.getGroupId()
+ + ':'
+ + reactorProject.getArtifactId()
+ + ':'
+ + reactorProject.getVersion();
+
+ projects.put(projectId, reactorProject);
}
// group transitive dependencies (even those that don't contribute to the class path like POMs) ...
@@ -441,88 +410,76 @@ public class InstallMojo
// ... and those that were resolved from the (local) repo
Collection<Artifact> dependencyArtifacts = new LinkedHashSet<>();
- for ( Artifact artifact : artifacts )
- {
+ for (Artifact artifact : artifacts) {
// workaround for MNG-2961 to ensure the base version does not contain a timestamp
artifact.isSnapshot();
String projectId = artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getBaseVersion();
- if ( !projects.containsKey( projectId ) )
- {
- dependencyArtifacts.add( artifact );
+ if (!projects.containsKey(projectId)) {
+ dependencyArtifacts.add(artifact);
}
}
// install dependencies
- try
- {
+ try {
// copy dependencies that where resolved from the local repo
- for ( Artifact artifact : dependencyArtifacts )
- {
- copyArtifact( artifact );
+ for (Artifact artifact : dependencyArtifacts) {
+ copyArtifact(artifact);
}
// install dependencies that were resolved from the reactor
- for ( String projectId : dependencyProjects )
- {
- MavenProject dependencyProject = projects.get( projectId );
- if ( dependencyProject == null )
- {
- getLog().warn( "skip dependencyProject null for projectId=" + projectId );
+ for (String projectId : dependencyProjects) {
+ MavenProject dependencyProject = projects.get(projectId);
+ if (dependencyProject == null) {
+ getLog().warn("skip dependencyProject null for projectId=" + projectId);
continue;
}
- installProjectArtifacts( dependencyProject );
- installProjectParents( dependencyProject );
+ installProjectArtifacts(dependencyProject);
+ installProjectParents(dependencyProject);
}
- }
- catch ( Exception e )
- {
- throw new MojoExecutionException( "Failed to install project dependencies: " + mvnProject, e );
+ } catch (Exception e) {
+ throw new MojoExecutionException("Failed to install project dependencies: " + mvnProject, e);
}
}
- protected void collectAllProjectReferences( MavenProject project, Collection<String> dependencyProjects )
- {
- for ( MavenProject reactorProject : project.getProjectReferences().values() )
- {
- String projectId =
- reactorProject.getGroupId() + ':' + reactorProject.getArtifactId() + ':' + reactorProject.getVersion();
- if ( dependencyProjects.add( projectId ) )
- {
- collectAllProjectReferences( reactorProject, dependencyProjects );
+ protected void collectAllProjectReferences(MavenProject project, Collection<String> dependencyProjects) {
+ for (MavenProject reactorProject : project.getProjectReferences().values()) {
+ String projectId = reactorProject.getGroupId()
+ + ':'
+ + reactorProject.getArtifactId()
+ + ':'
+ + reactorProject.getVersion();
+ if (dependencyProjects.add(projectId)) {
+ collectAllProjectReferences(reactorProject, dependencyProjects);
}
}
}
- private void copyArtifact( Artifact artifact )
- throws MojoExecutionException
- {
- copyPoms( artifact );
+ private void copyArtifact(Artifact artifact) throws MojoExecutionException {
+ copyPoms(artifact);
- Artifact depArtifact =
- artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(),
- artifact.getBaseVersion(), artifact.getType(),
- artifact.getClassifier() );
+ Artifact depArtifact = artifactFactory.createArtifactWithClassifier(
+ artifact.getGroupId(),
+ artifact.getArtifactId(),
+ artifact.getBaseVersion(),
+ artifact.getType(),
+ artifact.getClassifier());
File artifactFile = artifact.getFile();
- copyArtifact( artifactFile, depArtifact );
+ copyArtifact(artifactFile, depArtifact);
}
- private void copyPoms( Artifact artifact )
- throws MojoExecutionException
- {
- Artifact pomArtifact =
- artifactFactory.createProjectArtifact( artifact.getGroupId(), artifact.getArtifactId(),
- artifact.getBaseVersion() );
+ private void copyPoms(Artifact artifact) throws MojoExecutionException {
+ Artifact pomArtifact = artifactFactory.createProjectArtifact(
+ artifact.getGroupId(), artifact.getArtifactId(), artifact.getBaseVersion());
- File pomFile = new File( localRepository.getBasedir(), localRepository.pathOf( pomArtifact ) );
+ File pomFile = new File(localRepository.getBasedir(), localRepository.pathOf(pomArtifact));
- if ( pomFile.isFile() )
- {
- copyArtifact( pomFile, pomArtifact );
- copyParentPoms( pomFile );
+ if (pomFile.isFile()) {
+ copyArtifact(pomFile, pomArtifact);
+ copyParentPoms(pomFile);
}
}
@@ -532,14 +489,11 @@ public class InstallMojo
* @param pomFile The path to the POM file whose parents should be installed, must not be <code>null</code>.
* @throws MojoExecutionException If any (existing) parent POM could not be installed.
*/
- private void copyParentPoms( File pomFile )
- throws MojoExecutionException
- {
- Model model = PomUtils.loadPom( pomFile );
+ private void copyParentPoms(File pomFile) throws MojoExecutionException {
+ Model model = PomUtils.loadPom(pomFile);
Parent parent = model.getParent();
- if ( parent != null )
- {
- copyParentPoms( parent.getGroupId(), parent.getArtifactId(), parent.getVersion() );
+ if (parent != null) {
+ copyParentPoms(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
}
}
@@ -551,39 +505,30 @@ public class InstallMojo
* @param version The version of the POM which should be installed, must not be <code>null</code>.
* @throws MojoExecutionException If any (existing) parent POM could not be installed.
*/
- private void copyParentPoms( String groupId, String artifactId, String version )
- throws MojoExecutionException
- {
- Artifact pomArtifact = artifactFactory.createProjectArtifact( groupId, artifactId, version );
-
- if ( installedArtifacts.contains( pomArtifact.getId() ) || copiedArtifacts.contains( pomArtifact.getId() ) )
- {
- getLog().debug( "Not re-installing " + pomArtifact );
+ private void copyParentPoms(String groupId, String artifactId, String version) throws MojoExecutionException {
+ Artifact pomArtifact = artifactFactory.createProjectArtifact(groupId, artifactId, version);
+
+ if (installedArtifacts.contains(pomArtifact.getId()) || copiedArtifacts.contains(pomArtifact.getId())) {
+ getLog().debug("Not re-installing " + pomArtifact);
return;
}
- File pomFile = new File( localRepository.getBasedir(), localRepository.pathOf( pomArtifact ) );
- if ( pomFile.isFile() )
- {
- copyArtifact( pomFile, pomArtifact );
- copyParentPoms( pomFile );
+ File pomFile = new File(localRepository.getBasedir(), localRepository.pathOf(pomArtifact));
+ if (pomFile.isFile()) {
+ copyArtifact(pomFile, pomArtifact);
+ copyParentPoms(pomFile);
}
}
- private void installExtraArtifacts( String[] extraArtifacts )
- throws MojoExecutionException
- {
- if ( extraArtifacts == null )
- {
+ private void installExtraArtifacts(String[] extraArtifacts) throws MojoExecutionException {
+ if (extraArtifacts == null) {
return;
}
- for ( String extraArtifact : extraArtifacts )
- {
- String[] gav = extraArtifact.split( ":" );
- if ( gav.length < 3 || gav.length > 5 )
- {
- throw new MojoExecutionException( "Invalid artifact " + extraArtifact );
+ for (String extraArtifact : extraArtifacts) {
+ String[] gav = extraArtifact.split(":");
+ if (gav.length < 3 || gav.length > 5) {
+ throw new MojoExecutionException("Invalid artifact " + extraArtifact);
}
String groupId = gav[0];
@@ -591,56 +536,44 @@ public class InstallMojo
String version = gav[2];
String type = "jar";
- if ( gav.length > 3 )
- {
+ if (gav.length > 3) {
type = gav[3];
}
String classifier = null;
- if ( gav.length == 5 )
- {
+ if (gav.length == 5) {
classifier = gav[4];
}
DefaultDependableCoordinate coordinate = new DefaultDependableCoordinate();
- try
- {
- coordinate.setGroupId( groupId );
- coordinate.setArtifactId( artifactId );
- coordinate.setVersion( version );
- coordinate.setType( type );
- coordinate.setClassifier( classifier );
-
-
- if ( !localRepository.getBasedir().equals( localRepositoryPath.getPath() ) && useLocalRepository )
- {
+ try {
+ coordinate.setGroupId(groupId);
+ coordinate.setArtifactId(artifactId);
+ coordinate.setVersion(version);
+ coordinate.setType(type);
+ coordinate.setClassifier(classifier);
+
+ if (!localRepository.getBasedir().equals(localRepositoryPath.getPath()) && useLocalRepository) {
String previousId = localRepository.getId();
- try
- {
+ try {
// using another request with the correct target repo
- ProjectBuildingRequest projectBuildingRequest = repositoryManager
- .setLocalRepositoryBasedir( session.getProjectBuildingRequest(),
- localRepositoryPath );
- projectBuildingRequest.setRemoteRepositories( Collections.singletonList( localRepository ) );
- resolver.resolveDependencies( projectBuildingRequest, coordinate,
- new PatternExclusionsFilter( Collections.emptyList() ) );
+ ProjectBuildingRequest projectBuildingRequest = repositoryManager.setLocalRepositoryBasedir(
+ session.getProjectBuildingRequest(), localRepositoryPath);
+ projectBuildingRequest.setRemoteRepositories(Collections.singletonList(localRepository));
+ resolver.resolveDependencies(
+ projectBuildingRequest,
+ coordinate,
+ new PatternExclusionsFilter(Collections.emptyList()));
+ } finally {
+ localRepository.setId(previousId);
}
- finally
- {
- localRepository.setId( previousId );
- }
- }
- else
- {
- resolver.resolveDependencies( projectBuildingRequest, coordinate,
- new PatternExclusionsFilter( Collections.emptyList() ) );
+ } else {
+ resolver.resolveDependencies(
+ projectBuildingRequest, coordinate, new PatternExclusionsFilter(Collections.emptyList()));
}
- }
- catch ( DependencyResolverException e )
- {
- throw new MojoExecutionException( "Unable to resolve dependencies for: " + coordinate, e );
+ } catch (DependencyResolverException e) {
+ throw new MojoExecutionException("Unable to resolve dependencies for: " + coordinate, e);
}
}
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/IntegrationTestMojo.java b/src/main/java/org/apache/maven/plugins/invoker/IntegrationTestMojo.java
index 1765f43..d645696 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/IntegrationTestMojo.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/IntegrationTestMojo.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -32,16 +50,15 @@ import org.apache.maven.plugins.annotations.ResolutionScope;
* @author Stephen Connolly
*/
// CHECKSTYLE_OFF: LineLength
-@Mojo( name = "integration-test", defaultPhase = LifecyclePhase.INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true )
-public class IntegrationTestMojo
- extends AbstractInvokerMojo
-{
+@Mojo(
+ name = "integration-test",
+ defaultPhase = LifecyclePhase.INTEGRATION_TEST,
+ requiresDependencyResolution = ResolutionScope.TEST,
+ threadSafe = true)
+public class IntegrationTestMojo extends AbstractInvokerMojo {
- void processResults( InvokerSession invokerSession )
- throws MojoFailureException
- {
+ void processResults(InvokerSession invokerSession) throws MojoFailureException {
// do nothing
}
-
}
// CHECKSTYLE_ON: LineLength
diff --git a/src/main/java/org/apache/maven/plugins/invoker/InvokerMojo.java b/src/main/java/org/apache/maven/plugins/invoker/InvokerMojo.java
index af5d70e..c58ac2c 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/InvokerMojo.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/InvokerMojo.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -34,11 +52,13 @@ import org.apache.maven.plugins.annotations.ResolutionScope;
* @author <a href="mailto:jdcasey@apache.org">John Casey</a>
*/
// CHECKSTYLE_OFF: LineLength
-@Mojo( name = "run", defaultPhase = LifecyclePhase.INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true )
+@Mojo(
+ name = "run",
+ defaultPhase = LifecyclePhase.INTEGRATION_TEST,
+ requiresDependencyResolution = ResolutionScope.TEST,
+ threadSafe = true)
// CHECKSTYLE_ON: LineLength
-public class InvokerMojo
- extends AbstractInvokerMojo
-{
+public class InvokerMojo extends AbstractInvokerMojo {
/**
* A flag controlling whether failures of the sub builds should fail the main build, too. If set to
@@ -46,7 +66,7 @@ public class InvokerMojo
*
* @since 1.3
*/
- @Parameter( property = "maven.test.failure.ignore", defaultValue = "false" )
+ @Parameter(property = "maven.test.failure.ignore", defaultValue = "false")
private boolean ignoreFailures;
/**
@@ -54,7 +74,7 @@ public class InvokerMojo
*
* @since 1.9
*/
- @Parameter( property = "invoker.failIfNoProjects" )
+ @Parameter(property = "invoker.failIfNoProjects")
private Boolean failIfNoProjects;
/**
@@ -62,33 +82,25 @@ public class InvokerMojo
*
* @since 3.2.2
*/
- @Parameter( property = "invoker.streamLogsOnFailures", defaultValue = "false" )
+ @Parameter(property = "invoker.streamLogsOnFailures", defaultValue = "false")
private boolean streamLogsOnFailures;
- void processResults( InvokerSession invokerSession )
- throws MojoFailureException
- {
- if ( streamLogsOnFailures )
- {
- invokerSession.logFailedBuildLog( getLog(), ignoreFailures );
+ void processResults(InvokerSession invokerSession) throws MojoFailureException {
+ if (streamLogsOnFailures) {
+ invokerSession.logFailedBuildLog(getLog(), ignoreFailures);
}
- if ( !suppressSummaries )
- {
- invokerSession.logSummary( getLog(), ignoreFailures );
+ if (!suppressSummaries) {
+ invokerSession.logSummary(getLog(), ignoreFailures);
}
- invokerSession.handleFailures( getLog(), ignoreFailures );
+ invokerSession.handleFailures(getLog(), ignoreFailures);
}
@Override
- protected void doFailIfNoProjects()
- throws MojoFailureException
- {
- if ( Boolean.TRUE.equals( failIfNoProjects ) )
- {
- throw new MojoFailureException( "No projects to invoke!" );
+ protected void doFailIfNoProjects() throws MojoFailureException {
+ if (Boolean.TRUE.equals(failIfNoProjects)) {
+ throw new MojoFailureException("No projects to invoke!");
}
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/InvokerProperties.java b/src/main/java/org/apache/maven/plugins/invoker/InvokerProperties.java
index 048a8ac..4c5d30e 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/InvokerProperties.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/InvokerProperties.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -40,12 +58,11 @@ import org.codehaus.plexus.util.StringUtils;
*
* @author Benjamin Bentmann
*/
-class InvokerProperties
-{
+class InvokerProperties {
private static final String SELECTOR_PREFIX = "selector.";
private static final Pattern ENVIRONMENT_VARIABLES_PATTERN =
- Pattern.compile( "invoker\\.environmentVariables\\.([A-Za-z][^.]+)(\\.([0-9]+))?" );
+ Pattern.compile("invoker\\.environmentVariables\\.([A-Za-z][^.]+)(\\.([0-9]+))?");
// default values from Mojo configuration
private Boolean defaultDebug;
@@ -58,54 +75,48 @@ class InvokerProperties
private File defaultMavenExecutable;
private Boolean defaultUpdateSnapshots;
- private enum InvocationProperty
- {
- PROJECT( "invoker.project" ),
- BUILD_RESULT( "invoker.buildResult" ),
- GOALS( "invoker.goals" ),
- PROFILES( "invoker.profiles" ),
- MAVEN_EXECUTABLE( "invoker.mavenExecutable" ),
- MAVEN_OPTS( "invoker.mavenOpts" ),
- FAILURE_BEHAVIOR( "invoker.failureBehavior" ),
- NON_RECURSIVE( "invoker.nonRecursive" ),
- OFFLINE( "invoker.offline" ),
- SYSTEM_PROPERTIES_FILE( "invoker.systemPropertiesFile" ),
- DEBUG( "invoker.debug" ),
- QUIET( "invoker.quiet" ),
- SETTINGS_FILE( "invoker.settingsFile" ),
- TIMEOUT_IN_SECONDS( "invoker.timeoutInSeconds" ),
- UPDATE_SNAPSHOTS( "invoker.updateSnapshots" );
+ private enum InvocationProperty {
+ PROJECT("invoker.project"),
+ BUILD_RESULT("invoker.buildResult"),
+ GOALS("invoker.goals"),
+ PROFILES("invoker.profiles"),
+ MAVEN_EXECUTABLE("invoker.mavenExecutable"),
+ MAVEN_OPTS("invoker.mavenOpts"),
+ FAILURE_BEHAVIOR("invoker.failureBehavior"),
+ NON_RECURSIVE("invoker.nonRecursive"),
+ OFFLINE("invoker.offline"),
+ SYSTEM_PROPERTIES_FILE("invoker.systemPropertiesFile"),
+ DEBUG("invoker.debug"),
+ QUIET("invoker.quiet"),
+ SETTINGS_FILE("invoker.settingsFile"),
+ TIMEOUT_IN_SECONDS("invoker.timeoutInSeconds"),
+ UPDATE_SNAPSHOTS("invoker.updateSnapshots");
private final String key;
- InvocationProperty( final String s )
- {
+ InvocationProperty(final String s) {
this.key = s;
}
@Override
- public String toString()
- {
+ public String toString() {
return key;
}
}
- private enum SelectorProperty
- {
- JAVA_VERSION( ".java.version" ),
- MAVEN_VERSION( ".maven.version" ),
- OS_FAMLY( ".os.family" );
+ private enum SelectorProperty {
+ JAVA_VERSION(".java.version"),
+ MAVEN_VERSION(".maven.version"),
+ OS_FAMLY(".os.family");
private final String suffix;
- SelectorProperty( String suffix )
- {
+ SelectorProperty(String suffix) {
this.suffix = suffix;
}
@Override
- public String toString()
- {
+ public String toString() {
return suffix;
}
}
@@ -121,17 +132,15 @@ class InvokerProperties
*
* @param properties The invoker properties to wrap, may be <code>null</code> if none.
*/
- InvokerProperties( Properties properties )
- {
- this.properties = ( properties != null ) ? properties : new Properties();
+ InvokerProperties(Properties properties) {
+ this.properties = (properties != null) ? properties : new Properties();
}
/**
* Default value for debug
* @param defaultDebug a default value
*/
- public void setDefaultDebug( boolean defaultDebug )
- {
+ public void setDefaultDebug(boolean defaultDebug) {
this.defaultDebug = defaultDebug;
}
@@ -139,8 +148,7 @@ class InvokerProperties
* Default value for quiet
* @param defaultQuiet a default value
*/
- public void setDefaultQuiet( boolean defaultQuiet )
- {
+ public void setDefaultQuiet(boolean defaultQuiet) {
this.defaultQuiet = defaultQuiet;
}
@@ -148,8 +156,7 @@ class InvokerProperties
* Default value for goals
* @param defaultGoals a default value
*/
- public void setDefaultGoals( List<String> defaultGoals )
- {
+ public void setDefaultGoals(List<String> defaultGoals) {
this.defaultGoals = defaultGoals;
}
@@ -157,17 +164,15 @@ class InvokerProperties
* Default value for profiles
* @param defaultProfiles a default value
*/
- public void setDefaultProfiles( List<String> defaultProfiles )
- {
- this.defaultProfiles = defaultProfiles;
+ public void setDefaultProfiles(List<String> defaultProfiles) {
+ this.defaultProfiles = defaultProfiles;
}
/**
* Default value for mavenExecutable
* @param defaultMavenExecutable a default value
*/
- public void setDefaultMavenExecutable( File defaultMavenExecutable )
- {
+ public void setDefaultMavenExecutable(File defaultMavenExecutable) {
this.defaultMavenExecutable = defaultMavenExecutable;
}
@@ -175,8 +180,7 @@ class InvokerProperties
* Default value for mavenOpts
* @param defaultMavenOpts a default value
*/
- public void setDefaultMavenOpts( String defaultMavenOpts )
- {
+ public void setDefaultMavenOpts(String defaultMavenOpts) {
this.defaultMavenOpts = defaultMavenOpts;
}
@@ -184,8 +188,7 @@ class InvokerProperties
* Default value for timeoutInSeconds
* @param defaultTimeoutInSeconds a default value
*/
- public void setDefaultTimeoutInSeconds( int defaultTimeoutInSeconds )
- {
+ public void setDefaultTimeoutInSeconds(int defaultTimeoutInSeconds) {
this.defaultTimeoutInSeconds = defaultTimeoutInSeconds;
}
@@ -193,8 +196,7 @@ class InvokerProperties
* Default value for environmentVariables
* @param defaultEnvironmentVariables a default value
*/
- public void setDefaultEnvironmentVariables( Map<String, String> defaultEnvironmentVariables )
- {
+ public void setDefaultEnvironmentVariables(Map<String, String> defaultEnvironmentVariables) {
this.defaultEnvironmentVariables = defaultEnvironmentVariables;
}
@@ -202,8 +204,7 @@ class InvokerProperties
* Default value for updateSnapshots
* @param defaultUpdateSnapshots a default value
*/
- public void setDefaultUpdateSnapshots( boolean defaultUpdateSnapshots )
- {
+ public void setDefaultUpdateSnapshots(boolean defaultUpdateSnapshots) {
this.defaultUpdateSnapshots = defaultUpdateSnapshots;
}
@@ -212,8 +213,7 @@ class InvokerProperties
*
* @return The invoker properties being wrapped, never <code>null</code>.
*/
- public Properties getProperties()
- {
+ public Properties getProperties() {
return this.properties;
}
@@ -222,9 +222,8 @@ class InvokerProperties
*
* @return The name of the build job or an empty string if not set.
*/
- public String getJobName()
- {
- return this.properties.getProperty( "invoker.name", "" );
+ public String getJobName() {
+ return this.properties.getProperty("invoker.name", "");
}
/**
@@ -232,9 +231,8 @@ class InvokerProperties
*
* @return The description of the build job or an empty string if not set.
*/
- public String getJobDescription()
- {
- return this.properties.getProperty( "invoker.description", "" );
+ public String getJobDescription() {
+ return this.properties.getProperty("invoker.description", "");
}
/**
@@ -242,9 +240,8 @@ class InvokerProperties
*
* @return The ordinal value
*/
- public int getOrdinal()
- {
- return Integer.parseInt( this.properties.getProperty( "invoker.ordinal", "0" ) );
+ public int getOrdinal() {
+ return Integer.parseInt(this.properties.getProperty("invoker.ordinal", "0"));
}
/**
@@ -252,9 +249,8 @@ class InvokerProperties
*
* @return The specification of JRE versions or an empty string if not set.
*/
- public String getJreVersion()
- {
- return this.properties.getProperty( "invoker.java.version", "" );
+ public String getJreVersion() {
+ return this.properties.getProperty("invoker.java.version", "");
}
/**
@@ -262,10 +258,8 @@ class InvokerProperties
*
* @return The specification of JRE versions or an empty string if not set.
*/
- public String getJreVersion( int index )
- {
- return this.properties.getProperty( SELECTOR_PREFIX + index + SelectorProperty.JAVA_VERSION,
- getJreVersion() );
+ public String getJreVersion(int index) {
+ return this.properties.getProperty(SELECTOR_PREFIX + index + SelectorProperty.JAVA_VERSION, getJreVersion());
}
/**
@@ -274,9 +268,8 @@ class InvokerProperties
* @return The specification of Maven versions on which this build job should be run.
* @since 1.5
*/
- public String getMavenVersion()
- {
- return this.properties.getProperty( "invoker.maven.version", "" );
+ public String getMavenVersion() {
+ return this.properties.getProperty("invoker.maven.version", "");
}
/**
@@ -284,10 +277,8 @@ class InvokerProperties
* @return The specification of Maven versions on which this build job should be run.
* @since 3.0.0
*/
- public String getMavenVersion( int index )
- {
- return this.properties.getProperty( SELECTOR_PREFIX + index + SelectorProperty.MAVEN_VERSION,
- getMavenVersion() );
+ public String getMavenVersion(int index) {
+ return this.properties.getProperty(SELECTOR_PREFIX + index + SelectorProperty.MAVEN_VERSION, getMavenVersion());
}
/**
@@ -295,9 +286,8 @@ class InvokerProperties
*
* @return The specification of OS families or an empty string if not set.
*/
- public String getOsFamily()
- {
- return this.properties.getProperty( "invoker.os.family", "" );
+ public String getOsFamily() {
+ return this.properties.getProperty("invoker.os.family", "");
}
/**
@@ -307,40 +297,33 @@ class InvokerProperties
* @return The specification of OS families or an empty string if not set.
* @since 3.0.0
*/
- public String getOsFamily( int index )
- {
- return this.properties.getProperty( SELECTOR_PREFIX + index + SelectorProperty.OS_FAMLY, getOsFamily() );
+ public String getOsFamily(int index) {
+ return this.properties.getProperty(SELECTOR_PREFIX + index + SelectorProperty.OS_FAMLY, getOsFamily());
}
- public Collection<InvokerToolchain> getToolchains()
- {
- return getToolchains( Pattern.compile( "invoker\\.toolchain\\.([^.]+)\\.(.+)" ) );
+ public Collection<InvokerToolchain> getToolchains() {
+ return getToolchains(Pattern.compile("invoker\\.toolchain\\.([^.]+)\\.(.+)"));
}
- public Collection<InvokerToolchain> getToolchains( int index )
- {
- return getToolchains( Pattern.compile( "selector\\." + index + "\\.invoker\\.toolchain\\.([^.]+)\\.(.+)" ) );
+ public Collection<InvokerToolchain> getToolchains(int index) {
+ return getToolchains(Pattern.compile("selector\\." + index + "\\.invoker\\.toolchain\\.([^.]+)\\.(.+)"));
}
- private Collection<InvokerToolchain> getToolchains( Pattern p )
- {
+ private Collection<InvokerToolchain> getToolchains(Pattern p) {
Map<String, InvokerToolchain> toolchains = new HashMap<>();
- for ( Map.Entry<Object, Object> entry : this.properties.entrySet() )
- {
- Matcher m = p.matcher( entry.getKey().toString() );
- if ( m.matches() )
- {
- String type = m.group( 1 );
- String providesKey = m.group( 2 );
+ for (Map.Entry<Object, Object> entry : this.properties.entrySet()) {
+ Matcher m = p.matcher(entry.getKey().toString());
+ if (m.matches()) {
+ String type = m.group(1);
+ String providesKey = m.group(2);
String providesValue = entry.getValue().toString();
- InvokerToolchain tc = toolchains.get( type );
- if ( tc == null )
- {
- tc = new InvokerToolchain( type );
- toolchains.put( type, tc );
+ InvokerToolchain tc = toolchains.get(type);
+ if (tc == null) {
+ tc = new InvokerToolchain(type);
+ toolchains.put(type, tc);
}
- tc.addProvides( providesKey, providesValue );
+ tc.addProvides(providesKey, providesValue);
}
}
return toolchains.values();
@@ -353,29 +336,22 @@ class InvokerProperties
* @param index index to lookup
* @return map of environment name and value
*/
-
- private Map<String, String> getEnvironmentVariables( int index )
- {
+ private Map<String, String> getEnvironmentVariables(int index) {
Map<String, String> envItems = new HashMap<>();
- for ( Map.Entry<Object, Object> entry : properties.entrySet() )
- {
- Matcher matcher = ENVIRONMENT_VARIABLES_PATTERN.matcher( entry.getKey().toString() );
- if ( matcher.matches() )
- {
+ for (Map.Entry<Object, Object> entry : properties.entrySet()) {
+ Matcher matcher =
+ ENVIRONMENT_VARIABLES_PATTERN.matcher(entry.getKey().toString());
+ if (matcher.matches()) {
- if ( String.valueOf( index ).equals( matcher.group( 3 ) ) )
- {
+ if (String.valueOf(index).equals(matcher.group(3))) {
// variables with index has higher priority, so override
- envItems.put( matcher.group( 1 ), entry.getValue().toString() );
- }
- else if ( matcher.group( 3 ) == null )
- {
+ envItems.put(matcher.group(1), entry.getValue().toString());
+ } else if (matcher.group(3) == null) {
// variables without index has lower priority, so check if exist
- if ( !envItems.containsKey( matcher.group( 1 ) ) )
- {
- envItems.put( matcher.group( 1 ), entry.getValue().toString() );
+ if (!envItems.containsKey(matcher.group(1))) {
+ envItems.put(matcher.group(1), entry.getValue().toString());
}
}
}
@@ -389,12 +365,11 @@ class InvokerProperties
* @param index The one-based index of the invocation to check for, must not be negative.
* @return <code>true</code> if the invocation with the specified index is defined, <code>false</code> otherwise.
*/
- public boolean isInvocationDefined( int index )
- {
- return Arrays.stream( InvocationProperty.values() )
- .map( InvocationProperty::toString )
- .map( v -> properties.getProperty( v + '.' + index ) )
- .anyMatch( Objects::nonNull );
+ public boolean isInvocationDefined(int index) {
+ return Arrays.stream(InvocationProperty.values())
+ .map(InvocationProperty::toString)
+ .map(v -> properties.getProperty(v + '.' + index))
+ .anyMatch(Objects::nonNull);
}
/**
@@ -404,19 +379,16 @@ class InvokerProperties
* @return <code>true</code> if the selector with the specified index is defined, <code>false</code> otherwise.
* @since 3.0.0
*/
- public boolean isSelectorDefined( int index )
- {
- return Arrays.stream( SelectorProperty.values() )
- .map( v -> v.suffix )
- .map( v -> properties.getProperty( SELECTOR_PREFIX + index + v ) )
- .anyMatch( Objects::nonNull );
- }
-
- private <T> void setIfNotNull( Consumer<T> consumer, T value )
- {
- if ( value != null )
- {
- consumer.accept( value );
+ public boolean isSelectorDefined(int index) {
+ return Arrays.stream(SelectorProperty.values())
+ .map(v -> v.suffix)
+ .map(v -> properties.getProperty(SELECTOR_PREFIX + index + v))
+ .anyMatch(Objects::nonNull);
+ }
+
+ private <T> void setIfNotNull(Consumer<T> consumer, T value) {
+ if (value != null) {
+ consumer.accept(value);
}
}
@@ -427,75 +399,75 @@ class InvokerProperties
* @param request The invocation request to configure, must not be <code>null</code>.
* @param index The one-based index of the invocation to configure, must not be negative.
*/
- public void configureInvocation( InvocationRequest request, int index )
- {
- get( InvocationProperty.PROJECT, index ).ifPresent( project ->
- {
- File file = new File( request.getBaseDirectory(), project );
- if ( file.isFile() )
- {
- request.setBaseDirectory( file.getParentFile() );
- request.setPomFile( file );
- }
- else
- {
- request.setBaseDirectory( file );
- request.setPomFile( null );
+ public void configureInvocation(InvocationRequest request, int index) {
+ get(InvocationProperty.PROJECT, index).ifPresent(project -> {
+ File file = new File(request.getBaseDirectory(), project);
+ if (file.isFile()) {
+ request.setBaseDirectory(file.getParentFile());
+ request.setPomFile(file);
+ } else {
+ request.setBaseDirectory(file);
+ request.setPomFile(null);
}
- } );
+ });
- setIfNotNull( request::setGoals, get( InvocationProperty.GOALS, index )
- .map( s -> StringUtils.split( s, ", \t\n\r\f" ) )
- .map( Arrays::asList )
- .filter( l -> !l.isEmpty() )
- .orElse( defaultGoals ) );
+ setIfNotNull(
+ request::setGoals,
+ get(InvocationProperty.GOALS, index)
+ .map(s -> StringUtils.split(s, ", \t\n\r\f"))
+ .map(Arrays::asList)
+ .filter(l -> !l.isEmpty())
+ .orElse(defaultGoals));
- setIfNotNull( request::setProfiles, get( InvocationProperty.PROFILES, index )
- .map( s -> StringUtils.split( s, ", \t\n\r\f" ) )
- .map( Arrays::asList )
- .filter( l -> !l.isEmpty() )
- .orElse( defaultProfiles ) );
+ setIfNotNull(
+ request::setProfiles,
+ get(InvocationProperty.PROFILES, index)
+ .map(s -> StringUtils.split(s, ", \t\n\r\f"))
+ .map(Arrays::asList)
+ .filter(l -> !l.isEmpty())
+ .orElse(defaultProfiles));
- setIfNotNull( request::setMavenExecutable, get( InvocationProperty.MAVEN_EXECUTABLE, index )
- .map( File::new )
- .orElse( defaultMavenExecutable ) );
+ setIfNotNull(
+ request::setMavenExecutable,
+ get(InvocationProperty.MAVEN_EXECUTABLE, index).map(File::new).orElse(defaultMavenExecutable));
- setIfNotNull( request::setMavenOpts, get( InvocationProperty.MAVEN_OPTS, index ).orElse( defaultMavenOpts ) );
+ setIfNotNull(
+ request::setMavenOpts, get(InvocationProperty.MAVEN_OPTS, index).orElse(defaultMavenOpts));
- get( InvocationProperty.FAILURE_BEHAVIOR, index )
- .map( InvocationRequest.ReactorFailureBehavior::valueOfByLongOption )
- .ifPresent( request::setReactorFailureBehavior );
+ get(InvocationProperty.FAILURE_BEHAVIOR, index)
+ .map(InvocationRequest.ReactorFailureBehavior::valueOfByLongOption)
+ .ifPresent(request::setReactorFailureBehavior);
- get( InvocationProperty.NON_RECURSIVE, index )
- .map( Boolean::parseBoolean )
- .map( b -> !b )
- .ifPresent( request::setRecursive );
+ get(InvocationProperty.NON_RECURSIVE, index)
+ .map(Boolean::parseBoolean)
+ .map(b -> !b)
+ .ifPresent(request::setRecursive);
- get( InvocationProperty.OFFLINE, index )
- .map( Boolean::parseBoolean )
- .ifPresent( request::setOffline );
+ get(InvocationProperty.OFFLINE, index).map(Boolean::parseBoolean).ifPresent(request::setOffline);
- setIfNotNull( request::setDebug, get( InvocationProperty.DEBUG, index )
- .map( Boolean::parseBoolean )
- .orElse( defaultDebug ) );
+ setIfNotNull(
+ request::setDebug,
+ get(InvocationProperty.DEBUG, index).map(Boolean::parseBoolean).orElse(defaultDebug));
- setIfNotNull( request::setQuiet, get( InvocationProperty.QUIET, index )
- .map( Boolean::parseBoolean )
- .orElse( defaultQuiet ) );
+ setIfNotNull(
+ request::setQuiet,
+ get(InvocationProperty.QUIET, index).map(Boolean::parseBoolean).orElse(defaultQuiet));
- setIfNotNull( request::setTimeoutInSeconds, get( InvocationProperty.TIMEOUT_IN_SECONDS, index )
- .map( Integer::parseInt )
- .orElse( defaultTimeoutInSeconds ) );
+ setIfNotNull(
+ request::setTimeoutInSeconds,
+ get(InvocationProperty.TIMEOUT_IN_SECONDS, index)
+ .map(Integer::parseInt)
+ .orElse(defaultTimeoutInSeconds));
- setIfNotNull( request::setUpdateSnapshots, get( InvocationProperty.UPDATE_SNAPSHOTS, index )
- .map( Boolean::parseBoolean )
- .orElse( defaultUpdateSnapshots ) );
+ setIfNotNull(
+ request::setUpdateSnapshots,
+ get(InvocationProperty.UPDATE_SNAPSHOTS, index)
+ .map(Boolean::parseBoolean)
+ .orElse(defaultUpdateSnapshots));
- Optional.ofNullable( defaultEnvironmentVariables )
- .ifPresent( evn -> evn.forEach( request::addShellEnvironment ) );
+ Optional.ofNullable(defaultEnvironmentVariables).ifPresent(evn -> evn.forEach(request::addShellEnvironment));
- getEnvironmentVariables( index )
- .forEach( request::addShellEnvironment );
+ getEnvironmentVariables(index).forEach(request::addShellEnvironment);
}
/**
@@ -506,11 +478,10 @@ class InvokerProperties
* @return <code>true</code> if the exit code is zero and a success was expected or if the exit code is non-zero and
* a failue was expected, <code>false</code> otherwise.
*/
- public boolean isExpectedResult( int exitCode, int index )
- {
- boolean nonZeroExit = "failure".equalsIgnoreCase(
- get( InvocationProperty.BUILD_RESULT, index ).orElse( null ) );
- return ( exitCode != 0 ) == nonZeroExit;
+ public boolean isExpectedResult(int exitCode, int index) {
+ boolean nonZeroExit = "failure"
+ .equalsIgnoreCase(get(InvocationProperty.BUILD_RESULT, index).orElse(null));
+ return (exitCode != 0) == nonZeroExit;
}
/**
@@ -519,9 +490,8 @@ class InvokerProperties
* @param index The index of the invocation, must not be negative.
* @return The path to the properties file or <code>null</code> if not set.
*/
- public String getSystemPropertiesFile( int index )
- {
- return get( InvocationProperty.SYSTEM_PROPERTIES_FILE, index ).orElse( null );
+ public String getSystemPropertiesFile(int index) {
+ return get(InvocationProperty.SYSTEM_PROPERTIES_FILE, index).orElse(null);
}
/**
@@ -530,9 +500,8 @@ class InvokerProperties
* @param index The index of the invocation, must not be negative.
* @return the value for the settings file or <code>null</code> if not set.
*/
- public String getSettingsFile( int index )
- {
- return get( InvocationProperty.SETTINGS_FILE, index ).orElse( null );
+ public String getSettingsFile(int index) {
+ return get(InvocationProperty.SETTINGS_FILE, index).orElse(null);
}
/**
@@ -545,24 +514,19 @@ class InvokerProperties
* @param index The index of the invocation for which to retrieve the value, must not be negative.
* @return The value for the requested invoker property or <code>null</code> if not defined.
*/
- Optional<String> get( String key, int index )
- {
- if ( index < 0 )
- {
- throw new IllegalArgumentException( "invalid invocation index: " + index );
+ Optional<String> get(String key, int index) {
+ if (index < 0) {
+ throw new IllegalArgumentException("invalid invocation index: " + index);
}
// lookup in properties
- String value = Optional.ofNullable( properties.getProperty( key + '.' + index ) )
- .orElseGet( () -> properties.getProperty( key ) );
+ String value = Optional.ofNullable(properties.getProperty(key + '.' + index))
+ .orElseGet(() -> properties.getProperty(key));
- return Optional.ofNullable( value )
- .map( String::trim )
- .filter( s -> !s.isEmpty() );
+ return Optional.ofNullable(value).map(String::trim).filter(s -> !s.isEmpty());
}
- private Optional<String> get( InvocationProperty prop, int index )
- {
- return get( prop.toString(), index );
+ private Optional<String> get(InvocationProperty prop, int index) {
+ return get(prop.toString(), index);
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/InvokerReport.java b/src/main/java/org/apache/maven/plugins/invoker/InvokerReport.java
index 71fff65..fb3b224 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/InvokerReport.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/InvokerReport.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -30,11 +48,11 @@ import java.util.List;
import java.util.Locale;
import org.apache.maven.doxia.sink.Sink;
-import org.apache.maven.plugins.invoker.model.BuildJob;
-import org.apache.maven.plugins.invoker.model.io.xpp3.BuildJobXpp3Reader;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.plugins.invoker.model.BuildJob;
+import org.apache.maven.plugins.invoker.model.io.xpp3.BuildJobXpp3Reader;
import org.apache.maven.reporting.AbstractMavenReport;
import org.apache.maven.reporting.MavenReportException;
import org.codehaus.plexus.i18n.I18N;
@@ -51,10 +69,8 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
* @author Olivier Lamy
* @since 1.4
*/
-@Mojo( name = "report", threadSafe = true )
-public class InvokerReport
- extends AbstractMavenReport
-{
+@Mojo(name = "report", threadSafe = true)
+public class InvokerReport extends AbstractMavenReport {
/**
* Internationalization component.
@@ -65,7 +81,7 @@ public class InvokerReport
/**
* Base directory where all build reports have been written to.
*/
- @Parameter( defaultValue = "${project.build.directory}/invoker-reports", property = "invoker.reportsDirectory" )
+ @Parameter(defaultValue = "${project.build.directory}/invoker-reports", property = "invoker.reportsDirectory")
private File reportsDirectory;
/**
@@ -83,21 +99,18 @@ public class InvokerReport
*/
private MessageFormat nameAndDescriptionFormat;
- protected void executeReport( Locale locale )
- throws MavenReportException
- {
- DecimalFormatSymbols symbols = new DecimalFormatSymbols( locale );
- percentFormat = new DecimalFormat( getText( locale, "report.invoker.format.percent" ), symbols );
- secondsFormat = new DecimalFormat( getText( locale, "report.invoker.format.seconds" ), symbols );
- nameAndDescriptionFormat =
- new MessageFormat( getText( locale, "report.invoker.format.name_with_description" ) );
+ protected void executeReport(Locale locale) throws MavenReportException {
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
+ percentFormat = new DecimalFormat(getText(locale, "report.invoker.format.percent"), symbols);
+ secondsFormat = new DecimalFormat(getText(locale, "report.invoker.format.seconds"), symbols);
+ nameAndDescriptionFormat = new MessageFormat(getText(locale, "report.invoker.format.name_with_description"));
Sink sink = getSink();
sink.head();
sink.title();
- sink.text( getText( locale, "report.invoker.result.title" ) );
+ sink.text(getText(locale, "report.invoker.result.title"));
sink.title_();
sink.head_();
@@ -106,39 +119,32 @@ public class InvokerReport
sink.section1();
sink.sectionTitle1();
- sink.text( getText( locale, "report.invoker.result.title" ) );
+ sink.text(getText(locale, "report.invoker.result.title"));
sink.sectionTitle1_();
sink.paragraph();
- sink.text( getText( locale, "report.invoker.result.description" ) );
+ sink.text(getText(locale, "report.invoker.result.description"));
sink.paragraph_();
sink.section1_();
// ----------------------------------
// build buildJob beans
// ----------------------------------
- File[] reportFiles = ReportUtils.getReportFiles( reportsDirectory );
- if ( reportFiles.length <= 0 )
- {
- getLog().info( "no invoker report files found, skip report generation" );
+ File[] reportFiles = ReportUtils.getReportFiles(reportsDirectory);
+ if (reportFiles.length <= 0) {
+ getLog().info("no invoker report files found, skip report generation");
return;
}
BuildJobXpp3Reader buildJobReader = new BuildJobXpp3Reader();
- List<BuildJob> buildJobs = new ArrayList<>( reportFiles.length );
- for ( File reportFile : reportFiles )
- {
- try ( XmlStreamReader xmlReader = ReaderFactory.newXmlReader( reportFile ) )
- {
- buildJobs.add( buildJobReader.read( xmlReader ) );
- }
- catch ( XmlPullParserException e )
- {
- throw new MavenReportException( "Failed to parse report file: " + reportFile, e );
- }
- catch ( IOException e )
- {
- throw new MavenReportException( "Failed to read report file: " + reportFile, e );
+ List<BuildJob> buildJobs = new ArrayList<>(reportFiles.length);
+ for (File reportFile : reportFiles) {
+ try (XmlStreamReader xmlReader = ReaderFactory.newXmlReader(reportFile)) {
+ buildJobs.add(buildJobReader.read(xmlReader));
+ } catch (XmlPullParserException e) {
+ throw new MavenReportException("Failed to parse report file: " + reportFile, e);
+ } catch (IOException e) {
+ throw new MavenReportException("Failed to read report file: " + reportFile, e);
}
}
@@ -146,7 +152,7 @@ public class InvokerReport
// summary
// ----------------------------------
- constructSummarySection( buildJobs, locale );
+ constructSummarySection(buildJobs, locale);
// ----------------------------------
// per file/it detail
@@ -155,7 +161,7 @@ public class InvokerReport
sink.section2();
sink.sectionTitle2();
- sink.text( getText( locale, "report.invoker.detail.title" ) );
+ sink.text(getText(locale, "report.invoker.detail.title"));
sink.sectionTitle2_();
@@ -163,22 +169,21 @@ public class InvokerReport
// detail tests table header
sink.table();
- sink.tableRows( null, false );
+ sink.tableRows(null, false);
sink.tableRow();
// -------------------------------------------
// name | Result | time | message
// -------------------------------------------
- sinkTableHeader( sink, getText( locale, "report.invoker.detail.name" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.detail.result" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.detail.time" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.detail.message" ) );
+ sinkTableHeader(sink, getText(locale, "report.invoker.detail.name"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.detail.result"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.detail.time"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.detail.message"));
sink.tableRow_();
- for ( BuildJob buildJob : buildJobs )
- {
- renderBuildJob( buildJob );
+ for (BuildJob buildJob : buildJobs) {
+ renderBuildJob(buildJob);
}
sink.tableRows_();
@@ -190,14 +195,13 @@ public class InvokerReport
sink.close();
}
- private void constructSummarySection( List<? extends BuildJob> buildJobs, Locale locale )
- {
+ private void constructSummarySection(List<? extends BuildJob> buildJobs, Locale locale) {
Sink sink = getSink();
sink.section2();
sink.sectionTitle2();
- sink.text( getText( locale, "report.invoker.summary.title" ) );
+ sink.text(getText(locale, "report.invoker.summary.title"));
sink.sectionTitle2_();
sink.section2_();
@@ -208,17 +212,17 @@ public class InvokerReport
// ------------------------------------------------------------------------
sink.table();
- sink.tableRows( null, false );
+ sink.tableRows(null, false);
sink.tableRow();
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.number" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.success" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.failed" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.skipped" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.success.rate" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.time.total" ) );
- sinkTableHeader( sink, getText( locale, "report.invoker.summary.time.avg" ) );
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.number"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.success"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.failed"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.skipped"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.success.rate"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.time.total"));
+ sinkTableHeader(sink, getText(locale, "report.invoker.summary.time.avg"));
int number = buildJobs.size();
int success = 0;
@@ -226,18 +230,12 @@ public class InvokerReport
int skipped = 0;
double totalTime = 0;
- for ( BuildJob buildJob : buildJobs )
- {
- if ( BuildJob.Result.SUCCESS.equals( buildJob.getResult() ) )
- {
+ for (BuildJob buildJob : buildJobs) {
+ if (BuildJob.Result.SUCCESS.equals(buildJob.getResult())) {
success++;
- }
- else if ( BuildJob.Result.SKIPPED.equals( buildJob.getResult() ) )
- {
+ } else if (BuildJob.Result.SKIPPED.equals(buildJob.getResult())) {
skipped++;
- }
- else
- {
+ } else {
failed++;
}
totalTime += buildJob.getTime();
@@ -246,118 +244,96 @@ public class InvokerReport
sink.tableRow_();
sink.tableRow();
- sinkCell( sink, Integer.toString( number ) );
- sinkCell( sink, Integer.toString( success ) );
- sinkCell( sink, Integer.toString( failed ) );
- sinkCell( sink, Integer.toString( skipped ) );
+ sinkCell(sink, Integer.toString(number));
+ sinkCell(sink, Integer.toString(success));
+ sinkCell(sink, Integer.toString(failed));
+ sinkCell(sink, Integer.toString(skipped));
- if ( success + failed > 0 )
- {
- sinkCell( sink, percentFormat.format( (double) success / ( success + failed ) ) );
- }
- else
- {
- sinkCell( sink, "" );
+ if (success + failed > 0) {
+ sinkCell(sink, percentFormat.format((double) success / (success + failed)));
+ } else {
+ sinkCell(sink, "");
}
- sinkCell( sink, secondsFormat.format( totalTime ) );
+ sinkCell(sink, secondsFormat.format(totalTime));
- sinkCell( sink, secondsFormat.format( totalTime / number ) );
+ sinkCell(sink, secondsFormat.format(totalTime / number));
sink.tableRow_();
sink.tableRows_();
sink.table_();
-
}
- private void renderBuildJob( BuildJob buildJob )
- {
+ private void renderBuildJob(BuildJob buildJob) {
Sink sink = getSink();
sink.tableRow();
- sinkCell( sink, getBuildJobReportName( buildJob ) );
+ sinkCell(sink, getBuildJobReportName(buildJob));
// FIXME image
- sinkCell( sink, buildJob.getResult() );
- sinkCell( sink, secondsFormat.format( buildJob.getTime() ) );
- sinkCell( sink, buildJob.getFailureMessage() );
+ sinkCell(sink, buildJob.getResult());
+ sinkCell(sink, secondsFormat.format(buildJob.getTime()));
+ sinkCell(sink, buildJob.getFailureMessage());
sink.tableRow_();
}
- private String getBuildJobReportName( BuildJob buildJob )
- {
+ private String getBuildJobReportName(BuildJob buildJob) {
String buildJobName = buildJob.getName();
String buildJobDescription = buildJob.getDescription();
- boolean emptyJobName = StringUtils.isEmpty( buildJobName );
- boolean emptyJobDescription = StringUtils.isEmpty( buildJobDescription );
+ boolean emptyJobName = StringUtils.isEmpty(buildJobName);
+ boolean emptyJobDescription = StringUtils.isEmpty(buildJobDescription);
boolean isReportJobNameComplete = !emptyJobName && !emptyJobDescription;
- if ( isReportJobNameComplete )
- {
- return getFormattedName( buildJobName, buildJobDescription );
- }
- else
- {
+ if (isReportJobNameComplete) {
+ return getFormattedName(buildJobName, buildJobDescription);
+ } else {
String buildJobProject = buildJob.getProject();
- if ( !emptyJobName )
- {
- getLog().warn( incompleteNameWarning( "description", buildJobProject ) );
- }
- else if ( !emptyJobDescription )
- {
- getLog().warn( incompleteNameWarning( "name", buildJobProject ) );
+ if (!emptyJobName) {
+ getLog().warn(incompleteNameWarning("description", buildJobProject));
+ } else if (!emptyJobDescription) {
+ getLog().warn(incompleteNameWarning("name", buildJobProject));
}
return buildJobProject;
}
}
- private static String incompleteNameWarning( String missing, String pom )
- {
- return String.format( "Incomplete job name-description: %s is missing. "
- + "POM (%s) will be used in place of job name.",
- missing, pom );
+ private static String incompleteNameWarning(String missing, String pom) {
+ return String.format(
+ "Incomplete job name-description: %s is missing. " + "POM (%s) will be used in place of job name.",
+ missing, pom);
}
- private String getFormattedName( String name, String description )
- {
- return nameAndDescriptionFormat.format( new Object[] { name, description } );
+ private String getFormattedName(String name, String description) {
+ return nameAndDescriptionFormat.format(new Object[] {name, description});
}
- public String getDescription( Locale locale )
- {
- return getText( locale, "report.invoker.result.description" );
+ public String getDescription(Locale locale) {
+ return getText(locale, "report.invoker.result.description");
}
- public String getName( Locale locale )
- {
- return getText( locale, "report.invoker.result.name" );
+ public String getName(Locale locale) {
+ return getText(locale, "report.invoker.result.name");
}
- public String getOutputName()
- {
+ public String getOutputName() {
return "invoker-report";
}
- public boolean canGenerateReport()
- {
- return ReportUtils.getReportFiles( reportsDirectory ).length > 0;
+ public boolean canGenerateReport() {
+ return ReportUtils.getReportFiles(reportsDirectory).length > 0;
}
- private String getText( Locale locale, String key )
- {
- return i18n.getString( "invoker-report", locale, key );
+ private String getText(Locale locale, String key) {
+ return i18n.getString("invoker-report", locale, key);
}
- private void sinkTableHeader( Sink sink, String header )
- {
+ private void sinkTableHeader(Sink sink, String header) {
sink.tableHeaderCell();
- sink.text( header );
+ sink.text(header);
sink.tableHeaderCell_();
}
- private void sinkCell( Sink sink, String text )
- {
+ private void sinkCell(Sink sink, String text) {
sink.tableCell();
- sink.text( text );
+ sink.text(text);
sink.tableCell_();
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/InvokerSession.java b/src/main/java/org/apache/maven/plugins/invoker/InvokerSession.java
index 27eb321..7b5b295 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/InvokerSession.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/InvokerSession.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,8 +37,6 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
-import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
-
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@@ -28,19 +44,20 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugins.invoker.model.BuildJob;
import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.plugins.invoker.model.BuildJob;
import org.apache.maven.shared.utils.io.IOUtil;
+import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
+
/**
* Tracks a set of build jobs and their results.
*
* @author Benjamin Bentmann
*/
-class InvokerSession
-{
- private static final String SEPARATOR = buffer().strong(
- "-------------------------------------------------" ).toString();
+class InvokerSession {
+ private static final String SEPARATOR =
+ buffer().strong("-------------------------------------------------").toString();
private List<BuildJob> buildJobs;
@@ -55,8 +72,7 @@ class InvokerSession
/**
* Creates a new empty session.
*/
- InvokerSession()
- {
+ InvokerSession() {
buildJobs = new ArrayList<>();
}
@@ -65,9 +81,8 @@ class InvokerSession
*
* @param buildJobs The build jobs to set, must not be <code>null</code>.
*/
- InvokerSession( List<BuildJob> buildJobs )
- {
- this.buildJobs = new ArrayList<>( buildJobs );
+ InvokerSession(List<BuildJob> buildJobs) {
+ this.buildJobs = new ArrayList<>(buildJobs);
}
/**
@@ -75,9 +90,8 @@ class InvokerSession
*
* @param buildJob The build job to add, must not be <code>null</code>.
*/
- public void addJob( BuildJob buildJob )
- {
- buildJobs.add( buildJob );
+ public void addJob(BuildJob buildJob) {
+ buildJobs.add(buildJob);
resetStats();
}
@@ -87,9 +101,8 @@ class InvokerSession
*
* @param buildJobs The build jobs to set, must not be <code>null</code>.
*/
- public void setJobs( List<? extends BuildJob> buildJobs )
- {
- this.buildJobs = new ArrayList<>( buildJobs );
+ public void setJobs(List<? extends BuildJob> buildJobs) {
+ this.buildJobs = new ArrayList<>(buildJobs);
resetStats();
}
@@ -99,8 +112,7 @@ class InvokerSession
*
* @return The build jobs in this session, can be empty but never <code>null</code>.
*/
- public List<BuildJob> getJobs()
- {
+ public List<BuildJob> getJobs() {
return buildJobs;
}
@@ -109,8 +121,7 @@ class InvokerSession
*
* @return The successful build jobs in this session, can be empty but never <code>null</code>.
*/
- public List<BuildJob> getSuccessfulJobs()
- {
+ public List<BuildJob> getSuccessfulJobs() {
updateStats();
return successfulJobs;
@@ -121,8 +132,7 @@ class InvokerSession
*
* @return The failed build jobs in this session, can be empty but never <code>null</code>.
*/
- public List<BuildJob> getFailedJobs()
- {
+ public List<BuildJob> getFailedJobs() {
updateStats();
return failedJobs;
@@ -133,8 +143,7 @@ class InvokerSession
*
* @return The build jobs in error for this session, can be empty but never <code>null</code>.
*/
- public List<BuildJob> getErrorJobs()
- {
+ public List<BuildJob> getErrorJobs() {
updateStats();
return errorJobs;
@@ -145,25 +154,21 @@ class InvokerSession
*
* @return The skipped build jobs in this session, can be empty but never <code>null</code>.
*/
- public List<BuildJob> getSkippedJobs()
- {
+ public List<BuildJob> getSkippedJobs() {
updateStats();
return skippedJobs;
}
- private void resetStats()
- {
+ private void resetStats() {
successfulJobs = null;
failedJobs = null;
skippedJobs = null;
errorJobs = null;
}
- private void updateStats()
- {
- if ( successfulJobs != null && skippedJobs != null && failedJobs != null && errorJobs != null )
- {
+ private void updateStats() {
+ if (successfulJobs != null && skippedJobs != null && failedJobs != null && errorJobs != null) {
return;
}
@@ -172,23 +177,15 @@ class InvokerSession
skippedJobs = new ArrayList<>();
errorJobs = new ArrayList<>();
- for ( BuildJob buildJob : buildJobs )
- {
- if ( BuildJob.Result.SUCCESS.equals( buildJob.getResult() ) )
- {
- successfulJobs.add( buildJob );
- }
- else if ( BuildJob.Result.SKIPPED.equals( buildJob.getResult() ) )
- {
- skippedJobs.add( buildJob );
- }
- else if ( BuildJob.Result.ERROR.equals( buildJob.getResult() ) )
- {
- errorJobs.add( buildJob );
- }
- else if ( buildJob.getResult() != null )
- {
- failedJobs.add( buildJob );
+ for (BuildJob buildJob : buildJobs) {
+ if (BuildJob.Result.SUCCESS.equals(buildJob.getResult())) {
+ successfulJobs.add(buildJob);
+ } else if (BuildJob.Result.SKIPPED.equals(buildJob.getResult())) {
+ skippedJobs.add(buildJob);
+ } else if (BuildJob.Result.ERROR.equals(buildJob.getResult())) {
+ errorJobs.add(buildJob);
+ } else if (buildJob.getResult() != null) {
+ failedJobs.add(buildJob);
}
}
}
@@ -199,67 +196,57 @@ class InvokerSession
* @param logger The mojo logger to output messages to, must not be <code>null</code>.
* @param ignoreFailures A flag whether failures should be ignored or whether a build failure should be signaled.
*/
- public void logSummary( Log logger, boolean ignoreFailures )
- {
+ public void logSummary(Log logger, boolean ignoreFailures) {
updateStats();
- logger.info( SEPARATOR );
- logger.info( "Build Summary:" );
- logger.info( " Passed: " + successfulJobs.size()
+ logger.info(SEPARATOR);
+ logger.info("Build Summary:");
+ logger.info(" Passed: " + successfulJobs.size()
+ ", Failed: " + failedJobs.size()
+ ", Errors: " + errorJobs.size()
- + ", Skipped: " + skippedJobs.size() );
- logger.info( SEPARATOR );
+ + ", Skipped: " + skippedJobs.size());
+ logger.info(SEPARATOR);
- logBuildJobList( logger, ignoreFailures, "The following builds failed:", failedJobs );
- logBuildJobList( logger, ignoreFailures, "The following builds finished with error:", errorJobs );
- logBuildJobList( logger, true, "The following builds were skipped:", skippedJobs );
+ logBuildJobList(logger, ignoreFailures, "The following builds failed:", failedJobs);
+ logBuildJobList(logger, ignoreFailures, "The following builds finished with error:", errorJobs);
+ logBuildJobList(logger, true, "The following builds were skipped:", skippedJobs);
}
- public void logFailedBuildLog( Log logger, boolean ignoreFailures )
- throws MojoFailureException
- {
+ public void logFailedBuildLog(Log logger, boolean ignoreFailures) throws MojoFailureException {
updateStats();
- List<BuildJob> jobToLogs = new ArrayList<>( failedJobs );
- jobToLogs.addAll( errorJobs );
+ List<BuildJob> jobToLogs = new ArrayList<>(failedJobs);
+ jobToLogs.addAll(errorJobs);
- for ( BuildJob buildJob: jobToLogs )
- {
- File buildLogFile = buildJob.getBuildlog() != null ? new File( buildJob.getBuildlog() ) : null;
- if ( buildLogFile != null && buildLogFile.exists() )
- {
- try
- {
+ for (BuildJob buildJob : jobToLogs) {
+ File buildLogFile = buildJob.getBuildlog() != null ? new File(buildJob.getBuildlog()) : null;
+ if (buildLogFile != null && buildLogFile.exists()) {
+ try {
// prepare message with build.log in one string to omit begin [ERROR], [WARN]
// so whole log will be displayed without decoration
- StringBuilder buildLogMessage = new StringBuilder( );
- buildLogMessage.append( System.lineSeparator() );
- buildLogMessage.append( System.lineSeparator() );
- buildLogMessage.append( "*** begin build.log for: " + buildJob.getProject() + " ***" );
- buildLogMessage.append( System.lineSeparator() );
- try ( FileReader buildLogReader = new FileReader( buildLogFile ) )
- {
- buildLogMessage.append( IOUtil.toString( buildLogReader ) );
+ StringBuilder buildLogMessage = new StringBuilder();
+ buildLogMessage.append(System.lineSeparator());
+ buildLogMessage.append(System.lineSeparator());
+ buildLogMessage.append("*** begin build.log for: " + buildJob.getProject() + " ***");
+ buildLogMessage.append(System.lineSeparator());
+ try (FileReader buildLogReader = new FileReader(buildLogFile)) {
+ buildLogMessage.append(IOUtil.toString(buildLogReader));
}
- buildLogMessage.append( "*** end build.log for: " + buildJob.getProject() + " ***" );
- buildLogMessage.append( System.lineSeparator() );
+ buildLogMessage.append("*** end build.log for: " + buildJob.getProject() + " ***");
+ buildLogMessage.append(System.lineSeparator());
- logWithLevel( logger, ignoreFailures, SEPARATOR );
- logWithLevel( logger, ignoreFailures, buildLogMessage.toString() );
- logWithLevel( logger, ignoreFailures, SEPARATOR );
- logWithLevel( logger, ignoreFailures, "" );
+ logWithLevel(logger, ignoreFailures, SEPARATOR);
+ logWithLevel(logger, ignoreFailures, buildLogMessage.toString());
+ logWithLevel(logger, ignoreFailures, SEPARATOR);
+ logWithLevel(logger, ignoreFailures, "");
- }
- catch ( IOException e )
- {
- throw new MojoFailureException( e.getMessage(), e );
+ } catch (IOException e) {
+ throw new MojoFailureException(e.getMessage(), e);
}
}
}
}
-
/**
* Handles the build failures in this session.
*
@@ -267,36 +254,26 @@ class InvokerSession
* @param ignoreFailures A flag whether failures should be ignored or whether a build failure should be signaled.
* @throws MojoFailureException If failures are present and not ignored.
*/
- public void handleFailures( Log logger, boolean ignoreFailures )
- throws MojoFailureException
- {
+ public void handleFailures(Log logger, boolean ignoreFailures) throws MojoFailureException {
updateStats();
- if ( !failedJobs.isEmpty() )
- {
- String message = failedJobs.size() + " build" + ( failedJobs.size() == 1 ? "" : "s" ) + " failed.";
+ if (!failedJobs.isEmpty()) {
+ String message = failedJobs.size() + " build" + (failedJobs.size() == 1 ? "" : "s") + " failed.";
- if ( ignoreFailures )
- {
- logger.warn( "Ignoring that " + message );
- }
- else
- {
- throw new MojoFailureException( message + " See console output above for details." );
+ if (ignoreFailures) {
+ logger.warn("Ignoring that " + message);
+ } else {
+ throw new MojoFailureException(message + " See console output above for details.");
}
}
- if ( !errorJobs.isEmpty() )
- {
- String message = errorJobs.size() + " build" + ( errorJobs.size() == 1 ? "" : "s" ) + " in error.";
+ if (!errorJobs.isEmpty()) {
+ String message = errorJobs.size() + " build" + (errorJobs.size() == 1 ? "" : "s") + " in error.";
- if ( ignoreFailures )
- {
- logger.warn( "Ignoring that " + message );
- }
- else
- {
- throw new MojoFailureException( message + " See console output above for details." );
+ if (ignoreFailures) {
+ logger.warn("Ignoring that " + message);
+ } else {
+ throw new MojoFailureException(message + " See console output above for details.");
}
}
}
@@ -308,21 +285,18 @@ class InvokerSession
* @param warn flag indicate log level
* @param buildJobs jobs to list
*/
- private void logBuildJobList( Log logger, boolean warn, String header, List<BuildJob> buildJobs )
- {
- if ( buildJobs.isEmpty() )
- {
+ private void logBuildJobList(Log logger, boolean warn, String header, List<BuildJob> buildJobs) {
+ if (buildJobs.isEmpty()) {
return;
}
- logWithLevel( logger, warn, header );
+ logWithLevel(logger, warn, header);
- for ( BuildJob buildJob : buildJobs )
- {
- logWithLevel( logger, warn, "* " + buildJob.getProject() );
+ for (BuildJob buildJob : buildJobs) {
+ logWithLevel(logger, warn, "* " + buildJob.getProject());
}
- logger.info( SEPARATOR );
+ logger.info(SEPARATOR);
}
/**
@@ -332,16 +306,12 @@ class InvokerSession
* @param warn flag indicate log level
* @param message message to write
*/
- private void logWithLevel( Log logger, boolean warn, String message )
- {
+ private void logWithLevel(Log logger, boolean warn, String message) {
- if ( warn )
- {
- logger.warn( message );
- }
- else
- {
- logger.error( message );
+ if (warn) {
+ logger.warn(message);
+ } else {
+ logger.error(message);
}
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/InvokerToolchain.java b/src/main/java/org/apache/maven/plugins/invoker/InvokerToolchain.java
index ec8f06f..18f5139 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/InvokerToolchain.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/InvokerToolchain.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -27,29 +45,24 @@ import java.util.Map;
* @author Robert Scholte
* @since 3.2.0
*/
-public class InvokerToolchain
-{
+public class InvokerToolchain {
private final String type;
private Map<String, String> provides = new HashMap<>();
- public InvokerToolchain( String type )
- {
+ public InvokerToolchain(String type) {
this.type = type;
}
- public String getType()
- {
+ public String getType() {
return type;
}
- public void addProvides( String key, String value )
- {
- provides.put( key, value );
+ public void addProvides(String key, String value) {
+ provides.put(key, value);
}
- public Map<String, String> getProvides()
- {
+ public Map<String, String> getProvides() {
return provides;
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/JobExecutor.java b/src/main/java/org/apache/maven/plugins/invoker/JobExecutor.java
index 71ea13c..1badddd 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/JobExecutor.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/JobExecutor.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -34,58 +52,48 @@ import org.apache.maven.plugins.invoker.model.BuildJob;
*
* @author Slawomir Jaranowski
*/
-class JobExecutor
-{
- interface ThrowableJobConsumer
- {
- void accept( BuildJob t ) throws Throwable;
+class JobExecutor {
+ interface ThrowableJobConsumer {
+ void accept(BuildJob t) throws Throwable;
}
private final List<BuildJob> jobs;
private final int threadsCount;
- JobExecutor( List<BuildJob> jobs, int threadsCount )
- {
+ JobExecutor(List<BuildJob> jobs, int threadsCount) {
this.jobs = jobs;
this.threadsCount = threadsCount;
}
- public void forEach( ThrowableJobConsumer jobConsumer )
- {
+ public void forEach(ThrowableJobConsumer jobConsumer) {
// group and sort jobs by ordinal
Map<Integer, List<BuildJob>> groupedJobs = jobs.stream()
- .sorted( ( j1, j2 ) -> Integer.compare( j2.getOrdinal(), j1.getOrdinal() ) )
- .collect( Collectors.groupingBy( BuildJob::getOrdinal, LinkedHashMap::new, Collectors.toList() ) );
+ .sorted((j1, j2) -> Integer.compare(j2.getOrdinal(), j1.getOrdinal()))
+ .collect(Collectors.groupingBy(BuildJob::getOrdinal, LinkedHashMap::new, Collectors.toList()));
- ExecutorService executorService = Executors.newFixedThreadPool( threadsCount );
+ ExecutorService executorService = Executors.newFixedThreadPool(threadsCount);
- groupedJobs.forEach( ( key, value ) ->
- {
+ groupedJobs.forEach((key, value) -> {
// prepare list of callable tasks
- List<Callable<Void>> callableJobs = value.stream().map( buildJob -> (Callable<Void>) () ->
- {
- try
- {
- jobConsumer.accept( buildJob );
- }
- catch ( Throwable e )
- {
- buildJob.setResult( BuildJob.Result.ERROR );
- buildJob.setFailureMessage( String.valueOf( e ) );
- }
- return null;
- } ).collect( Collectors.toList() );
+ List<Callable<Void>> callableJobs = value.stream()
+ .map(buildJob -> (Callable<Void>) () -> {
+ try {
+ jobConsumer.accept(buildJob);
+ } catch (Throwable e) {
+ buildJob.setResult(BuildJob.Result.ERROR);
+ buildJob.setFailureMessage(String.valueOf(e));
+ }
+ return null;
+ })
+ .collect(Collectors.toList());
- try
- {
- executorService.invokeAll( callableJobs );
- }
- catch ( InterruptedException e )
- {
+ try {
+ executorService.invokeAll(callableJobs);
+ } catch (InterruptedException e) {
Thread.currentThread().interrupt();
- throw new RuntimeException( e );
+ throw new RuntimeException(e);
}
- } );
+ });
// all task are finished here
executorService.shutdownNow();
diff --git a/src/main/java/org/apache/maven/plugins/invoker/MetadataUtils.java b/src/main/java/org/apache/maven/plugins/invoker/MetadataUtils.java
index 6588b97..a5762be 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/MetadataUtils.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/MetadataUtils.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -44,8 +62,7 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
*
* @author Benjamin Bentmann
*/
-class MetadataUtils
-{
+class MetadataUtils {
/**
* Creates local metadata files for the specified artifact. The goal is to simulate the installation of the artifact
@@ -56,113 +73,93 @@ class MetadataUtils
* @param artifact The artifact to create metadata for, must not be <code>null</code>.
* @throws IOException If the metadata could not be created.
*/
- public static void createMetadata( File file, Artifact artifact )
- throws IOException
- {
- TimeZone tz = java.util.TimeZone.getTimeZone( "UTC" );
- SimpleDateFormat fmt = new SimpleDateFormat( "yyyyMMddHHmmss" );
- fmt.setTimeZone( tz );
- String timestamp = fmt.format( new Date() );
-
- if ( artifact.isSnapshot() )
- {
- File metadataFile = new File( file.getParentFile(), "maven-metadata-local.xml" );
-
- Xpp3Dom metadata = new Xpp3Dom( "metadata" );
- addChild( metadata, "groupId", artifact.getGroupId() );
- addChild( metadata, "artifactId", artifact.getArtifactId() );
- addChild( metadata, "version", artifact.getBaseVersion() );
- Xpp3Dom versioning = new Xpp3Dom( "versioning" );
- versioning.addChild( addChild( new Xpp3Dom( "snapshot" ), "localCopy", "true" ) );
- addChild( versioning, "lastUpdated", timestamp );
- metadata.addChild( versioning );
-
- writeMetadata( metadataFile, metadata );
+ public static void createMetadata(File file, Artifact artifact) throws IOException {
+ TimeZone tz = java.util.TimeZone.getTimeZone("UTC");
+ SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
+ fmt.setTimeZone(tz);
+ String timestamp = fmt.format(new Date());
+
+ if (artifact.isSnapshot()) {
+ File metadataFile = new File(file.getParentFile(), "maven-metadata-local.xml");
+
+ Xpp3Dom metadata = new Xpp3Dom("metadata");
+ addChild(metadata, "groupId", artifact.getGroupId());
+ addChild(metadata, "artifactId", artifact.getArtifactId());
+ addChild(metadata, "version", artifact.getBaseVersion());
+ Xpp3Dom versioning = new Xpp3Dom("versioning");
+ versioning.addChild(addChild(new Xpp3Dom("snapshot"), "localCopy", "true"));
+ addChild(versioning, "lastUpdated", timestamp);
+ metadata.addChild(versioning);
+
+ writeMetadata(metadataFile, metadata);
}
- File metadataFile = new File( file.getParentFile().getParentFile(), "maven-metadata-local.xml" );
+ File metadataFile = new File(file.getParentFile().getParentFile(), "maven-metadata-local.xml");
Set<String> allVersions = new LinkedHashSet<>();
- Xpp3Dom metadata = readMetadata( metadataFile );
-
- if ( metadata != null )
- {
- Xpp3Dom versioning = metadata.getChild( "versioning" );
- if ( versioning != null )
- {
- Xpp3Dom versions = versioning.getChild( "versions" );
- if ( versions != null )
- {
-
- Xpp3Dom[] children = versions.getChildren( "version" );
- for ( Xpp3Dom aChildren : children )
- {
- allVersions.add( aChildren.getValue() );
+ Xpp3Dom metadata = readMetadata(metadataFile);
+
+ if (metadata != null) {
+ Xpp3Dom versioning = metadata.getChild("versioning");
+ if (versioning != null) {
+ Xpp3Dom versions = versioning.getChild("versions");
+ if (versions != null) {
+
+ Xpp3Dom[] children = versions.getChildren("version");
+ for (Xpp3Dom aChildren : children) {
+ allVersions.add(aChildren.getValue());
}
}
}
}
- allVersions.add( artifact.getBaseVersion() );
+ allVersions.add(artifact.getBaseVersion());
- metadata = new Xpp3Dom( "metadata" );
- addChild( metadata, "groupId", artifact.getGroupId() );
- addChild( metadata, "artifactId", artifact.getArtifactId() );
- Xpp3Dom versioning = new Xpp3Dom( "versioning" );
- versioning.addChild( addChildren( new Xpp3Dom( "versions" ), "version", allVersions ) );
- addChild( versioning, "lastUpdated", timestamp );
- metadata.addChild( versioning );
+ metadata = new Xpp3Dom("metadata");
+ addChild(metadata, "groupId", artifact.getGroupId());
+ addChild(metadata, "artifactId", artifact.getArtifactId());
+ Xpp3Dom versioning = new Xpp3Dom("versioning");
+ versioning.addChild(addChildren(new Xpp3Dom("versions"), "version", allVersions));
+ addChild(versioning, "lastUpdated", timestamp);
+ metadata.addChild(versioning);
- metadata = Xpp3DomUtils.mergeXpp3Dom( metadata, readMetadata( metadataFile ) );
+ metadata = Xpp3DomUtils.mergeXpp3Dom(metadata, readMetadata(metadataFile));
- writeMetadata( metadataFile, metadata );
+ writeMetadata(metadataFile, metadata);
}
- private static Xpp3Dom addChild( Xpp3Dom parent, String childName, String childValue )
- {
- Xpp3Dom child = new Xpp3Dom( childName );
- child.setValue( childValue );
- parent.addChild( child );
+ private static Xpp3Dom addChild(Xpp3Dom parent, String childName, String childValue) {
+ Xpp3Dom child = new Xpp3Dom(childName);
+ child.setValue(childValue);
+ parent.addChild(child);
return parent;
}
- private static Xpp3Dom addChildren( Xpp3Dom parent, String childName, Collection<String> childValues )
- {
- for ( String childValue : childValues )
- {
- addChild( parent, childName, childValue );
+ private static Xpp3Dom addChildren(Xpp3Dom parent, String childName, Collection<String> childValues) {
+ for (String childValue : childValues) {
+ addChild(parent, childName, childValue);
}
return parent;
}
- private static Xpp3Dom readMetadata( File metadataFile )
- throws IOException
- {
- if ( !metadataFile.isFile() )
- {
+ private static Xpp3Dom readMetadata(File metadataFile) throws IOException {
+ if (!metadataFile.isFile()) {
return null;
}
- try ( Reader reader = ReaderFactory.newXmlReader( metadataFile ) )
- {
- return Xpp3DomBuilder.build( reader );
- }
- catch ( XmlPullParserException e )
- {
- throw new IOException( e.getMessage(), e );
+ try (Reader reader = ReaderFactory.newXmlReader(metadataFile)) {
+ return Xpp3DomBuilder.build(reader);
+ } catch (XmlPullParserException e) {
+ throw new IOException(e.getMessage(), e);
}
}
- private static void writeMetadata( File metadataFile, Xpp3Dom metadata )
- throws IOException
- {
+ private static void writeMetadata(File metadataFile, Xpp3Dom metadata) throws IOException {
metadataFile.getParentFile().mkdirs();
- try ( Writer writer = WriterFactory.newXmlWriter( metadataFile ) )
- {
- Xpp3DomWriter.write( writer, metadata );
+ try (Writer writer = WriterFactory.newXmlWriter(metadataFile)) {
+ Xpp3DomWriter.write(writer, metadata);
}
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/PomUtils.java b/src/main/java/org/apache/maven/plugins/invoker/PomUtils.java
index 7ebc02d..32952d4 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/PomUtils.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/PomUtils.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -34,8 +52,7 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
*
* @author Benjamin Bentmann
*/
-class PomUtils
-{
+class PomUtils {
/**
* Loads the (raw) model from the specified POM file.
@@ -44,21 +61,13 @@ class PomUtils
* @return The raw model, never <code>null</code>.
* @throws MojoExecutionException If the POM file could not be loaded.
*/
- public static Model loadPom( File pomFile )
- throws MojoExecutionException
- {
- try ( Reader reader = ReaderFactory.newXmlReader( pomFile ) )
- {
- return new MavenXpp3Reader().read( reader, false );
- }
- catch ( XmlPullParserException e )
- {
- throw new MojoExecutionException( "Failed to parse POM: " + pomFile, e );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to read POM: " + pomFile, e );
+ public static Model loadPom(File pomFile) throws MojoExecutionException {
+ try (Reader reader = ReaderFactory.newXmlReader(pomFile)) {
+ return new MavenXpp3Reader().read(reader, false);
+ } catch (XmlPullParserException e) {
+ throw new MojoExecutionException("Failed to parse POM: " + pomFile, e);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to read POM: " + pomFile, e);
}
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/ReportUtils.java b/src/main/java/org/apache/maven/plugins/invoker/ReportUtils.java
index e0bf651..48d1fd9 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/ReportUtils.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/ReportUtils.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -27,18 +45,13 @@ import java.io.FilenameFilter;
*
* @author Benjamin Bentmann
*/
-class ReportUtils
-{
+class ReportUtils {
- private static class FileFilterOnlyXmlFile
- implements FilenameFilter
- {
+ private static class FileFilterOnlyXmlFile implements FilenameFilter {
- public boolean accept( File dir, String name )
- {
- return name.startsWith( "BUILD-" ) && name.endsWith( ".xml" );
+ public boolean accept(File dir, String name) {
+ return name.startsWith("BUILD-") && name.endsWith(".xml");
}
-
}
/**
@@ -47,17 +60,14 @@ class ReportUtils
* @param reportsDirectory The base directory where the invoker reports are located in, may be <code>null</code>.
* @return The paths to the invoker reports, can be empty but never <code>null</code>.
*/
- public static File[] getReportFiles( File reportsDirectory )
- {
+ public static File[] getReportFiles(File reportsDirectory) {
File[] reportFiles =
- ( reportsDirectory != null ) ? reportsDirectory.listFiles( new FileFilterOnlyXmlFile() ) : null;
+ (reportsDirectory != null) ? reportsDirectory.listFiles(new FileFilterOnlyXmlFile()) : null;
- if ( reportFiles == null )
- {
+ if (reportFiles == null) {
reportFiles = new File[0];
}
return reportFiles;
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/RunFailureException.java b/src/main/java/org/apache/maven/plugins/invoker/RunFailureException.java
index 1966fc6..6241970 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/RunFailureException.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/RunFailureException.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -24,32 +42,26 @@ package org.apache.maven.plugins.invoker;
*
* @author Slawomir Jaranowski
*/
-public class RunFailureException extends Exception
-{
+public class RunFailureException extends Exception {
private final String type;
- public RunFailureException( String message, String type )
- {
- super( message );
+ public RunFailureException(String message, String type) {
+ super(message);
this.type = type;
}
- public RunFailureException( String type, Throwable cause )
- {
- super( cause );
+ public RunFailureException(String type, Throwable cause) {
+ super(cause);
this.type = type;
-
}
- public RunFailureException( String message, String type, Throwable cause )
- {
- super( message, cause );
+ public RunFailureException(String message, String type, Throwable cause) {
+ super(message, cause);
this.type = type;
}
- public String getType()
- {
+ public String getType() {
return type;
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/Selector.java b/src/main/java/org/apache/maven/plugins/invoker/Selector.java
index 6f6cfba..03c7199 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/Selector.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/Selector.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -26,8 +44,7 @@ import org.apache.maven.plugins.invoker.AbstractInvokerMojo.ToolchainPrivateMana
* @author Robert Scholte
*
*/
-class Selector
-{
+class Selector {
static final int SELECTOR_MAVENVERSION = 1;
static final int SELECTOR_JREVERSION = 2;
@@ -44,52 +61,40 @@ class Selector
private final ToolchainPrivateManager toolchainPrivateManager;
- Selector( String actualMavenVersion, String actualJavaVersion, ToolchainPrivateManager toolchainPrivateManager )
- {
+ Selector(String actualMavenVersion, String actualJavaVersion, ToolchainPrivateManager toolchainPrivateManager) {
this.actualMavenVersion = actualMavenVersion;
this.actualJavaVersion = actualJavaVersion;
this.toolchainPrivateManager = toolchainPrivateManager;
}
- public int getSelection( InvokerProperties invokerProperties )
- {
- if ( !invokerProperties.isSelectorDefined( 1 ) )
- {
- return getGlobal( invokerProperties );
+ public int getSelection(InvokerProperties invokerProperties) {
+ if (!invokerProperties.isSelectorDefined(1)) {
+ return getGlobal(invokerProperties);
}
- for ( int selectorIndex = 1;; selectorIndex++ )
- {
- if ( selectorIndex > 1 && !invokerProperties.isSelectorDefined( selectorIndex ) )
- {
+ for (int selectorIndex = 1; ; selectorIndex++) {
+ if (selectorIndex > 1 && !invokerProperties.isSelectorDefined(selectorIndex)) {
break;
}
int selection = 0;
- if ( !SelectorUtils.isMavenVersion( invokerProperties.getMavenVersion( selectorIndex ),
- actualMavenVersion ) )
- {
+ if (!SelectorUtils.isMavenVersion(invokerProperties.getMavenVersion(selectorIndex), actualMavenVersion)) {
selection |= SELECTOR_MAVENVERSION;
}
- if ( !SelectorUtils.isJreVersion( invokerProperties.getJreVersion( selectorIndex ), actualJavaVersion ) )
- {
+ if (!SelectorUtils.isJreVersion(invokerProperties.getJreVersion(selectorIndex), actualJavaVersion)) {
selection |= SELECTOR_JREVERSION;
}
- if ( !SelectorUtils.isOsFamily( invokerProperties.getOsFamily( selectorIndex ) ) )
- {
+ if (!SelectorUtils.isOsFamily(invokerProperties.getOsFamily(selectorIndex))) {
selection |= SELECTOR_OSFAMILY;
}
- if ( !SelectorUtils.isToolchain( toolchainPrivateManager,
- invokerProperties.getToolchains( selectorIndex ) ) )
- {
+ if (!SelectorUtils.isToolchain(toolchainPrivateManager, invokerProperties.getToolchains(selectorIndex))) {
selection |= SELECTOR_TOOLCHAIN;
}
- if ( selection == 0 )
- {
+ if (selection == 0) {
return 0;
}
}
@@ -103,26 +108,21 @@ class Selector
* @return <code>0</code> if the job corresponding to the properties should be run, otherwise a bitwise value
* representing the reason why it should be skipped.
*/
- private int getGlobal( InvokerProperties invokerProperties )
- {
+ private int getGlobal(InvokerProperties invokerProperties) {
int selection = 0;
- if ( !SelectorUtils.isMavenVersion( invokerProperties.getMavenVersion(), actualMavenVersion ) )
- {
+ if (!SelectorUtils.isMavenVersion(invokerProperties.getMavenVersion(), actualMavenVersion)) {
selection |= SELECTOR_MAVENVERSION;
}
- if ( !SelectorUtils.isJreVersion( invokerProperties.getJreVersion(), actualJavaVersion ) )
- {
+ if (!SelectorUtils.isJreVersion(invokerProperties.getJreVersion(), actualJavaVersion)) {
selection |= SELECTOR_JREVERSION;
}
- if ( !SelectorUtils.isOsFamily( invokerProperties.getOsFamily() ) )
- {
+ if (!SelectorUtils.isOsFamily(invokerProperties.getOsFamily())) {
selection |= SELECTOR_OSFAMILY;
}
- if ( !SelectorUtils.isToolchain( toolchainPrivateManager, invokerProperties.getToolchains() ) )
- {
+ if (!SelectorUtils.isToolchain(toolchainPrivateManager, invokerProperties.getToolchains())) {
selection |= SELECTOR_TOOLCHAIN;
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/SelectorUtils.java b/src/main/java/org/apache/maven/plugins/invoker/SelectorUtils.java
index 2503bfb..3d47253 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/SelectorUtils.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/SelectorUtils.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -45,53 +63,40 @@ import org.codehaus.plexus.util.StringUtils;
*
* @author Benjamin Bentmann
*/
-class SelectorUtils
-{
+class SelectorUtils {
- static void parseList( String list, Collection<String> includes, Collection<String> excludes )
- {
- String[] tokens = ( list != null ) ? StringUtils.split( list, "," ) : new String[0];
+ static void parseList(String list, Collection<String> includes, Collection<String> excludes) {
+ String[] tokens = (list != null) ? StringUtils.split(list, ",") : new String[0];
- for ( String token1 : tokens )
- {
+ for (String token1 : tokens) {
String token = token1.trim();
- if ( token.startsWith( "!" ) )
- {
- excludes.add( token.substring( 1 ) );
- }
- else
- {
- includes.add( token );
+ if (token.startsWith("!")) {
+ excludes.add(token.substring(1));
+ } else {
+ includes.add(token);
}
}
}
- static boolean isOsFamily( String osSpec )
- {
+ static boolean isOsFamily(String osSpec) {
List<String> includes = new ArrayList<>();
List<String> excludes = new ArrayList<>();
- parseList( osSpec, includes, excludes );
+ parseList(osSpec, includes, excludes);
- return isOsFamily( includes, true ) && !isOsFamily( excludes, false );
+ return isOsFamily(includes, true) && !isOsFamily(excludes, false);
}
- static boolean isOsFamily( List<String> families, boolean defaultMatch )
- {
- if ( families != null && !families.isEmpty() )
- {
- for ( String family : families )
- {
- if ( Os.isFamily( family ) )
- {
+ static boolean isOsFamily(List<String> families, boolean defaultMatch) {
+ if (families != null && !families.isEmpty()) {
+ for (String family : families) {
+ if (Os.isFamily(family)) {
return true;
}
}
return false;
- }
- else
- {
+ } else {
return defaultMatch;
}
}
@@ -101,178 +106,143 @@ class SelectorUtils
*
* @return The current Maven version.
*/
- static String getMavenVersion()
- {
- try
- {
+ static String getMavenVersion() {
+ try {
// This relies on the fact that MavenProject is the in core classloader
// and that the core classloader is for the maven-core artifact
// and that should have a pom.properties file
// if this ever changes, we will have to revisit this code.
Properties properties = new Properties();
// CHECKSTYLE_OFF: LineLength
- properties.load( MavenProject.class.getClassLoader()
- .getResourceAsStream( "META-INF/maven/org.apache.maven/maven-core/pom.properties" ) );
+ properties.load(MavenProject.class
+ .getClassLoader()
+ .getResourceAsStream("META-INF/maven/org.apache.maven/maven-core/pom.properties"));
// CHECKSTYLE_ON: LineLength
- return StringUtils.trim( properties.getProperty( "version" ) );
- }
- catch ( Exception e )
- {
+ return StringUtils.trim(properties.getProperty("version"));
+ } catch (Exception e) {
return null;
}
}
- static String getMavenVersion( File mavenHome ) throws IOException
- {
- File mavenLib = new File( mavenHome, "lib" );
- File[] jarFiles = mavenLib.listFiles( ( dir, name ) -> name.endsWith( ".jar" ) );
+ static String getMavenVersion(File mavenHome) throws IOException {
+ File mavenLib = new File(mavenHome, "lib");
+ File[] jarFiles = mavenLib.listFiles((dir, name) -> name.endsWith(".jar"));
- if ( jarFiles == null )
- {
- throw new IllegalArgumentException( "Invalid Maven home installation directory: " + mavenHome );
+ if (jarFiles == null) {
+ throw new IllegalArgumentException("Invalid Maven home installation directory: " + mavenHome);
}
- for ( File file : jarFiles )
- {
- try
- {
- URL url = new URL( "jar:" + file.toURI().toURL().toExternalForm()
- + "!/META-INF/maven/org.apache.maven/maven-core/pom.properties" );
+ for (File file : jarFiles) {
+ try {
+ URL url = new URL("jar:" + file.toURI().toURL().toExternalForm()
+ + "!/META-INF/maven/org.apache.maven/maven-core/pom.properties");
- try ( InputStream in = url.openStream() )
- {
+ try (InputStream in = url.openStream()) {
Properties properties = new Properties();
- properties.load( in );
- String version = StringUtils.trim( properties.getProperty( "version" ) );
- if ( version != null )
- {
+ properties.load(in);
+ String version = StringUtils.trim(properties.getProperty("version"));
+ if (version != null) {
return version;
}
}
- }
- catch ( FileNotFoundException | MalformedURLException e )
- {
+ } catch (FileNotFoundException | MalformedURLException e) {
// ignore
}
}
return null;
}
- static boolean isMavenVersion( String mavenSpec )
- {
- return isMavenVersion( mavenSpec, getMavenVersion() );
+ static boolean isMavenVersion(String mavenSpec) {
+ return isMavenVersion(mavenSpec, getMavenVersion());
}
- static boolean isMavenVersion( String mavenSpec, String actualVersion )
- {
+ static boolean isMavenVersion(String mavenSpec, String actualVersion) {
List<String> includes = new ArrayList<>();
List<String> excludes = new ArrayList<>();
- parseList( mavenSpec, includes, excludes );
+ parseList(mavenSpec, includes, excludes);
- List<Integer> mavenVersionList = parseVersion( actualVersion );
+ List<Integer> mavenVersionList = parseVersion(actualVersion);
- return isJreVersion( mavenVersionList, includes, true ) && !isJreVersion( mavenVersionList, excludes, false );
+ return isJreVersion(mavenVersionList, includes, true) && !isJreVersion(mavenVersionList, excludes, false);
}
- static String getJreVersion()
- {
- return System.getProperty( "java.version", "" );
+ static String getJreVersion() {
+ return System.getProperty("java.version", "");
}
- static String getJreVersion( File javaHome )
- {
+ static String getJreVersion(File javaHome) {
// @todo detect actual version
return null;
}
- static boolean isJreVersion( String jreSpec )
- {
- return isJreVersion( jreSpec, getJreVersion() );
+ static boolean isJreVersion(String jreSpec) {
+ return isJreVersion(jreSpec, getJreVersion());
}
- static boolean isJreVersion( String jreSpec, String actualJreVersion )
- {
+ static boolean isJreVersion(String jreSpec, String actualJreVersion) {
List<String> includes = new ArrayList<>();
List<String> excludes = new ArrayList<>();
- parseList( jreSpec, includes, excludes );
+ parseList(jreSpec, includes, excludes);
- List<Integer> jreVersion = parseVersion( actualJreVersion );
+ List<Integer> jreVersion = parseVersion(actualJreVersion);
- return isJreVersion( jreVersion, includes, true ) && !isJreVersion( jreVersion, excludes, false );
+ return isJreVersion(jreVersion, includes, true) && !isJreVersion(jreVersion, excludes, false);
}
- static boolean isJreVersion( List<Integer> jreVersion, List<String> versionPatterns, boolean defaultMatch )
- {
- if ( versionPatterns != null && !versionPatterns.isEmpty() )
- {
- for ( String versionPattern : versionPatterns )
- {
- if ( isJreVersion( jreVersion, versionPattern ) )
- {
+ static boolean isJreVersion(List<Integer> jreVersion, List<String> versionPatterns, boolean defaultMatch) {
+ if (versionPatterns != null && !versionPatterns.isEmpty()) {
+ for (String versionPattern : versionPatterns) {
+ if (isJreVersion(jreVersion, versionPattern)) {
return true;
}
}
return false;
- }
- else
- {
+ } else {
return defaultMatch;
}
}
- static boolean isJreVersion( List<Integer> jreVersion, String versionPattern )
- {
- List<Integer> checkVersion = parseVersion( versionPattern );
+ static boolean isJreVersion(List<Integer> jreVersion, String versionPattern) {
+ List<Integer> checkVersion = parseVersion(versionPattern);
- if ( versionPattern.endsWith( "+" ) )
- {
+ if (versionPattern.endsWith("+")) {
// 1.5+ <=> [1.5,)
- return compareVersions( jreVersion, checkVersion ) >= 0;
- }
- else if ( versionPattern.endsWith( "-" ) )
- {
+ return compareVersions(jreVersion, checkVersion) >= 0;
+ } else if (versionPattern.endsWith("-")) {
// 1.5- <=> (,1.5)
- return compareVersions( jreVersion, checkVersion ) < 0;
- }
- else
- {
+ return compareVersions(jreVersion, checkVersion) < 0;
+ } else {
// 1.5 <=> [1.5,1.6)
return checkVersion.size() <= jreVersion.size()
- && checkVersion.equals( jreVersion.subList( 0, checkVersion.size() ) );
+ && checkVersion.equals(jreVersion.subList(0, checkVersion.size()));
}
}
- static List<Integer> parseVersion( String version )
- {
- version = version.replaceAll( "[^0-9]", "." );
+ static List<Integer> parseVersion(String version) {
+ version = version.replaceAll("[^0-9]", ".");
- String[] tokens = StringUtils.split( version, "." );
+ String[] tokens = StringUtils.split(version, ".");
- List<Integer> numbers = Arrays.stream( tokens ).map( Integer::valueOf ).collect( Collectors.toList() );
+ List<Integer> numbers = Arrays.stream(tokens).map(Integer::valueOf).collect(Collectors.toList());
return numbers;
}
- static int compareVersions( List<Integer> version1, List<Integer> version2 )
- {
- for ( Iterator<Integer> it1 = version1.iterator(), it2 = version2.iterator(); ; )
- {
- if ( !it1.hasNext() )
- {
+ static int compareVersions(List<Integer> version1, List<Integer> version2) {
+ for (Iterator<Integer> it1 = version1.iterator(), it2 = version2.iterator(); ; ) {
+ if (!it1.hasNext()) {
return it2.hasNext() ? -1 : 0;
}
- if ( !it2.hasNext() )
- {
+ if (!it2.hasNext()) {
return it1.hasNext() ? 1 : 0;
}
Integer num1 = it1.next();
Integer num2 = it2.next();
- int rel = num1.compareTo( num2 );
- if ( rel != 0 )
- {
+ int rel = num1.compareTo(num2);
+ if (rel != 0) {
return rel;
}
}
@@ -283,36 +253,27 @@ class SelectorUtils
* @param invokerToolchains
* @return {@code true} if all invokerToolchains are available, otherwise {@code false}
*/
- static boolean isToolchain( ToolchainPrivateManager toolchainPrivateManager,
- Collection<InvokerToolchain> invokerToolchains )
- {
- for ( InvokerToolchain invokerToolchain : invokerToolchains )
- {
+ static boolean isToolchain(
+ ToolchainPrivateManager toolchainPrivateManager, Collection<InvokerToolchain> invokerToolchains) {
+ for (InvokerToolchain invokerToolchain : invokerToolchains) {
boolean found = false;
- try
- {
- for ( ToolchainPrivate tc : toolchainPrivateManager.getToolchainPrivates( invokerToolchain.getType() ) )
- {
- if ( !invokerToolchain.getType().equals( tc.getType() ) )
- {
+ try {
+ for (ToolchainPrivate tc : toolchainPrivateManager.getToolchainPrivates(invokerToolchain.getType())) {
+ if (!invokerToolchain.getType().equals(tc.getType())) {
// useful because of MNG-5716
continue;
}
- if ( tc.matchesRequirements( invokerToolchain.getProvides() ) )
- {
+ if (tc.matchesRequirements(invokerToolchain.getProvides())) {
found = true;
continue;
}
}
- }
- catch ( MisconfiguredToolchainException e )
- {
+ } catch (MisconfiguredToolchainException e) {
return false;
}
- if ( !found )
- {
+ if (!found) {
return false;
}
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/SystemPropertyPrinter.java b/src/main/java/org/apache/maven/plugins/invoker/SystemPropertyPrinter.java
index 6ee237f..594357e 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/SystemPropertyPrinter.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/SystemPropertyPrinter.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -26,17 +44,13 @@ package org.apache.maven.plugins.invoker;
* @author Robert Scholte
* @since 1.8
*/
-public class SystemPropertyPrinter
-{
+public class SystemPropertyPrinter {
/**
* @param args system properties to print
*/
- public static void main( String[] args )
- {
- for ( String arg : args )
- {
- System.out.println( System.getProperty( arg, "" ) );
+ public static void main(String[] args) {
+ for (String arg : args) {
+ System.out.println(System.getProperty(arg, ""));
}
}
-
}
diff --git a/src/main/java/org/apache/maven/plugins/invoker/VerifyMojo.java b/src/main/java/org/apache/maven/plugins/invoker/VerifyMojo.java
index 66ab762..1ae1904 100644
--- a/src/main/java/org/apache/maven/plugins/invoker/VerifyMojo.java
+++ b/src/main/java/org/apache/maven/plugins/invoker/VerifyMojo.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,37 +37,35 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugins.invoker.model.io.xpp3.BuildJobXpp3Reader;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.plugins.invoker.model.io.xpp3.BuildJobXpp3Reader;
import org.codehaus.plexus.util.ReaderFactory;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
-import java.io.File;
-import java.io.IOException;
-import java.io.Reader;
-
/**
* Checks the results of maven-invoker-plugin based integration tests and fails the build if any tests failed.
*
* @author Olivier Lamy
* @since 1.4
*/
-@Mojo( name = "verify", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true )
-public class VerifyMojo
- extends AbstractMojo
-{
+@Mojo(name = "verify", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true)
+public class VerifyMojo extends AbstractMojo {
/**
* Flag used to suppress certain invocations. This is useful in tailoring the build using profiles.
*
* @since 1.1
*/
- @Parameter( property = "invoker.skip", defaultValue = "false" )
+ @Parameter(property = "invoker.skip", defaultValue = "false")
private boolean skipInvocation;
/**
@@ -57,7 +73,7 @@ public class VerifyMojo
*
* @since 1.4
*/
- @Parameter( property = "invoker.reportsDirectory", defaultValue = "${project.build.directory}/invoker-reports" )
+ @Parameter(property = "invoker.reportsDirectory", defaultValue = "${project.build.directory}/invoker-reports")
private File reportsDirectory;
/**
@@ -66,7 +82,7 @@ public class VerifyMojo
*
* @since 1.3
*/
- @Parameter( property = "maven.test.failure.ignore", defaultValue = "false" )
+ @Parameter(property = "maven.test.failure.ignore", defaultValue = "false")
private boolean ignoreFailures;
/**
@@ -74,7 +90,7 @@ public class VerifyMojo
* only indication of the build's success or failure will be the effect it has on the main build (if it fails, the
* main build should fail as well).
*/
- @Parameter( defaultValue = "false" )
+ @Parameter(defaultValue = "false")
private boolean suppressSummaries;
/**
@@ -82,7 +98,7 @@ public class VerifyMojo
*
* @since 1.9
*/
- @Parameter( property = "invoker.failIfNoProjects" )
+ @Parameter(property = "invoker.failIfNoProjects")
private Boolean failIfNoProjects;
/**
@@ -90,7 +106,7 @@ public class VerifyMojo
*
* @since 3.2.2
*/
- @Parameter( property = "invoker.streamLogsOnFailures", defaultValue = "false" )
+ @Parameter(property = "invoker.streamLogsOnFailures", defaultValue = "false")
private boolean streamLogsOnFailures;
/**
@@ -99,24 +115,19 @@ public class VerifyMojo
* @throws org.apache.maven.plugin.MojoExecutionException If the goal encountered severe errors.
* @throws org.apache.maven.plugin.MojoFailureException If any of the Maven builds failed.
*/
- public void execute()
- throws MojoExecutionException, MojoFailureException
- {
- if ( skipInvocation )
- {
- getLog().info( "Skipping invocation per configuration."
- + " If this is incorrect, ensure the skipInvocation parameter is not set to true." );
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ if (skipInvocation) {
+ getLog().info("Skipping invocation per configuration."
+ + " If this is incorrect, ensure the skipInvocation parameter is not set to true.");
return;
}
- File[] reportFiles = ReportUtils.getReportFiles( reportsDirectory );
- if ( reportFiles.length <= 0 )
- {
- if ( Boolean.TRUE.equals( failIfNoProjects ) )
- {
- throw new MojoFailureException( "No projects to invoke!" );
+ File[] reportFiles = ReportUtils.getReportFiles(reportsDirectory);
+ if (reportFiles.length <= 0) {
+ if (Boolean.TRUE.equals(failIfNoProjects)) {
+ throw new MojoFailureException("No projects to invoke!");
}
- getLog().info( "No invoker report files found, nothing to check." );
+ getLog().info("No invoker report files found, nothing to check.");
return;
}
@@ -124,33 +135,24 @@ public class VerifyMojo
InvokerSession invokerSession = new InvokerSession();
- for ( File reportFile : reportFiles )
- {
- try ( Reader xmlReader = ReaderFactory.newXmlReader( reportFile ) )
- {
- invokerSession.addJob( reader.read( xmlReader ) );
- }
- catch ( XmlPullParserException e )
- {
- throw new MojoExecutionException( "Failed to parse report file: " + reportFile, e );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Failed to read report file: " + reportFile, e );
+ for (File reportFile : reportFiles) {
+ try (Reader xmlReader = ReaderFactory.newXmlReader(reportFile)) {
+ invokerSession.addJob(reader.read(xmlReader));
+ } catch (XmlPullParserException e) {
+ throw new MojoExecutionException("Failed to parse report file: " + reportFile, e);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to read report file: " + reportFile, e);
}
}
- if ( streamLogsOnFailures )
- {
- invokerSession.logFailedBuildLog( getLog(), ignoreFailures );
+ if (streamLogsOnFailures) {
+ invokerSession.logFailedBuildLog(getLog(), ignoreFailures);
}
- if ( !suppressSummaries )
- {
- invokerSession.logSummary( getLog(), ignoreFailures );
+ if (!suppressSummaries) {
+ invokerSession.logSummary(getLog(), ignoreFailures);
}
- invokerSession.handleFailures( getLog(), ignoreFailures );
+ invokerSession.handleFailures(getLog(), ignoreFailures);
}
-
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/ExtendedMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/invoker/ExtendedMavenProjectStub.java
index 0f3aeaf..c0271d4 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/ExtendedMavenProjectStub.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/ExtendedMavenProjectStub.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,39 +37,33 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
+import java.util.Properties;
+
import org.apache.maven.model.Scm;
import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
-import java.util.Properties;
-
/**
* @author Olivier Lamy
* @since 22 nov. 07
*/
-public class ExtendedMavenProjectStub
- extends MavenProjectStub
-{
+public class ExtendedMavenProjectStub extends MavenProjectStub {
private Scm scm;
private Properties properties;
- public Scm getScm()
- {
+ public Scm getScm() {
return scm;
}
- public void setScm( Scm scm )
- {
+ public void setScm(Scm scm) {
this.scm = scm;
}
- public Properties getProperties()
- {
+ public Properties getProperties() {
return properties;
}
- public void setProperties( Properties properties )
- {
+ public void setProperties(Properties properties) {
this.properties = properties;
}
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/InterpolationTest.java b/src/test/java/org/apache/maven/plugins/invoker/InterpolationTest.java
index 8f96fb9..40d2495 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/InterpolationTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/InterpolationTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -35,74 +53,66 @@ import org.codehaus.plexus.util.ReaderFactory;
* @author Olivier Lamy
* @since 22 nov. 07
*/
-public class InterpolationTest
- extends AbstractMojoTestCase
-{
+public class InterpolationTest extends AbstractMojoTestCase {
- protected MavenProjectStub buildMavenProjectStub()
- {
+ protected MavenProjectStub buildMavenProjectStub() {
ExtendedMavenProjectStub project = new ExtendedMavenProjectStub();
- project.setVersion( "1.0-SNAPSHOT" );
- project.setArtifactId( "foo" );
- project.setGroupId( "bar" );
+ project.setVersion("1.0-SNAPSHOT");
+ project.setArtifactId("foo");
+ project.setGroupId("bar");
Properties properties = new Properties();
- properties.put( "fooOnProject", "barOnProject" );
- project.setProperties( properties );
+ properties.put("fooOnProject", "barOnProject");
+ project.setProperties(properties);
Scm scm = new Scm();
- scm.setConnection( "http://blabla" );
- project.setScm( scm );
+ scm.setConnection("http://blabla");
+ project.setScm(scm);
return project;
}
- public void testCompositeMap()
- {
+ public void testCompositeMap() {
Properties properties = new Properties();
- properties.put( "foo", "bar" );
- properties.put( "version", "2.0-SNAPSHOT" );
- CompositeMap compositeMap = new CompositeMap( buildMavenProjectStub(), (Map) properties, false );
- assertEquals( "1.0-SNAPSHOT", compositeMap.get( "pom.version" ) );
- assertEquals( "bar", compositeMap.get( "foo" ) );
- assertEquals( "bar", compositeMap.get( "pom.groupId" ) );
- assertEquals( "http://blabla", compositeMap.get( "pom.scm.connection" ) );
- assertEquals( "barOnProject", compositeMap.get( "fooOnProject" ) );
+ properties.put("foo", "bar");
+ properties.put("version", "2.0-SNAPSHOT");
+ CompositeMap compositeMap = new CompositeMap(buildMavenProjectStub(), (Map) properties, false);
+ assertEquals("1.0-SNAPSHOT", compositeMap.get("pom.version"));
+ assertEquals("bar", compositeMap.get("foo"));
+ assertEquals("bar", compositeMap.get("pom.groupId"));
+ assertEquals("http://blabla", compositeMap.get("pom.scm.connection"));
+ assertEquals("barOnProject", compositeMap.get("fooOnProject"));
}
- public void testPomInterpolation()
- throws Exception
- {
+ public void testPomInterpolation() throws Exception {
Reader reader = null;
File interpolatedPomFile;
- try
- {
+ try {
InvokerMojo invokerMojo = new InvokerMojo();
- setVariableValueToObject( invokerMojo, "project", buildMavenProjectStub() );
- setVariableValueToObject( invokerMojo, "settings", new Settings() );
+ setVariableValueToObject(invokerMojo, "project", buildMavenProjectStub());
+ setVariableValueToObject(invokerMojo, "settings", new Settings());
Properties properties = new Properties();
- properties.put( "foo", "bar" );
- properties.put( "version", "2.0-SNAPSHOT" );
- setVariableValueToObject( invokerMojo, "filterProperties", properties );
- String dirPath = getBasedir() + File.separatorChar + "src" + File.separatorChar + "test"
- + File.separatorChar + "resources" + File.separatorChar + "unit" + File.separatorChar + "interpolation";
+ properties.put("foo", "bar");
+ properties.put("version", "2.0-SNAPSHOT");
+ setVariableValueToObject(invokerMojo, "filterProperties", properties);
+ String dirPath =
+ getBasedir() + File.separatorChar + "src" + File.separatorChar + "test" + File.separatorChar
+ + "resources" + File.separatorChar + "unit" + File.separatorChar + "interpolation";
- interpolatedPomFile = new File( getBasedir(), "target/interpolated-pom.xml" );
- invokerMojo.buildInterpolatedFile( new File( dirPath, "pom.xml" ), interpolatedPomFile );
- reader = ReaderFactory.newXmlReader( interpolatedPomFile );
- String content = IOUtil.toString( reader );
- assertTrue( content.indexOf( "<interpolateValue>bar</interpolateValue>" ) > 0 );
+ interpolatedPomFile = new File(getBasedir(), "target/interpolated-pom.xml");
+ invokerMojo.buildInterpolatedFile(new File(dirPath, "pom.xml"), interpolatedPomFile);
+ reader = ReaderFactory.newXmlReader(interpolatedPomFile);
+ String content = IOUtil.toString(reader);
+ assertTrue(content.indexOf("<interpolateValue>bar</interpolateValue>") > 0);
reader.close();
reader = null;
// recreate it to test delete if exists before creation
- invokerMojo.buildInterpolatedFile( new File( dirPath, "pom.xml" ), interpolatedPomFile );
- reader = ReaderFactory.newXmlReader( interpolatedPomFile );
- content = IOUtil.toString( reader );
- assertTrue( content.indexOf( "<interpolateValue>bar</interpolateValue>" ) > 0 );
+ invokerMojo.buildInterpolatedFile(new File(dirPath, "pom.xml"), interpolatedPomFile);
+ reader = ReaderFactory.newXmlReader(interpolatedPomFile);
+ content = IOUtil.toString(reader);
+ assertTrue(content.indexOf("<interpolateValue>bar</interpolateValue>") > 0);
reader.close();
reader = null;
- }
- finally
- {
- IOUtil.close( reader );
+ } finally {
+ IOUtil.close(reader);
}
}
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/InvokerMojoTest.java b/src/test/java/org/apache/maven/plugins/invoker/InvokerMojoTest.java
index b1f704b..eaf704f 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/InvokerMojoTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/InvokerMojoTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,108 +37,97 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
-import static org.assertj.core.api.Assertions.assertThat;
+import java.io.File;
+import java.util.Collections;
+import java.util.List;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.apache.maven.plugins.invoker.model.BuildJob;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;
-import java.io.File;
-import java.util.Collections;
-import java.util.List;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Olivier Lamy
* @since 18 nov. 07
*/
-public class InvokerMojoTest extends AbstractMojoTestCase
-{
+public class InvokerMojoTest extends AbstractMojoTestCase {
private static final String DUMMY_PROJECT = "dummy" + File.separator + "pom.xml";
private static final String WITH_POM_DIR_PROJECT = "with-pom-project-dir" + File.separator + "pom.xml";
private static final String INTERPOLATION_PROJECT = "interpolation" + File.separator + "pom.xml";
private static final String WITHOUT_POM_PROJECT = "without-pom-project-dir";
- private MavenProject getMavenProject()
- {
+ private MavenProject getMavenProject() {
MavenProject mavenProject = new MavenProject();
- mavenProject.setFile( new File( "target/foo.txt" ) );
+ mavenProject.setFile(new File("target/foo.txt"));
return mavenProject;
}
- public void testSingleInvokerTest() throws Exception
- {
+ public void testSingleInvokerTest() throws Exception {
// given
InvokerMojo invokerMojo = new InvokerMojo();
String dirPath = getBasedir() + "/src/test/resources/unit";
- setVariableValueToObject( invokerMojo, "projectsDirectory", new File( dirPath ) );
- setVariableValueToObject( invokerMojo, "invokerPropertiesFile", "invoker.properties" );
- setVariableValueToObject( invokerMojo, "project", getMavenProject() );
- setVariableValueToObject( invokerMojo, "invokerTest", "*dummy*" );
- setVariableValueToObject( invokerMojo, "settings", new Settings() );
+ setVariableValueToObject(invokerMojo, "projectsDirectory", new File(dirPath));
+ setVariableValueToObject(invokerMojo, "invokerPropertiesFile", "invoker.properties");
+ setVariableValueToObject(invokerMojo, "project", getMavenProject());
+ setVariableValueToObject(invokerMojo, "invokerTest", "*dummy*");
+ setVariableValueToObject(invokerMojo, "settings", new Settings());
// when
List<BuildJob> jobs = invokerMojo.getBuildJobs();
// then
- assertThat( jobs )
- .map( BuildJob::getProject )
- .containsExactlyInAnyOrder( DUMMY_PROJECT );
+ assertThat(jobs).map(BuildJob::getProject).containsExactlyInAnyOrder(DUMMY_PROJECT);
}
- public void testMultiInvokerTest() throws Exception
- {
+ public void testMultiInvokerTest() throws Exception {
// given
InvokerMojo invokerMojo = new InvokerMojo();
String dirPath = getBasedir() + "/src/test/resources/unit";
- setVariableValueToObject( invokerMojo, "projectsDirectory", new File( dirPath ) );
- setVariableValueToObject( invokerMojo, "invokerPropertiesFile", "invoker.properties" );
- setVariableValueToObject( invokerMojo, "project", getMavenProject() );
- setVariableValueToObject( invokerMojo, "invokerTest", "*dummy*,*terpolatio*" );
- setVariableValueToObject( invokerMojo, "settings", new Settings() );
+ setVariableValueToObject(invokerMojo, "projectsDirectory", new File(dirPath));
+ setVariableValueToObject(invokerMojo, "invokerPropertiesFile", "invoker.properties");
+ setVariableValueToObject(invokerMojo, "project", getMavenProject());
+ setVariableValueToObject(invokerMojo, "invokerTest", "*dummy*,*terpolatio*");
+ setVariableValueToObject(invokerMojo, "settings", new Settings());
// when
List<BuildJob> jobs = invokerMojo.getBuildJobs();
// then
- assertThat( jobs )
- .map( BuildJob::getProject )
- .containsExactlyInAnyOrder( DUMMY_PROJECT, INTERPOLATION_PROJECT );
+ assertThat(jobs).map(BuildJob::getProject).containsExactlyInAnyOrder(DUMMY_PROJECT, INTERPOLATION_PROJECT);
}
- public void testFullPatternInvokerTest() throws Exception
- {
+ public void testFullPatternInvokerTest() throws Exception {
// given
InvokerMojo invokerMojo = new InvokerMojo();
String dirPath = getBasedir() + "/src/test/resources/unit";
- setVariableValueToObject( invokerMojo, "projectsDirectory", new File( dirPath ) );
- setVariableValueToObject( invokerMojo, "invokerPropertiesFile", "invoker.properties" );
- setVariableValueToObject( invokerMojo, "project", getMavenProject() );
- setVariableValueToObject( invokerMojo, "invokerTest", "*" );
- setVariableValueToObject( invokerMojo, "settings", new Settings() );
+ setVariableValueToObject(invokerMojo, "projectsDirectory", new File(dirPath));
+ setVariableValueToObject(invokerMojo, "invokerPropertiesFile", "invoker.properties");
+ setVariableValueToObject(invokerMojo, "project", getMavenProject());
+ setVariableValueToObject(invokerMojo, "invokerTest", "*");
+ setVariableValueToObject(invokerMojo, "settings", new Settings());
// when
List<BuildJob> jobs = invokerMojo.getBuildJobs();
// then
- assertThat( jobs )
- .map( BuildJob::getProject )
+ assertThat(jobs)
+ .map(BuildJob::getProject)
.containsExactlyInAnyOrder(
- DUMMY_PROJECT, WITH_POM_DIR_PROJECT, WITHOUT_POM_PROJECT,
- INTERPOLATION_PROJECT );
+ DUMMY_PROJECT, WITH_POM_DIR_PROJECT, WITHOUT_POM_PROJECT, INTERPOLATION_PROJECT);
}
- public void testSetupInProjectList() throws Exception
- {
+ public void testSetupInProjectList() throws Exception {
// given
InvokerMojo invokerMojo = new InvokerMojo();
String dirPath = getBasedir() + "/src/test/resources/unit";
- setVariableValueToObject( invokerMojo, "projectsDirectory", new File( dirPath ) );
- setVariableValueToObject( invokerMojo, "invokerPropertiesFile", "invoker.properties" );
- setVariableValueToObject( invokerMojo, "project", getMavenProject() );
- setVariableValueToObject( invokerMojo, "settings", new Settings() );
- setVariableValueToObject( invokerMojo, "setupIncludes", Collections.singletonList( "dum*/pom.xml" ) );
+ setVariableValueToObject(invokerMojo, "projectsDirectory", new File(dirPath));
+ setVariableValueToObject(invokerMojo, "invokerPropertiesFile", "invoker.properties");
+ setVariableValueToObject(invokerMojo, "project", getMavenProject());
+ setVariableValueToObject(invokerMojo, "settings", new Settings());
+ setVariableValueToObject(invokerMojo, "setupIncludes", Collections.singletonList("dum*/pom.xml"));
// when
List<BuildJob> jobs = invokerMojo.getBuildJobs();
@@ -128,30 +135,27 @@ public class InvokerMojoTest extends AbstractMojoTestCase
// then
// we have all projects with pom.xml
- assertThat( jobs )
- .map( BuildJob::getProject )
- .containsExactlyInAnyOrder(
- DUMMY_PROJECT, WITH_POM_DIR_PROJECT, INTERPOLATION_PROJECT );
+ assertThat(jobs)
+ .map(BuildJob::getProject)
+ .containsExactlyInAnyOrder(DUMMY_PROJECT, WITH_POM_DIR_PROJECT, INTERPOLATION_PROJECT);
// and we have one setup project
- assertThat( jobs )
- .filteredOn( job -> BuildJob.Type.SETUP.equals( job.getType() ) )
- .map( BuildJob::getProject )
- .containsExactlyInAnyOrder( DUMMY_PROJECT );
+ assertThat(jobs)
+ .filteredOn(job -> BuildJob.Type.SETUP.equals(job.getType()))
+ .map(BuildJob::getProject)
+ .containsExactlyInAnyOrder(DUMMY_PROJECT);
}
- public void testSetupProjectIsFiltered() throws Exception
- {
+ public void testSetupProjectIsFiltered() throws Exception {
// given
InvokerMojo invokerMojo = new InvokerMojo();
String dirPath = getBasedir() + "/src/test/resources/unit";
- setVariableValueToObject( invokerMojo, "projectsDirectory", new File( dirPath ) );
- setVariableValueToObject( invokerMojo, "invokerPropertiesFile", "invoker.properties" );
- setVariableValueToObject( invokerMojo, "project", getMavenProject() );
- setVariableValueToObject( invokerMojo, "settings", new Settings() );
- setVariableValueToObject( invokerMojo, "setupIncludes", Collections.singletonList( "dum*/pom.xml" ) );
- setVariableValueToObject( invokerMojo, "invokerTest", "*project-dir*" );
-
+ setVariableValueToObject(invokerMojo, "projectsDirectory", new File(dirPath));
+ setVariableValueToObject(invokerMojo, "invokerPropertiesFile", "invoker.properties");
+ setVariableValueToObject(invokerMojo, "project", getMavenProject());
+ setVariableValueToObject(invokerMojo, "settings", new Settings());
+ setVariableValueToObject(invokerMojo, "setupIncludes", Collections.singletonList("dum*/pom.xml"));
+ setVariableValueToObject(invokerMojo, "invokerTest", "*project-dir*");
// when
List<BuildJob> jobs = invokerMojo.getBuildJobs();
@@ -159,44 +163,37 @@ public class InvokerMojoTest extends AbstractMojoTestCase
// then
// we have filtered projects
- assertThat( jobs )
- .map( BuildJob::getProject )
- .containsExactlyInAnyOrder(
- WITH_POM_DIR_PROJECT, WITHOUT_POM_PROJECT );
+ assertThat(jobs).map(BuildJob::getProject).containsExactlyInAnyOrder(WITH_POM_DIR_PROJECT, WITHOUT_POM_PROJECT);
// and we don't have a setup project
- assertThat( jobs )
- .filteredOn( job -> BuildJob.Type.SETUP.equals( job.getType() ) )
+ assertThat(jobs)
+ .filteredOn(job -> BuildJob.Type.SETUP.equals(job.getType()))
.isEmpty();
}
- public void testAlreadyCloned()
- {
- assertFalse( AbstractInvokerMojo.alreadyCloned( "dir", Collections.emptyList() ) );
- assertTrue( AbstractInvokerMojo.alreadyCloned( "dir", Collections.singletonList( "dir" ) ) );
- assertTrue( AbstractInvokerMojo.alreadyCloned( "dir" + File.separator + "sub",
- Collections.singletonList( "dir" ) ) );
- assertFalse( AbstractInvokerMojo.alreadyCloned( "dirs", Collections.singletonList( "dir" ) ) );
+ public void testAlreadyCloned() {
+ assertFalse(AbstractInvokerMojo.alreadyCloned("dir", Collections.emptyList()));
+ assertTrue(AbstractInvokerMojo.alreadyCloned("dir", Collections.singletonList("dir")));
+ assertTrue(AbstractInvokerMojo.alreadyCloned("dir" + File.separator + "sub", Collections.singletonList("dir")));
+ assertFalse(AbstractInvokerMojo.alreadyCloned("dirs", Collections.singletonList("dir")));
}
- public void testParallelThreadsSettings() throws IllegalAccessException
- {
+ public void testParallelThreadsSettings() throws IllegalAccessException {
Object[][] testValues = {
- {"4", 4},
- {"1C", Runtime.getRuntime().availableProcessors()},
- {"2.5C", (int) ( Double.parseDouble( "2.5" ) * Runtime.getRuntime().availableProcessors() )}
+ {"4", 4},
+ {"1C", Runtime.getRuntime().availableProcessors()},
+ {"2.5C", (int) (Double.parseDouble("2.5") * Runtime.getRuntime().availableProcessors())}
};
InvokerMojo invokerMojo = new InvokerMojo();
- for ( Object[] testValue : testValues )
- {
+ for (Object[] testValue : testValues) {
String parallelThreads = (String) testValue[0];
int expectedParallelThreads = (Integer) testValue[1];
- setVariableValueToObject( invokerMojo, "parallelThreads", parallelThreads );
+ setVariableValueToObject(invokerMojo, "parallelThreads", parallelThreads);
- assertEquals( expectedParallelThreads, invokerMojo.getParallelThreadsCount() );
+ assertEquals(expectedParallelThreads, invokerMojo.getParallelThreadsCount());
}
}
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/InvokerPropertiesTest.java b/src/test/java/org/apache/maven/plugins/invoker/InvokerPropertiesTest.java
index 1694e1d..c656f00 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/InvokerPropertiesTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/InvokerPropertiesTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -48,534 +66,501 @@ import static org.mockito.Mockito.when;
*
* @author Benjamin Bentmann
*/
-@RunWith( MockitoJUnitRunner.class )
-public class InvokerPropertiesTest
-{
+@RunWith(MockitoJUnitRunner.class)
+public class InvokerPropertiesTest {
@Mock
private InvocationRequest request;
@Test
- public void testConstructorNullSafe()
- {
- InvokerProperties facade = new InvokerProperties( null );
- assertThat( facade.getProperties() ).isNotNull();
+ public void testConstructorNullSafe() {
+ InvokerProperties facade = new InvokerProperties(null);
+ assertThat(facade.getProperties()).isNotNull();
}
@Test
- public void testGetInvokerProperty()
- {
+ public void testGetInvokerProperty() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- assertThat( facade.get( "undefined-key", 0 ) ).isEmpty();
+ assertThat(facade.get("undefined-key", 0)).isEmpty();
- props.setProperty( "key", "value" );
- assertThat( facade.get( "key", 1 ) ).hasValue( "value" );
+ props.setProperty("key", "value");
+ assertThat(facade.get("key", 1)).hasValue("value");
- props.setProperty( "key.1", "another-value" );
- assertThat( facade.get( "key", 1 ) ).hasValue( "another-value" );
- assertThat( facade.get( "key", 2 ) ).hasValue( "value" );
+ props.setProperty("key.1", "another-value");
+ assertThat(facade.get("key", 1)).hasValue("another-value");
+ assertThat(facade.get("key", 2)).hasValue("value");
}
@Test
- public void testGetJobName()
- {
+ public void testGetJobName() {
Properties props = new Properties();
final String jobName = "Build Job name";
- props.put( "invoker.name", jobName );
- InvokerProperties facade = new InvokerProperties( props );
+ props.put("invoker.name", jobName);
+ InvokerProperties facade = new InvokerProperties(props);
- assertThat( facade.getJobName() ).isEqualTo( jobName );
+ assertThat(facade.getJobName()).isEqualTo(jobName);
}
@Test
- public void testIsExpectedResult()
- {
+ public void testIsExpectedResult() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- assertThat( facade.isExpectedResult( 0, 0 ) ).isTrue();
- assertThat( facade.isExpectedResult( 1, 0 ) ).isFalse();
+ assertThat(facade.isExpectedResult(0, 0)).isTrue();
+ assertThat(facade.isExpectedResult(1, 0)).isFalse();
- props.setProperty( "invoker.buildResult", "success" );
- assertThat( facade.isExpectedResult( 0, 0 ) ).isTrue();
- assertThat( facade.isExpectedResult( 1, 0 ) ).isFalse();
+ props.setProperty("invoker.buildResult", "success");
+ assertThat(facade.isExpectedResult(0, 0)).isTrue();
+ assertThat(facade.isExpectedResult(1, 0)).isFalse();
- props.setProperty( "invoker.buildResult", "failure" );
- assertThat( facade.isExpectedResult( 0, 0 ) ).isFalse();
- assertThat( facade.isExpectedResult( 1, 0 ) ).isTrue();
+ props.setProperty("invoker.buildResult", "failure");
+ assertThat(facade.isExpectedResult(0, 0)).isFalse();
+ assertThat(facade.isExpectedResult(1, 0)).isTrue();
}
@Test
- public void testConfigureRequestEmptyProperties()
- {
+ public void testConfigureRequestEmptyProperties() {
- InvokerProperties facade = new InvokerProperties( null );
+ InvokerProperties facade = new InvokerProperties(null);
- facade.configureInvocation( request, 0 );
- verifyNoInteractions( request );
+ facade.configureInvocation(request, 0);
+ verifyNoInteractions(request);
}
@Test
- public void testConfigureRequestGoals()
- {
+ public void testConfigureRequestGoals() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- props.setProperty( "invoker.goals", "verify" );
- facade.configureInvocation( request, 0 );
- verify( request ).setGoals( Collections.singletonList( "verify" ) );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.goals", " " );
- facade.configureInvocation( request, 0 );
- verify( request, never() ).setGoals( anyList() );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.goals", "" );
- facade.configureInvocation( request, 0 );
- verify( request, never() ).setGoals( anyList() );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.goals", " clean , test verify " );
- facade.configureInvocation( request, 0 );
- verify( request ).setGoals( Arrays.asList( "clean", "test", "verify" ) );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ InvokerProperties facade = new InvokerProperties(props);
+
+ props.setProperty("invoker.goals", "verify");
+ facade.configureInvocation(request, 0);
+ verify(request).setGoals(Collections.singletonList("verify"));
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.goals", " ");
+ facade.configureInvocation(request, 0);
+ verify(request, never()).setGoals(anyList());
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.goals", "");
+ facade.configureInvocation(request, 0);
+ verify(request, never()).setGoals(anyList());
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.goals", " clean , test verify ");
+ facade.configureInvocation(request, 0);
+ verify(request).setGoals(Arrays.asList("clean", "test", "verify"));
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
props.clear();
- facade.setDefaultGoals( Arrays.asList( "clean", "test" ) );
- facade.configureInvocation( request, 0 );
- verify( request ).setGoals( Arrays.asList( "clean", "test" ) );
- verifyNoMoreInteractions( request );
+ facade.setDefaultGoals(Arrays.asList("clean", "test"));
+ facade.configureInvocation(request, 0);
+ verify(request).setGoals(Arrays.asList("clean", "test"));
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestProfiles()
- {
+ public void testConfigureRequestProfiles() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- props.setProperty( "invoker.profiles", "verify" );
- facade.configureInvocation( request, 0 );
- verify( request ).setProfiles( Collections.singletonList( "verify" ) );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.profiles", " " );
- facade.configureInvocation( request, 0 );
- verify( request, never() ).setProfiles( anyList() );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.profiles", "" );
- facade.configureInvocation( request, 0 );
- verify( request, never() ).setProfiles( anyList() );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.profiles", " clean , test verify ," );
- facade.configureInvocation( request, 0 );
- verify( request ).setProfiles( Arrays.asList( "clean", "test", "verify" ) );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ InvokerProperties facade = new InvokerProperties(props);
+
+ props.setProperty("invoker.profiles", "verify");
+ facade.configureInvocation(request, 0);
+ verify(request).setProfiles(Collections.singletonList("verify"));
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.profiles", " ");
+ facade.configureInvocation(request, 0);
+ verify(request, never()).setProfiles(anyList());
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.profiles", "");
+ facade.configureInvocation(request, 0);
+ verify(request, never()).setProfiles(anyList());
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.profiles", " clean , test verify ,");
+ facade.configureInvocation(request, 0);
+ verify(request).setProfiles(Arrays.asList("clean", "test", "verify"));
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
props.clear();
- facade.setDefaultProfiles( Arrays.asList( "profile1", "profile2" ) );
- facade.configureInvocation( request, 0 );
- verify( request ).setProfiles( Arrays.asList( "profile1", "profile2" ) );
- verifyNoMoreInteractions( request );
-
+ facade.setDefaultProfiles(Arrays.asList("profile1", "profile2"));
+ facade.configureInvocation(request, 0);
+ verify(request).setProfiles(Arrays.asList("profile1", "profile2"));
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestProject() throws Exception
- {
+ public void testConfigureRequestProject() throws Exception {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- File tempPom = File.createTempFile( "maven-invoker-plugin-test", ".pom" );
- try
- {
+ File tempPom = File.createTempFile("maven-invoker-plugin-test", ".pom");
+ try {
File tempDir = tempPom.getParentFile();
- when( request.getBaseDirectory() ).thenReturn( tempDir );
-
- props.setProperty( "invoker.project", tempPom.getName() );
- facade.configureInvocation( request, 0 );
- verify( request ).getBaseDirectory();
- verify( request ).setBaseDirectory( tempDir );
- verify( request ).setPomFile( tempPom );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.project", "" );
- facade.configureInvocation( request, 0 );
- verifyNoInteractions( request );
- }
- finally
- {
+ when(request.getBaseDirectory()).thenReturn(tempDir);
+
+ props.setProperty("invoker.project", tempPom.getName());
+ facade.configureInvocation(request, 0);
+ verify(request).getBaseDirectory();
+ verify(request).setBaseDirectory(tempDir);
+ verify(request).setPomFile(tempPom);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.project", "");
+ facade.configureInvocation(request, 0);
+ verifyNoInteractions(request);
+ } finally {
tempPom.delete();
}
}
@Test
- public void testConfigureRequestMavenExecutable()
- {
+ public void testConfigureRequestMavenExecutable() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
- File aDefExecutable = new File( "defExecutable" );
- facade.setDefaultMavenExecutable( aDefExecutable );
+ InvokerProperties facade = new InvokerProperties(props);
+ File aDefExecutable = new File("defExecutable");
+ facade.setDefaultMavenExecutable(aDefExecutable);
- props.setProperty( "invoker.mavenExecutable", "aPropExecutable" );
- facade.configureInvocation( request, 0 );
- verify( request ).setMavenExecutable( new File( "aPropExecutable" ) );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ props.setProperty("invoker.mavenExecutable", "aPropExecutable");
+ facade.configureInvocation(request, 0);
+ verify(request).setMavenExecutable(new File("aPropExecutable"));
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
props.clear();
- facade.configureInvocation( request, 0 );
- verify( request ).setMavenExecutable( aDefExecutable );
- verifyNoMoreInteractions( request );
+ facade.configureInvocation(request, 0);
+ verify(request).setMavenExecutable(aDefExecutable);
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestMavenOpts()
- {
+ public void testConfigureRequestMavenOpts() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
- facade.setDefaultMavenOpts( "-XxxDef" );
+ InvokerProperties facade = new InvokerProperties(props);
+ facade.setDefaultMavenOpts("-XxxDef");
- props.setProperty( "invoker.mavenOpts", "-Xmx512m" );
- facade.configureInvocation( request, 0 );
- verify( request ).setMavenOpts( "-Xmx512m" );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ props.setProperty("invoker.mavenOpts", "-Xmx512m");
+ facade.configureInvocation(request, 0);
+ verify(request).setMavenOpts("-Xmx512m");
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
props.clear();
- facade.configureInvocation( request, 0 );
- verify( request ).setMavenOpts( "-XxxDef" );
- verifyNoMoreInteractions( request );
+ facade.configureInvocation(request, 0);
+ verify(request).setMavenOpts("-XxxDef");
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestFailureBehavior()
- {
+ public void testConfigureRequestFailureBehavior() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- props.setProperty( "invoker.failureBehavior", ReactorFailureBehavior.FailNever.getLongOption() );
- facade.configureInvocation( request, 0 );
- verify( request ).setReactorFailureBehavior( eq( ReactorFailureBehavior.FailNever ) );
+ props.setProperty("invoker.failureBehavior", ReactorFailureBehavior.FailNever.getLongOption());
+ facade.configureInvocation(request, 0);
+ verify(request).setReactorFailureBehavior(eq(ReactorFailureBehavior.FailNever));
- verifyNoMoreInteractions( request );
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestFailureBehaviorUnKnownName()
- {
+ public void testConfigureRequestFailureBehaviorUnKnownName() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- props.setProperty( "invoker.failureBehavior", "xxxUnKnown" );
+ props.setProperty("invoker.failureBehavior", "xxxUnKnown");
- assertThatCode( () -> facade.configureInvocation( request, 0 ) )
- .isExactlyInstanceOf( IllegalArgumentException.class )
- .hasMessage( "The string 'xxxUnKnown' can not be converted to enumeration." );
+ assertThatCode(() -> facade.configureInvocation(request, 0))
+ .isExactlyInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The string 'xxxUnKnown' can not be converted to enumeration.");
- verifyNoInteractions( request );
+ verifyNoInteractions(request);
}
-
@Test
- public void testConfigureRequestRecursion()
- {
+ public void testConfigureRequestRecursion() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- props.setProperty( "invoker.nonRecursive", "true" );
- facade.configureInvocation( request, 0 );
- verify( request ).setRecursive( false );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.nonRecursive", "false" );
- facade.configureInvocation( request, 0 );
- verify( request ).setRecursive( true );
- verifyNoMoreInteractions( request );
+ InvokerProperties facade = new InvokerProperties(props);
+
+ props.setProperty("invoker.nonRecursive", "true");
+ facade.configureInvocation(request, 0);
+ verify(request).setRecursive(false);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.nonRecursive", "false");
+ facade.configureInvocation(request, 0);
+ verify(request).setRecursive(true);
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestOffline()
- {
+ public void testConfigureRequestOffline() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- props.setProperty( "invoker.offline", "true" );
- facade.configureInvocation( request, 0 );
- verify( request ).setOffline( true );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- props.setProperty( "invoker.offline", "false" );
- facade.configureInvocation( request, 0 );
- verify( request ).setOffline( false );
- verifyNoMoreInteractions( request );
+ InvokerProperties facade = new InvokerProperties(props);
+
+ props.setProperty("invoker.offline", "true");
+ facade.configureInvocation(request, 0);
+ verify(request).setOffline(true);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ props.setProperty("invoker.offline", "false");
+ facade.configureInvocation(request, 0);
+ verify(request).setOffline(false);
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureRequestDebug()
- {
+ public void testConfigureRequestDebug() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- props.setProperty( "invoker.debug", "true" );
- facade.configureInvocation( request, 0 );
- verify( request ).setDebug( true );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ props.setProperty("invoker.debug", "true");
+ facade.configureInvocation(request, 0);
+ verify(request).setDebug(true);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
- props.setProperty( "invoker.debug", "false" );
- facade.configureInvocation( request, 0 );
- verify( request ).setDebug( false );
- verifyNoMoreInteractions( request );
+ props.setProperty("invoker.debug", "false");
+ facade.configureInvocation(request, 0);
+ verify(request).setDebug(false);
+ verifyNoMoreInteractions(request);
props.clear();
- facade.setDefaultDebug( true );
- facade.configureInvocation( request, 0 );
- verify( request ).setDebug( true );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- facade.setDefaultDebug( false );
- facade.configureInvocation( request, 0 );
- verify( request ).setDebug( false );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ facade.setDefaultDebug(true);
+ facade.configureInvocation(request, 0);
+ verify(request).setDebug(true);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ facade.setDefaultDebug(false);
+ facade.configureInvocation(request, 0);
+ verify(request).setDebug(false);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
}
@Test
- public void testConfigureRequestQuiet()
- {
+ public void testConfigureRequestQuiet() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- props.setProperty( "invoker.quiet", "true" );
- facade.configureInvocation( request, 0 );
- verify( request ).setQuiet( true );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ props.setProperty("invoker.quiet", "true");
+ facade.configureInvocation(request, 0);
+ verify(request).setQuiet(true);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
- props.setProperty( "invoker.quiet", "false" );
- facade.configureInvocation( request, 0 );
- verify( request ).setQuiet( false );
- verifyNoMoreInteractions( request );
+ props.setProperty("invoker.quiet", "false");
+ facade.configureInvocation(request, 0);
+ verify(request).setQuiet(false);
+ verifyNoMoreInteractions(request);
props.clear();
- facade.setDefaultQuiet( true );
- facade.configureInvocation( request, 0 );
- verify( request ).setQuiet( true );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
-
- facade.setDefaultQuiet( false );
- facade.configureInvocation( request, 0 );
- verify( request ).setQuiet( false );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ facade.setDefaultQuiet(true);
+ facade.configureInvocation(request, 0);
+ verify(request).setQuiet(true);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
+
+ facade.setDefaultQuiet(false);
+ facade.configureInvocation(request, 0);
+ verify(request).setQuiet(false);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
}
@Test
- public void testConfigureRequestTimeoutInSeconds()
- {
+ public void testConfigureRequestTimeoutInSeconds() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- props.setProperty( "invoker.timeoutInSeconds", "5" );
- facade.configureInvocation( request, 0 );
- verify( request ).setTimeoutInSeconds( 5 );
- verifyNoMoreInteractions( request );
- clearInvocations( request );
+ props.setProperty("invoker.timeoutInSeconds", "5");
+ facade.configureInvocation(request, 0);
+ verify(request).setTimeoutInSeconds(5);
+ verifyNoMoreInteractions(request);
+ clearInvocations(request);
props.clear();
- facade.setDefaultTimeoutInSeconds( 3 );
- facade.configureInvocation( request, 0 );
- verify( request ).setTimeoutInSeconds( 3 );
- verifyNoMoreInteractions( request );
-
+ facade.setDefaultTimeoutInSeconds(3);
+ facade.configureInvocation(request, 0);
+ verify(request).setTimeoutInSeconds(3);
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureEnvironmentVariables()
- {
+ public void testConfigureEnvironmentVariables() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- props.setProperty( "invoker.abcdef", "abcdf" );
- props.setProperty( "invoker.environmentVariables.KEY1.1", "value1.1" );
- props.setProperty( "invoker.environmentVariables.KEY1", "value1" );
- props.setProperty( "invoker.environmentVariables.KEY2", "value2" );
- props.setProperty( "invoker.environmentVariables.KEY2.1", "value2.1" );
- props.setProperty( "invoker.environmentVariables.KEY3", "value3" );
- facade.configureInvocation( request, 0 );
- verify( request ).addShellEnvironment( "KEY1", "value1" );
- verify( request ).addShellEnvironment( "KEY2", "value2" );
- verify( request ).addShellEnvironment( "KEY3", "value3" );
- verifyNoMoreInteractions( request );
+ InvokerProperties facade = new InvokerProperties(props);
+
+ props.setProperty("invoker.abcdef", "abcdf");
+ props.setProperty("invoker.environmentVariables.KEY1.1", "value1.1");
+ props.setProperty("invoker.environmentVariables.KEY1", "value1");
+ props.setProperty("invoker.environmentVariables.KEY2", "value2");
+ props.setProperty("invoker.environmentVariables.KEY2.1", "value2.1");
+ props.setProperty("invoker.environmentVariables.KEY3", "value3");
+ facade.configureInvocation(request, 0);
+ verify(request).addShellEnvironment("KEY1", "value1");
+ verify(request).addShellEnvironment("KEY2", "value2");
+ verify(request).addShellEnvironment("KEY3", "value3");
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureEnvironmentVariablesWithIndex()
- {
+ public void testConfigureEnvironmentVariablesWithIndex() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- props.setProperty( "invoker.abcdef", "abcdf" );
- props.setProperty( "invoker.environmentVariables.KEY1.1", "value1.1" );
- props.setProperty( "invoker.environmentVariables.KEY1", "value1" );
- props.setProperty( "invoker.environmentVariables.KEY2", "value2" );
- props.setProperty( "invoker.environmentVariables.KEY2.1", "value2.1" );
- props.setProperty( "invoker.environmentVariables.KEY3", "value3" );
- facade.configureInvocation( request, 1 );
- verify( request ).addShellEnvironment( "KEY1", "value1.1" );
- verify( request ).addShellEnvironment( "KEY2", "value2.1" );
- verify( request ).addShellEnvironment( "KEY3", "value3" );
- verifyNoMoreInteractions( request );
+ InvokerProperties facade = new InvokerProperties(props);
+
+ props.setProperty("invoker.abcdef", "abcdf");
+ props.setProperty("invoker.environmentVariables.KEY1.1", "value1.1");
+ props.setProperty("invoker.environmentVariables.KEY1", "value1");
+ props.setProperty("invoker.environmentVariables.KEY2", "value2");
+ props.setProperty("invoker.environmentVariables.KEY2.1", "value2.1");
+ props.setProperty("invoker.environmentVariables.KEY3", "value3");
+ facade.configureInvocation(request, 1);
+ verify(request).addShellEnvironment("KEY1", "value1.1");
+ verify(request).addShellEnvironment("KEY2", "value2.1");
+ verify(request).addShellEnvironment("KEY3", "value3");
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureUpdateSnapshots()
- {
+ public void testConfigureUpdateSnapshots() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- props.setProperty( "invoker.updateSnapshots", "true" );
- facade.configureInvocation( request, 1 );
- verify( request ).setUpdateSnapshots( true );
- clearInvocations( request );
+ props.setProperty("invoker.updateSnapshots", "true");
+ facade.configureInvocation(request, 1);
+ verify(request).setUpdateSnapshots(true);
+ clearInvocations(request);
props.clear();
- props.setProperty( "invoker.updateSnapshots", "false" );
- facade.configureInvocation( request , 1 );
- verify( request ).setUpdateSnapshots( false );
+ props.setProperty("invoker.updateSnapshots", "false");
+ facade.configureInvocation(request, 1);
+ verify(request).setUpdateSnapshots(false);
- verifyNoMoreInteractions( request );
+ verifyNoMoreInteractions(request);
}
@Test
- public void testConfigureUpdateSnapshotsDefault()
- {
+ public void testConfigureUpdateSnapshotsDefault() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- facade.setDefaultUpdateSnapshots( true );
- facade.configureInvocation( request, 1 );
- verify( request ).setUpdateSnapshots( true );
- clearInvocations( request );
+ facade.setDefaultUpdateSnapshots(true);
+ facade.configureInvocation(request, 1);
+ verify(request).setUpdateSnapshots(true);
+ clearInvocations(request);
- facade.setDefaultUpdateSnapshots( false );
- facade.configureInvocation( request, 1 );
- verify( request ).setUpdateSnapshots( false );
+ facade.setDefaultUpdateSnapshots(false);
+ facade.configureInvocation(request, 1);
+ verify(request).setUpdateSnapshots(false);
- verifyNoMoreInteractions( request );
+ verifyNoMoreInteractions(request);
}
@Test
- public void testIsInvocationDefined()
- {
+ public void testIsInvocationDefined() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
- assertThat( facade.isInvocationDefined( 1 ) ).isFalse();
+ assertThat(facade.isInvocationDefined(1)).isFalse();
- props.setProperty( "invoker.goals", "install" );
- assertThat( facade.isInvocationDefined( 1 ) ).isFalse();
+ props.setProperty("invoker.goals", "install");
+ assertThat(facade.isInvocationDefined(1)).isFalse();
- props.setProperty( "invoker.goals.2", "install" );
- assertThat( facade.isInvocationDefined( 1 ) ).isFalse();
- assertThat( facade.isInvocationDefined( 2 ) ).isTrue();
- assertThat( facade.isInvocationDefined( 3 ) ).isFalse();
+ props.setProperty("invoker.goals.2", "install");
+ assertThat(facade.isInvocationDefined(1)).isFalse();
+ assertThat(facade.isInvocationDefined(2)).isTrue();
+ assertThat(facade.isInvocationDefined(3)).isFalse();
- props.setProperty( "invoker.goals.3", "install" );
- assertThat( facade.isInvocationDefined( 1 ) ).isFalse();
- assertThat( facade.isInvocationDefined( 2 ) ).isTrue();
- assertThat( facade.isInvocationDefined( 3 ) ).isTrue();
- assertThat( facade.isInvocationDefined( 4 ) ).isFalse();
+ props.setProperty("invoker.goals.3", "install");
+ assertThat(facade.isInvocationDefined(1)).isFalse();
+ assertThat(facade.isInvocationDefined(2)).isTrue();
+ assertThat(facade.isInvocationDefined(3)).isTrue();
+ assertThat(facade.isInvocationDefined(4)).isFalse();
}
@Test
- public void testIsSelectedDefined()
- {
+ public void testIsSelectedDefined() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
-
- assertThat( facade.isSelectorDefined( 1 ) ).isFalse();
-
- props.setProperty( "invoker.java.version", "1.6+" );
- props.setProperty( "invoker.maven.version", "3.0+" );
- props.setProperty( "invoker.os.family", "windows" );
- assertThat( facade.isSelectorDefined( 1 ) ).isFalse();
-
- props.setProperty( "selector.2.java.version", "1.6+" );
- props.setProperty( "selector.3.maven.version", "3.0+" );
- props.setProperty( "selector.4.os.family", "windows" );
- assertThat( facade.isSelectorDefined( 1 ) ).isFalse();
- assertThat( facade.isSelectorDefined( 2 ) ).isTrue();
- assertThat( facade.isSelectorDefined( 3 ) ).isTrue();
- assertThat( facade.isSelectorDefined( 4 ) ).isTrue();
- assertThat( facade.isSelectorDefined( 5 ) ).isFalse();
+ InvokerProperties facade = new InvokerProperties(props);
+
+ assertThat(facade.isSelectorDefined(1)).isFalse();
+
+ props.setProperty("invoker.java.version", "1.6+");
+ props.setProperty("invoker.maven.version", "3.0+");
+ props.setProperty("invoker.os.family", "windows");
+ assertThat(facade.isSelectorDefined(1)).isFalse();
+
+ props.setProperty("selector.2.java.version", "1.6+");
+ props.setProperty("selector.3.maven.version", "3.0+");
+ props.setProperty("selector.4.os.family", "windows");
+ assertThat(facade.isSelectorDefined(1)).isFalse();
+ assertThat(facade.isSelectorDefined(2)).isTrue();
+ assertThat(facade.isSelectorDefined(3)).isTrue();
+ assertThat(facade.isSelectorDefined(4)).isTrue();
+ assertThat(facade.isSelectorDefined(5)).isFalse();
}
@Test
- public void testGetToolchainsForEmptyProperties()
- {
+ public void testGetToolchainsForEmptyProperties() {
Properties props = new Properties();
- InvokerProperties facade = new InvokerProperties( props );
+ InvokerProperties facade = new InvokerProperties(props);
Collection<InvokerToolchain> toolchains = facade.getToolchains();
- assertThat( toolchains ).isEmpty();
+ assertThat(toolchains).isEmpty();
- toolchains = facade.getToolchains( 1 );
- assertThat( toolchains ).isEmpty();
+ toolchains = facade.getToolchains(1);
+ assertThat(toolchains).isEmpty();
}
@Test
- public void testGetToolchains()
- {
+ public void testGetToolchains() {
Properties props = new Properties();
- props.put( "invoker.toolchain.jdk.version", "11" );
- InvokerProperties facade = new InvokerProperties( props );
+ props.put("invoker.toolchain.jdk.version", "11");
+ InvokerProperties facade = new InvokerProperties(props);
Collection<InvokerToolchain> toolchains = facade.getToolchains();
- assertThat( toolchains ).hasSize( 1 );
+ assertThat(toolchains).hasSize(1);
InvokerToolchain toolchain = toolchains.iterator().next();
- assertThat( toolchain.getType() ).isEqualTo( "jdk" );
- assertThat( toolchain.getProvides() ).containsExactlyEntriesOf( Collections.singletonMap( "version", "11" ) );
+ assertThat(toolchain.getType()).isEqualTo("jdk");
+ assertThat(toolchain.getProvides()).containsExactlyEntriesOf(Collections.singletonMap("version", "11"));
}
@Test
- public void testGetToolchainsWithIndex()
- {
+ public void testGetToolchainsWithIndex() {
Properties props = new Properties();
- props.put( "selector.1.invoker.toolchain.jdk.version", "11" );
- InvokerProperties facade = new InvokerProperties( props );
+ props.put("selector.1.invoker.toolchain.jdk.version", "11");
+ InvokerProperties facade = new InvokerProperties(props);
- Collection<InvokerToolchain> toolchains = facade.getToolchains( 1 );
- assertThat( toolchains ).hasSize( 1 );
+ Collection<InvokerToolchain> toolchains = facade.getToolchains(1);
+ assertThat(toolchains).hasSize(1);
InvokerToolchain toolchain = toolchains.iterator().next();
- assertThat( toolchain.getType() ).isEqualTo( "jdk" );
- assertThat( toolchain.getProvides() ).containsExactlyEntriesOf( Collections.singletonMap( "version", "11" ) );
+ assertThat(toolchain.getType()).isEqualTo("jdk");
+ assertThat(toolchain.getProvides()).containsExactlyEntriesOf(Collections.singletonMap("version", "11"));
}
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/InvokerSessionTest.java b/src/test/java/org/apache/maven/plugins/invoker/InvokerSessionTest.java
index 8960670..da04638 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/InvokerSessionTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/InvokerSessionTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,36 +37,33 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-
import java.util.Collections;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.invoker.model.BuildJob;
import org.junit.Test;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
/**
* Unittest for {@link InvokerSession}
*/
-public class InvokerSessionTest
-{
+public class InvokerSessionTest {
@Test
- public void skipSummary()
- {
- Log logger = mock( Log.class );
- BuildJob skippedBuildJob = new BuildJob( "minvoker-279" );
- skippedBuildJob.setResult( BuildJob.Result.SKIPPED );
- InvokerSession session = new InvokerSession( Collections.singletonList( skippedBuildJob ) );
-
- session.logSummary( logger, false );
-
- verify( logger ).warn( "The following builds were skipped:" );
- verify( logger ).warn( "* minvoker-279" );
- verify( logger, never() ).error( anyString() );
- }
+ public void skipSummary() {
+ Log logger = mock(Log.class);
+ BuildJob skippedBuildJob = new BuildJob("minvoker-279");
+ skippedBuildJob.setResult(BuildJob.Result.SKIPPED);
+ InvokerSession session = new InvokerSession(Collections.singletonList(skippedBuildJob));
+
+ session.logSummary(logger, false);
+ verify(logger).warn("The following builds were skipped:");
+ verify(logger).warn("* minvoker-279");
+ verify(logger, never()).error(anyString());
+ }
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/JobExecutorTest.java b/src/test/java/org/apache/maven/plugins/invoker/JobExecutorTest.java
index abcc028..66aeef6 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/JobExecutorTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/JobExecutorTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -37,121 +55,108 @@ import static org.assertj.core.api.Assertions.fail;
*
* @author Slawomir Jaranowski
*/
-public class JobExecutorTest
-{
+public class JobExecutorTest {
@Test
- public void emptyJobList()
- {
- JobExecutor jobExecutor = new JobExecutor( Collections.emptyList(), 1 );
+ public void emptyJobList() {
+ JobExecutor jobExecutor = new JobExecutor(Collections.emptyList(), 1);
- jobExecutor.forEach( job -> fail( "fail" ) );
+ jobExecutor.forEach(job -> fail("fail"));
}
@Test
- public void failedJob()
- {
- BuildJob job = aJob( "job1", 100 );
+ public void failedJob() {
+ BuildJob job = aJob("job1", 100);
- JobExecutor jobExecutor = new JobExecutor( Collections.singletonList( job ), 1 );
+ JobExecutor jobExecutor = new JobExecutor(Collections.singletonList(job), 1);
- jobExecutor.forEach( j -> fail( "fail " + j.getProject() ) );
+ jobExecutor.forEach(j -> fail("fail " + j.getProject()));
- assertThat( job.getResult() ).isEqualTo( BuildJob.Result.ERROR );
- assertThat( job.getFailureMessage() ).isEqualTo( "java.lang.AssertionError: fail job1" );
+ assertThat(job.getResult()).isEqualTo(BuildJob.Result.ERROR);
+ assertThat(job.getFailureMessage()).isEqualTo("java.lang.AssertionError: fail job1");
}
@Test
- public void jobsShouldBeGroupedAndExecutedInProperOrder()
- {
+ public void jobsShouldBeGroupedAndExecutedInProperOrder() {
Map<Integer, AtomicInteger> jobsCounter = new HashMap<>();
- jobsCounter.put( 100, new AtomicInteger( 3 ) );
- jobsCounter.put( 10, new AtomicInteger( 2 ) );
- jobsCounter.put( 1, new AtomicInteger( 1 ) );
+ jobsCounter.put(100, new AtomicInteger(3));
+ jobsCounter.put(10, new AtomicInteger(2));
+ jobsCounter.put(1, new AtomicInteger(1));
- BuildJob job1 = aJob( "job1-100", 100 );
- BuildJob job2 = aJob( "job2-100", 100 );
- BuildJob job3 = aJob( "job3-100", 100 );
+ BuildJob job1 = aJob("job1-100", 100);
+ BuildJob job2 = aJob("job2-100", 100);
+ BuildJob job3 = aJob("job3-100", 100);
- BuildJob job4 = aJob( "job4-10", 10 );
- BuildJob job5 = aJob( "job5-10", 10 );
+ BuildJob job4 = aJob("job4-10", 10);
+ BuildJob job5 = aJob("job5-10", 10);
- BuildJob job6 = aJob( "job6-1", 1 );
+ BuildJob job6 = aJob("job6-1", 1);
// put jobs in wrong order
- List<BuildJob> jobs = Arrays.asList(
- job4, job5,
- job1, job2,
- job6,
- job3
- );
+ List<BuildJob> jobs = Arrays.asList(job4, job5, job1, job2, job6, job3);
- JobExecutor jobExecutor = new JobExecutor( jobs, 10 );
+ JobExecutor jobExecutor = new JobExecutor(jobs, 10);
- jobExecutor.forEach( job ->
- {
- jobsCounter.get( job.getOrdinal() ).decrementAndGet();
+ jobExecutor.forEach(job -> {
+ jobsCounter.get(job.getOrdinal()).decrementAndGet();
- switch ( job.getOrdinal() )
- {
+ switch (job.getOrdinal()) {
case 100:
- assertThat( jobsCounter.get( 10 ).get() )
- .as( "Jobs-10 must not be executed before 100" )
- .isEqualTo( 2 );
+ assertThat(jobsCounter.get(10).get())
+ .as("Jobs-10 must not be executed before 100")
+ .isEqualTo(2);
- assertThat( jobsCounter.get( 1 ).get() )
- .as( "Jobs-1 must not be executed before 100" )
- .isEqualTo( 1 );
+ assertThat(jobsCounter.get(1).get())
+ .as("Jobs-1 must not be executed before 100")
+ .isEqualTo(1);
break;
case 10:
- assertThat( jobsCounter.get( 100 ).get() )
- .as( "Jobs-100 must be executed before 10" )
- .isZero();
+ assertThat(jobsCounter.get(100).get())
+ .as("Jobs-100 must be executed before 10")
+ .isZero();
- assertThat( jobsCounter.get( 1 ).get() )
- .as( "Jobs-1 must not be executed before 10" )
- .isEqualTo( 1 );
+ assertThat(jobsCounter.get(1).get())
+ .as("Jobs-1 must not be executed before 10")
+ .isEqualTo(1);
break;
case 1:
- assertThat( jobsCounter.get( 100 ).get() )
- .as( "Jobs-100 must be executed before 1" )
- .isZero();
+ assertThat(jobsCounter.get(100).get())
+ .as("Jobs-100 must be executed before 1")
+ .isZero();
- assertThat( jobsCounter.get( 10 ).get() )
- .as( "Jobs-10 must be executed before 1" )
- .isZero();
+ assertThat(jobsCounter.get(10).get())
+ .as("Jobs-10 must be executed before 1")
+ .isZero();
break;
default:
- fail( "invalid job ordinal value %d", job.getOrdinal() );
+ fail("invalid job ordinal value %d", job.getOrdinal());
break;
}
- job.setResult( BuildJob.Result.SUCCESS );
- job.setDescription( Thread.currentThread().getName() );
- } );
+ job.setResult(BuildJob.Result.SUCCESS);
+ job.setDescription(Thread.currentThread().getName());
+ });
// all jobs have success status
- assertThat( jobs ).allSatisfy( job ->
- {
- assertThat( job.getDescription() ).isNotBlank();
- assertThat( job.getResult() ).as( job.getFailureMessage() ).isEqualTo( BuildJob.Result.SUCCESS );
- } );
+ assertThat(jobs).allSatisfy(job -> {
+ assertThat(job.getDescription()).isNotBlank();
+ assertThat(job.getResult()).as(job.getFailureMessage()).isEqualTo(BuildJob.Result.SUCCESS);
+ });
// jobs run on separate thread
- assertThat( job1.getDescription() ).isNotEqualTo( job2.getDescription() );
- assertThat( job1.getDescription() ).isNotEqualTo( job3.getDescription() );
- assertThat( job2.getDescription() ).isNotEqualTo( job3.getDescription() );
+ assertThat(job1.getDescription()).isNotEqualTo(job2.getDescription());
+ assertThat(job1.getDescription()).isNotEqualTo(job3.getDescription());
+ assertThat(job2.getDescription()).isNotEqualTo(job3.getDescription());
- assertThat( job4.getDescription() ).isNotEqualTo( job5.getDescription() );
+ assertThat(job4.getDescription()).isNotEqualTo(job5.getDescription());
}
- private BuildJob aJob( String name, int ordinal )
- {
- BuildJob buildJob = new BuildJob( name );
- buildJob.setOrdinal( ordinal );
+ private BuildJob aJob(String name, int ordinal) {
+ BuildJob buildJob = new BuildJob(name);
+ buildJob.setOrdinal(ordinal);
return buildJob;
}
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/SelectorTest.java b/src/test/java/org/apache/maven/plugins/invoker/SelectorTest.java
index 7c927d3..b87e72d 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/SelectorTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/SelectorTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -19,63 +37,59 @@ package org.apache.maven.plugins.invoker;
* under the License.
*/
-import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
/**
* Test for {@link Selector}.
*/
-public class SelectorTest
-{
+public class SelectorTest {
@Test
- public void testGlobalMatch()
- {
- Selector selector = new Selector( "3.2.5", "1.7", null );
+ public void testGlobalMatch() {
+ Selector selector = new Selector("3.2.5", "1.7", null);
Properties props = new Properties();
- props.setProperty( "invoker.maven.version", "3.0+" );
- InvokerProperties invokerProperties = new InvokerProperties( props );
- assertEquals( 0, selector.getSelection( invokerProperties ) );
+ props.setProperty("invoker.maven.version", "3.0+");
+ InvokerProperties invokerProperties = new InvokerProperties(props);
+ assertEquals(0, selector.getSelection(invokerProperties));
}
@Test
- public void testSelectorMatch()
- {
- Selector selector = new Selector( "3.2.5", "1.7", null );
+ public void testSelectorMatch() {
+ Selector selector = new Selector("3.2.5", "1.7", null);
Properties props = new Properties();
- props.setProperty( "selector.1.maven.version", "3.0+" );
- InvokerProperties invokerProperties = new InvokerProperties( props );
- assertEquals( 0, selector.getSelection( invokerProperties ) );
+ props.setProperty("selector.1.maven.version", "3.0+");
+ InvokerProperties invokerProperties = new InvokerProperties(props);
+ assertEquals(0, selector.getSelection(invokerProperties));
- props.setProperty( "selector.1.maven.version", "3.3.1+" );
- assertEquals( Selector.SELECTOR_MULTI, selector.getSelection( invokerProperties ) );
+ props.setProperty("selector.1.maven.version", "3.3.1+");
+ assertEquals(Selector.SELECTOR_MULTI, selector.getSelection(invokerProperties));
}
@Test
- public void testSelectorWithGlobalMatch()
- {
- Selector selector = new Selector( "3.2.5", "1.7", null );
+ public void testSelectorWithGlobalMatch() {
+ Selector selector = new Selector("3.2.5", "1.7", null);
Properties props = new Properties();
// invoker.maven.version is used by all selectors
- props.setProperty( "invoker.maven.version", "3.0+" );
- props.setProperty( "selector.1.java.version", "1.4+" );
- props.setProperty( "selector.2.os.family", "myos" );
- InvokerProperties invokerProperties = new InvokerProperties( props );
- assertEquals( 0, selector.getSelection( invokerProperties ) );
+ props.setProperty("invoker.maven.version", "3.0+");
+ props.setProperty("selector.1.java.version", "1.4+");
+ props.setProperty("selector.2.os.family", "myos");
+ InvokerProperties invokerProperties = new InvokerProperties(props);
+ assertEquals(0, selector.getSelection(invokerProperties));
- props.setProperty( "invoker.maven.version", "3.3.1+" );
- assertEquals( Selector.SELECTOR_MULTI, selector.getSelection( invokerProperties ) );
+ props.setProperty("invoker.maven.version", "3.3.1+");
+ assertEquals(Selector.SELECTOR_MULTI, selector.getSelection(invokerProperties));
- props.setProperty( "invoker.maven.version", "3.0+" );
- props.setProperty( "selector.1.maven.version", "3.3.1+" );
- assertEquals( Selector.SELECTOR_MULTI, selector.getSelection( invokerProperties ) );
+ props.setProperty("invoker.maven.version", "3.0+");
+ props.setProperty("selector.1.maven.version", "3.3.1+");
+ assertEquals(Selector.SELECTOR_MULTI, selector.getSelection(invokerProperties));
- props.setProperty( "selector.2.os.family", "!myos" );
- assertEquals( 0, selector.getSelection( invokerProperties ) );
+ props.setProperty("selector.2.os.family", "!myos");
+ assertEquals(0, selector.getSelection(invokerProperties));
}
-
}
diff --git a/src/test/java/org/apache/maven/plugins/invoker/SelectorUtilsTest.java b/src/test/java/org/apache/maven/plugins/invoker/SelectorUtilsTest.java
index 7b855eb..0297027 100644
--- a/src/test/java/org/apache/maven/plugins/invoker/SelectorUtilsTest.java
+++ b/src/test/java/org/apache/maven/plugins/invoker/SelectorUtilsTest.java
@@ -1,3 +1,21 @@
+/*
+ * 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.
+ */
package org.apache.maven.plugins.invoker;
/*
@@ -45,124 +63,111 @@ import static org.mockito.Mockito.when;
*
* @author Benjamin Bentmann
*/
-public class SelectorUtilsTest
-{
+public class SelectorUtilsTest {
@Test
- public void testParseList()
- {
+ public void testParseList() {
List<String> includes = new ArrayList<>();
List<String> excludes = new ArrayList<>();
- SelectorUtils.parseList( null, includes, excludes );
+ SelectorUtils.parseList(null, includes, excludes);
- SelectorUtils.parseList( " 1.5, !1.4, 1.6+ ", includes, excludes );
- assertEquals( Arrays.asList( "1.5", "1.6+" ), includes );
- assertEquals( Collections.singletonList( "1.4" ), excludes );
+ SelectorUtils.parseList(" 1.5, !1.4, 1.6+ ", includes, excludes);
+ assertEquals(Arrays.asList("1.5", "1.6+"), includes);
+ assertEquals(Collections.singletonList("1.4"), excludes);
}
@Test
- public void testParseVersion()
- {
- assertEquals( Arrays.asList( 1, 6, 0, 12 ), SelectorUtils.parseVersion( "1.6.0_12" ) );
+ public void testParseVersion() {
+ assertEquals(Arrays.asList(1, 6, 0, 12), SelectorUtils.parseVersion("1.6.0_12"));
- assertEquals( Arrays.asList( 1, 6, 0, 12 ), SelectorUtils.parseVersion( "1.6.0_12+" ) );
- assertEquals( Arrays.asList( 1, 6, 0, 12 ), SelectorUtils.parseVersion( "1.6.0_12-" ) );
+ assertEquals(Arrays.asList(1, 6, 0, 12), SelectorUtils.parseVersion("1.6.0_12+"));
+ assertEquals(Arrays.asList(1, 6, 0, 12), SelectorUtils.parseVersion("1.6.0_12-"));
}
@Test
- public void testCompareVersions()
- {
- assertTrue( SelectorUtils.compareVersions( Arrays.asList( 1, 6 ), Arrays.asList( 1, 6 ) ) == 0 );
+ public void testCompareVersions() {
+ assertTrue(SelectorUtils.compareVersions(Arrays.asList(1, 6), Arrays.asList(1, 6)) == 0);
- assertTrue( SelectorUtils.compareVersions( Arrays.asList( 1, 5 ), Arrays.asList( 1, 6 ) ) < 0 );
- assertTrue( SelectorUtils.compareVersions( Arrays.asList( 1, 6 ), Arrays.asList( 1, 5 ) ) > 0 );
+ assertTrue(SelectorUtils.compareVersions(Arrays.asList(1, 5), Arrays.asList(1, 6)) < 0);
+ assertTrue(SelectorUtils.compareVersions(Arrays.asList(1, 6), Arrays.asList(1, 5)) > 0);
- assertTrue( SelectorUtils.compareVersions( Collections.singletonList( 1 ), Arrays.asList( 1, 6 ) ) < 0 );
- assertTrue( SelectorUtils.compareVersions( Arrays.asList( 1, 6 ), Collections.singletonList( 1 ) ) > 0 );
+ assertTrue(SelectorUtils.compareVersions(Collections.singletonList(1), Arrays.asList(1, 6)) < 0);
+ assertTrue(SelectorUtils.compareVersions(Arrays.asList(1, 6), Collections.singletonList(1)) > 0);
}
@Test
- public void testIsMatchingJre()
- {
-
- assertFalse( SelectorUtils.isJreVersion( Arrays.asList( 1, 4, 2, 8 ), "1.5" ) );
- assertTrue( SelectorUtils.isJreVersion( Arrays.asList( 1, 5 ), "1.5" ) );
- assertTrue( SelectorUtils.isJreVersion( Arrays.asList( 1, 5, 9 ), "1.5" ) );
- assertFalse( SelectorUtils.isJreVersion( Arrays.asList( 1, 6 ), "1.5" ) );
-
- assertFalse( SelectorUtils.isJreVersion( Arrays.asList( 1, 4, 2, 8 ), "1.5+" ) );
- assertTrue( SelectorUtils.isJreVersion( Arrays.asList( 1, 5 ), "1.5+" ) );
- assertTrue( SelectorUtils.isJreVersion( Arrays.asList( 1, 5, 9 ), "1.5+" ) );
- assertTrue( SelectorUtils.isJreVersion( Arrays.asList( 1, 6 ), "1.5+" ) );
-
- assertTrue( SelectorUtils.isJreVersion( Arrays.asList( 1, 4, 2, 8 ), "1.5-" ) );
- assertFalse( SelectorUtils.isJreVersion( Arrays.asList( 1, 5 ), "1.5-" ) );
- assertFalse( SelectorUtils.isJreVersion( Arrays.asList( 1, 5, 9 ), "1.5-" ) );
- assertFalse( SelectorUtils.isJreVersion( Arrays.asList( 1, 6 ), "1.5-" ) );
-
- assertTrue( SelectorUtils.isJreVersion( (String) null, "1.5" ) );
- assertTrue( SelectorUtils.isJreVersion( "", "1.5" ) );
+ public void testIsMatchingJre() {
+
+ assertFalse(SelectorUtils.isJreVersion(Arrays.asList(1, 4, 2, 8), "1.5"));
+ assertTrue(SelectorUtils.isJreVersion(Arrays.asList(1, 5), "1.5"));
+ assertTrue(SelectorUtils.isJreVersion(Arrays.asList(1, 5, 9), "1.5"));
+ assertFalse(SelectorUtils.isJreVersion(Arrays.asList(1, 6), "1.5"));
+
+ assertFalse(SelectorUtils.isJreVersion(Arrays.asList(1, 4, 2, 8), "1.5+"));
+ assertTrue(SelectorUtils.isJreVersion(Arrays.asList(1, 5), "1.5+"));
+ assertTrue(SelectorUtils.isJreVersion(Arrays.asList(1, 5, 9), "1.5+"));
+ assertTrue(SelectorUtils.isJreVersion(Arrays.asList(1, 6), "1.5+"));
+
+ assertTrue(SelectorUtils.isJreVersion(Arrays.asList(1, 4, 2, 8), "1.5-"));
+ assertFalse(SelectorUtils.isJreVersion(Arrays.asList(1, 5), "1.5-"));
+ assertFalse(SelectorUtils.isJreVersion(Arrays.asList(1, 5, 9), "1.5-"));
+ assertFalse(SelectorUtils.isJreVersion(Arrays.asList(1, 6), "1.5-"));
+
+ assertTrue(SelectorUtils.isJreVersion((String) null, "1.5"));
+ assertTrue(SelectorUtils.isJreVersion("", "1.5"));
}
@Test
- public void testIsMatchingToolchain() throws Exception
- {
- InvokerToolchain openJdk9 = new InvokerToolchain( "jdk" );
- openJdk9.addProvides( "version", "9" );
- openJdk9.addProvides( "vendor", "openJDK" );
-
- InvokerToolchain maven360 = new InvokerToolchain( "maven" );
- openJdk9.addProvides( "version", "3.6.0" );
-
- ToolchainPrivateManager toolchainPrivateManager = mock( ToolchainPrivateManager.class );
- ToolchainPrivate jdkMatching = mock( ToolchainPrivate.class );
- when( jdkMatching.matchesRequirements( isA( Map.class ) ) ).thenReturn( true );
- when( jdkMatching.getType() ).thenReturn( "jdk" );
-
- ToolchainPrivate jdkMismatch = mock( ToolchainPrivate.class );
- when( jdkMismatch.getType() ).thenReturn( "jdk" );
-
- when( toolchainPrivateManager.getToolchainPrivates( "jdk" ) )
- .thenReturn( new ToolchainPrivate[] {jdkMatching} );
- assertTrue( SelectorUtils.isToolchain( toolchainPrivateManager, Collections.singleton( openJdk9 ) ) );
-
- when( toolchainPrivateManager.getToolchainPrivates( "jdk" ) )
- .thenReturn( new ToolchainPrivate[] {jdkMismatch} );
- assertFalse( SelectorUtils.isToolchain( toolchainPrivateManager, Collections.singleton( openJdk9 ) ) );
-
- when( toolchainPrivateManager.getToolchainPrivates( "jdk" ) )
- .thenReturn( new ToolchainPrivate[] {jdkMatching, jdkMismatch, jdkMatching} );
- assertTrue( SelectorUtils.isToolchain( toolchainPrivateManager, Collections.singleton( openJdk9 ) ) );
-
- when( toolchainPrivateManager.getToolchainPrivates( "jdk" ) )
- .thenReturn( new ToolchainPrivate[0] );
- assertFalse( SelectorUtils.isToolchain( toolchainPrivateManager, Collections.singleton( openJdk9 ) ) );
-
- when( toolchainPrivateManager.getToolchainPrivates( "jdk" ) )
- .thenReturn( new ToolchainPrivate[] {jdkMatching} );
- when( toolchainPrivateManager.getToolchainPrivates( "maven" ) )
- .thenReturn( new ToolchainPrivate[0] );
- assertFalse( SelectorUtils.isToolchain( toolchainPrivateManager, Arrays.asList( openJdk9, maven360 ) ) );
+ public void testIsMatchingToolchain() throws Exception {
+ InvokerToolchain openJdk9 = new InvokerToolchain("jdk");
+ openJdk9.addProvides("version", "9");
+ openJdk9.addProvides("vendor", "openJDK");
+
+ InvokerToolchain maven360 = new InvokerToolchain("maven");
+ openJdk9.addProvides("version", "3.6.0");
+
+ ToolchainPrivateManager toolchainPrivateManager = mock(ToolchainPrivateManager.class);
+ ToolchainPrivate jdkMatching = mock(ToolchainPrivate.class);
+ when(jdkMatching.matchesRequirements(isA(Map.class))).thenReturn(true);
+ when(jdkMatching.getType()).thenReturn("jdk");
+
+ ToolchainPrivate jdkMismatch = mock(ToolchainPrivate.class);
+ when(jdkMismatch.getType()).thenReturn("jdk");
+
+ when(toolchainPrivateManager.getToolchainPrivates("jdk")).thenReturn(new ToolchainPrivate[] {jdkMatching});
+ assertTrue(SelectorUtils.isToolchain(toolchainPrivateManager, Collections.singleton(openJdk9)));
+
+ when(toolchainPrivateManager.getToolchainPrivates("jdk")).thenReturn(new ToolchainPrivate[] {jdkMismatch});
+ assertFalse(SelectorUtils.isToolchain(toolchainPrivateManager, Collections.singleton(openJdk9)));
+
+ when(toolchainPrivateManager.getToolchainPrivates("jdk"))
+ .thenReturn(new ToolchainPrivate[] {jdkMatching, jdkMismatch, jdkMatching});
+ assertTrue(SelectorUtils.isToolchain(toolchainPrivateManager, Collections.singleton(openJdk9)));
+
+ when(toolchainPrivateManager.getToolchainPrivates("jdk")).thenReturn(new ToolchainPrivate[0]);
+ assertFalse(SelectorUtils.isToolchain(toolchainPrivateManager, Collections.singleton(openJdk9)));
+
+ when(toolchainPrivateManager.getToolchainPrivates("jdk")).thenReturn(new ToolchainPrivate[] {jdkMatching});
+ when(toolchainPrivateManager.getToolchainPrivates("maven")).thenReturn(new ToolchainPrivate[0]);
+ assertFalse(SelectorUtils.isToolchain(toolchainPrivateManager, Arrays.asList(openJdk9, maven360)));
}
@Test
- public void mavenVersionForNotExistingMavenHomeThrowException()
- {
- File mavenHome = new File( "not-existing-path" );
+ public void mavenVersionForNotExistingMavenHomeThrowException() {
+ File mavenHome = new File("not-existing-path");
- assertThatCode( () -> SelectorUtils.getMavenVersion( mavenHome ) )
- .isExactlyInstanceOf( IllegalArgumentException.class )
- .hasMessage( "Invalid Maven home installation directory: not-existing-path" );
+ assertThatCode(() -> SelectorUtils.getMavenVersion(mavenHome))
+ .isExactlyInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid Maven home installation directory: not-existing-path");
}
@Test
- public void mavenVersionFromMavenHome() throws IOException
- {
- File mavenHome = new File( System.getProperty( "maven.home" ) );
+ public void mavenVersionFromMavenHome() throws IOException {
+ File mavenHome = new File(System.getProperty("maven.home"));
- String mavenVersion = SelectorUtils.getMavenVersion( mavenHome );
+ String mavenVersion = SelectorUtils.getMavenVersion(mavenHome);
- assertThat( mavenVersion ).isNotBlank();
+ assertThat(mavenVersion).isNotBlank();
}
}