You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by bm...@apache.org on 2023/01/05 11:41:08 UTC
[maven-wrapper] 01/01: [MWRAPPER-89] update to maven-parent v39; spotless code style;
This is an automated email from the ASF dual-hosted git repository.
bmarwell pushed a commit to branch MWRAPPER-89_parent_v39_spotless
in repository https://gitbox.apache.org/repos/asf/maven-wrapper.git
commit 95890af00876b3c2d6e3fabee899d0786a6410c1
Author: Benjamin Marwell <bm...@apache.org>
AuthorDate: Thu Jan 5 12:42:58 2023 +0100
[MWRAPPER-89] update to maven-parent v39; spotless code style;
---
maven-wrapper-distribution/pom.xml | 20 +-
maven-wrapper-plugin/pom.xml | 10 +-
.../apache/maven/plugins/wrapper/WrapperMojo.java | 304 ++++++------
maven-wrapper/pom.xml | 4 +-
.../apache/maven/wrapper/BootstrapMainStarter.java | 65 ++-
.../apache/maven/wrapper/DefaultDownloader.java | 192 ++++---
.../java/org/apache/maven/wrapper/Downloader.java | 24 +-
.../maven/wrapper/HashAlgorithmVerifier.java | 67 +--
.../java/org/apache/maven/wrapper/Installer.java | 208 ++++----
.../main/java/org/apache/maven/wrapper/Logger.java | 36 +-
.../org/apache/maven/wrapper/MavenWrapperMain.java | 149 +++---
.../org/apache/maven/wrapper/PathAssembler.java | 107 ++--
.../maven/wrapper/SystemPropertiesHandler.java | 55 ++-
.../java/org/apache/maven/wrapper/Verifier.java | 24 +-
.../apache/maven/wrapper/WrapperConfiguration.java | 73 +--
.../org/apache/maven/wrapper/WrapperExecutor.java | 183 ++++---
.../wrapper/cli/AbstractCommandLineConverter.java | 44 +-
.../AbstractPropertiesCommandLineConverter.java | 53 +-
.../wrapper/cli/CommandLineArgumentException.java | 34 +-
.../maven/wrapper/cli/CommandLineConverter.java | 35 +-
.../maven/wrapper/cli/CommandLineOption.java | 96 ++--
.../maven/wrapper/cli/CommandLineParser.java | 550 ++++++++-------------
.../maven/wrapper/cli/ParsedCommandLine.java | 103 ++--
.../maven/wrapper/cli/ParsedCommandLineOption.java | 47 +-
.../cli/ProjectPropertiesCommandLineConverter.java | 31 +-
.../cli/SystemPropertiesCommandLineConverter.java | 33 +-
.../org/apache/maven/wrapper/DownloaderTest.java | 87 ++--
.../maven/wrapper/HashAlgorithmVerifierTest.java | 72 ++-
.../org/apache/maven/wrapper/InstallerTest.java | 412 +++++++--------
.../apache/maven/wrapper/PathAssemblerTest.java | 223 +++++----
.../maven/wrapper/SystemPropertiesHandlerTest.java | 81 +--
.../apache/maven/wrapper/WrapperExecutorTest.java | 477 +++++++++---------
pom.xml | 20 +-
33 files changed, 1963 insertions(+), 1956 deletions(-)
diff --git a/maven-wrapper-distribution/pom.xml b/maven-wrapper-distribution/pom.xml
index d5afb11..8171bb3 100644
--- a/maven-wrapper-distribution/pom.xml
+++ b/maven-wrapper-distribution/pom.xml
@@ -1,5 +1,4 @@
<?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,7 +17,6 @@ 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -27,7 +25,7 @@ under the License.
<artifactId>maven-wrapper-parent</artifactId>
<version>3.2.0-SNAPSHOT</version>
</parent>
-
+
<artifactId>maven-wrapper-distribution</artifactId>
<packaging>pom</packaging>
@@ -47,14 +45,6 @@ under the License.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- </execution>
- </executions>
<configuration>
<descriptors>
<descriptor>src/assembly/only-script.xml</descriptor>
@@ -66,6 +56,14 @@ under the License.
<delimiter>@@</delimiter>
</delimiters>
</configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <phase>package</phase>
+ </execution>
+ </executions>
</plugin>
</plugins>
</build>
diff --git a/maven-wrapper-plugin/pom.xml b/maven-wrapper-plugin/pom.xml
index 6d71489..37c6a89 100644
--- a/maven-wrapper-plugin/pom.xml
+++ b/maven-wrapper-plugin/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,7 +17,6 @@ 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>
@@ -33,9 +31,7 @@ under the License.
<packaging>maven-plugin</packaging>
<name>Apache Maven Wrapper Plugin</name>
- <description>
- The Maven Wrapper Plugin is a plugin that provides support for the Maven Wrapper by unpacking Maven Wrapper Distribution to current project.
- </description>
+ <description>The Maven Wrapper Plugin is a plugin that provides support for the Maven Wrapper by unpacking Maven Wrapper Distribution to current project.</description>
<prerequisites>
<maven>${mavenVersion}</maven>
@@ -162,7 +158,7 @@ under the License.
<localRepo>
<source>${project.build.directory}/local-repo</source>
</localRepo>
- <proxyRepo/>
+ <proxyRepo />
</repositories>
</configuration>
<executions>
diff --git a/maven-wrapper-plugin/src/main/java/org/apache/maven/plugins/wrapper/WrapperMojo.java b/maven-wrapper-plugin/src/main/java/org/apache/maven/plugins/wrapper/WrapperMojo.java
index 6632b29..998acb2 100644
--- a/maven-wrapper-plugin/src/main/java/org/apache/maven/plugins/wrapper/WrapperMojo.java
+++ b/maven-wrapper-plugin/src/main/java/org/apache/maven/plugins/wrapper/WrapperMojo.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.wrapper;
/*
@@ -19,8 +37,6 @@ package org.apache.maven.plugins.wrapper;
* under the License.
*/
-import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
-
import javax.inject.Inject;
import java.io.BufferedWriter;
@@ -53,16 +69,16 @@ import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.components.io.fileselectors.FileInfo;
import org.codehaus.plexus.components.io.fileselectors.FileSelector;
+import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
+
/**
* Unpacks the maven-wrapper distribution files to the current project source tree.
*
* @author Robert Scholte
* @since 3.0.0
*/
-@Mojo( name = "wrapper", aggregator = true, requiresDirectInvocation = true )
-public class WrapperMojo
- extends AbstractMojo
-{
+@Mojo(name = "wrapper", aggregator = true, requiresDirectInvocation = true)
+public class WrapperMojo extends AbstractMojo {
private static final String MVNW_REPOURL = "MVNW_REPOURL";
private static final String DEFAULT_REPOURL = "https://repo.maven.apache.org/maven2";
@@ -73,7 +89,7 @@ public class WrapperMojo
* The version of Maven to require, default value is the Runtime version of Maven.
* Can be any valid release above 2.0.9
*/
- @Parameter( property = "maven" )
+ @Parameter(property = "maven")
private String mavenVersion;
/**
@@ -89,53 +105,53 @@ public class WrapperMojo
*
* Value will be used as classifier of the downloaded file
*/
- @Parameter( defaultValue = "bin", property = "type" )
+ @Parameter(defaultValue = "bin", property = "type")
private String distributionType;
/**
* Include <code>mvnwDebug*</code> scripts?
*/
- @Parameter( defaultValue = "false", property = "includeDebug" )
+ @Parameter(defaultValue = "false", property = "includeDebug")
private boolean includeDebugScript;
/**
* The expected SHA-256 checksum of the <i>maven-wrapper.jar</i> that is
* used to load the configured Maven distribution.
*/
- @Parameter( property = "wrapperSha256Sum" )
+ @Parameter(property = "wrapperSha256Sum")
private String wrapperSha256Sum;
/**
* The expected SHA-256 checksum of the Maven distribution that is
* executed by the installed wrapper.
*/
- @Parameter( property = "distributionSha256Sum" )
+ @Parameter(property = "distributionSha256Sum")
private String distributionSha256Sum;
/**
* Determines if the Maven distribution should be downloaded
* on every execution of the Maven wrapper.
*/
- @Parameter( defaultValue = "false", property = "alwaysDownload" )
+ @Parameter(defaultValue = "false", property = "alwaysDownload")
private boolean alwaysDownload;
/**
* Determines if the Maven distribution should be unpacked
* on every execution of the Maven wrapper.
*/
- @Parameter( defaultValue = "false", property = "alwaysUnpack" )
+ @Parameter(defaultValue = "false", property = "alwaysUnpack")
private boolean alwaysUnpack;
// READONLY PARAMETERS
- @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;
// Waiting for https://github.com/eclipse/sisu.inject/pull/39 PathTypeConverter
- @Parameter( defaultValue = "${project.basedir}", readonly = true, required = true )
+ @Parameter(defaultValue = "${project.basedir}", readonly = true, required = true)
private File basedir;
// CONSTANTS
@@ -155,104 +171,86 @@ public class WrapperMojo
private Map<String, UnArchiver> unarchivers;
@Override
- public void execute()
- throws MojoExecutionException, MojoFailureException
- {
- mavenVersion = getVersion( mavenVersion, Maven.class, "org.apache.maven/maven-core" );
- String wrapperVersion = getVersion( null, this.getClass(), "org.apache.maven.plugins/maven-wrapper-plugin" );
-
- final Artifact artifact = downloadWrapperDistribution( wrapperVersion );
- final Path wrapperDir = createDirectories( basedir.toPath().resolve( ".mvn/wrapper" ) );
-
- cleanup( wrapperDir );
- unpack( artifact, basedir.toPath() );
- replaceProperties( wrapperVersion, wrapperDir );
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ mavenVersion = getVersion(mavenVersion, Maven.class, "org.apache.maven/maven-core");
+ String wrapperVersion = getVersion(null, this.getClass(), "org.apache.maven.plugins/maven-wrapper-plugin");
+
+ final Artifact artifact = downloadWrapperDistribution(wrapperVersion);
+ final Path wrapperDir = createDirectories(basedir.toPath().resolve(".mvn/wrapper"));
+
+ cleanup(wrapperDir);
+ unpack(artifact, basedir.toPath());
+ replaceProperties(wrapperVersion, wrapperDir);
}
- private Path createDirectories( Path dir )
- throws MojoExecutionException
- {
- try
- {
- return Files.createDirectories( dir );
- }
- catch ( IOException ioe )
- {
- throw new MojoExecutionException( ioe.getMessage(), ioe );
+ private Path createDirectories(Path dir) throws MojoExecutionException {
+ try {
+ return Files.createDirectories(dir);
+ } catch (IOException ioe) {
+ throw new MojoExecutionException(ioe.getMessage(), ioe);
}
}
- private void cleanup( Path wrapperDir )
- throws MojoExecutionException
- {
- try ( DirectoryStream<Path> dsClass = Files.newDirectoryStream( wrapperDir, "*.class" ) )
- {
- for ( Path file : dsClass )
- {
+ private void cleanup(Path wrapperDir) throws MojoExecutionException {
+ try (DirectoryStream<Path> dsClass = Files.newDirectoryStream(wrapperDir, "*.class")) {
+ for (Path file : dsClass) {
// Cleanup old compiled *.class
- Files.deleteIfExists( file );
+ Files.deleteIfExists(file);
}
- Files.deleteIfExists( wrapperDir.resolve( "MavenWrapperDownloader.java" ) );
- Files.deleteIfExists( wrapperDir.resolve( "maven-wrapper.jar" ) );
- }
- catch ( IOException ioe )
- {
- throw new MojoExecutionException( ioe.getMessage(), ioe );
+ Files.deleteIfExists(wrapperDir.resolve("MavenWrapperDownloader.java"));
+ Files.deleteIfExists(wrapperDir.resolve("maven-wrapper.jar"));
+ } catch (IOException ioe) {
+ throw new MojoExecutionException(ioe.getMessage(), ioe);
}
}
- private Artifact downloadWrapperDistribution( String wrapperVersion )
- throws MojoExecutionException
- {
- Artifact artifact =
- repositorySystem.createArtifactWithClassifier( WRAPPER_DISTRIBUTION_GROUP_ID,
- WRAPPER_DISTRIBUTION_ARTIFACT_ID, wrapperVersion,
- WRAPPER_DISTRIBUTION_EXTENSION, distributionType );
+ private Artifact downloadWrapperDistribution(String wrapperVersion) throws MojoExecutionException {
+ Artifact artifact = repositorySystem.createArtifactWithClassifier(
+ WRAPPER_DISTRIBUTION_GROUP_ID,
+ WRAPPER_DISTRIBUTION_ARTIFACT_ID,
+ wrapperVersion,
+ WRAPPER_DISTRIBUTION_EXTENSION,
+ distributionType);
MavenExecutionRequest executionRequest = session.getRequest();
ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest()
- .setArtifact( artifact )
- .setLocalRepository( session.getLocalRepository() )
- .setRemoteRepositories( session.getCurrentProject().getPluginArtifactRepositories() )
- .setOffline( executionRequest.isOffline() )
- .setForceUpdate( executionRequest.isUpdateSnapshots() );
-
- ArtifactResolutionResult resolveResult = repositorySystem.resolve( resolutionRequest );
-
- if ( !resolveResult.isSuccess() )
- {
- if ( executionRequest.isShowErrors() )
- {
- for ( Exception e : resolveResult.getExceptions() )
- {
- getLog().error( e.getMessage(), e );
+ .setArtifact(artifact)
+ .setLocalRepository(session.getLocalRepository())
+ .setRemoteRepositories(session.getCurrentProject().getPluginArtifactRepositories())
+ .setOffline(executionRequest.isOffline())
+ .setForceUpdate(executionRequest.isUpdateSnapshots());
+
+ ArtifactResolutionResult resolveResult = repositorySystem.resolve(resolutionRequest);
+
+ if (!resolveResult.isSuccess()) {
+ if (executionRequest.isShowErrors()) {
+ for (Exception e : resolveResult.getExceptions()) {
+ getLog().error(e.getMessage(), e);
}
}
- throw new MojoExecutionException( "artifact: " + artifact + " not resolved." );
+ throw new MojoExecutionException("artifact: " + artifact + " not resolved.");
}
return artifact;
}
- private void unpack( Artifact artifact, Path targetFolder )
- {
- UnArchiver unarchiver = unarchivers.get( WRAPPER_DISTRIBUTION_EXTENSION );
- unarchiver.setDestDirectory( targetFolder.toFile() );
- unarchiver.setSourceFile( artifact.getFile() );
- if ( !includeDebugScript )
- {
- unarchiver.setFileSelectors( new FileSelector[] { new FileSelector()
- {
- @Override
- public boolean isSelected( FileInfo fileInfo )
- {
- return !fileInfo.getName().contains( "Debug" );
+ private void unpack(Artifact artifact, Path targetFolder) {
+ UnArchiver unarchiver = unarchivers.get(WRAPPER_DISTRIBUTION_EXTENSION);
+ unarchiver.setDestDirectory(targetFolder.toFile());
+ unarchiver.setSourceFile(artifact.getFile());
+ if (!includeDebugScript) {
+ unarchiver.setFileSelectors(new FileSelector[] {
+ new FileSelector() {
+ @Override
+ public boolean isSelected(FileInfo fileInfo) {
+ return !fileInfo.getName().contains("Debug");
+ }
}
- } } );
+ });
}
unarchiver.extract();
- getLog().info( "Unpacked " + buffer().strong( distributionType ) + " type wrapper distribution " + artifact );
+ getLog().info("Unpacked " + buffer().strong(distributionType) + " type wrapper distribution " + artifact);
}
/**
@@ -263,82 +261,67 @@ public class WrapperMojo
* @param targetFolder the folder containing the wrapper.properties
* @throws MojoExecutionException if writing fails
*/
- private void replaceProperties( String wrapperVersion, Path targetFolder )
- throws MojoExecutionException
- {
+ private void replaceProperties(String wrapperVersion, Path targetFolder) throws MojoExecutionException {
String repoUrl = getRepoUrl();
- String distributionUrl =
- repoUrl + "/org/apache/maven/apache-maven/" + mavenVersion + "/apache-maven-" + mavenVersion + "-bin.zip";
+ String distributionUrl = repoUrl + "/org/apache/maven/apache-maven/" + mavenVersion + "/apache-maven-"
+ + mavenVersion + "-bin.zip";
String wrapperUrl = repoUrl + "/org/apache/maven/wrapper/maven-wrapper/" + wrapperVersion + "/maven-wrapper-"
- + wrapperVersion + ".jar";
+ + wrapperVersion + ".jar";
- Path wrapperPropertiesFile = targetFolder.resolve( "maven-wrapper.properties" );
+ Path wrapperPropertiesFile = targetFolder.resolve("maven-wrapper.properties");
- getLog().info( "Configuring .mvn/wrapper/maven-wrapper.properties to use "
- + buffer().strong( "Maven " + mavenVersion ) + " and download from " + repoUrl );
+ getLog().info("Configuring .mvn/wrapper/maven-wrapper.properties to use "
+ + buffer().strong("Maven " + mavenVersion) + " and download from " + repoUrl);
final String license = "# Licensed to the Apache Software Foundation (ASF) under one%n"
- + "# or more contributor license agreements. See the NOTICE file%n"
- + "# distributed with this work for additional information%n"
- + "# regarding copyright ownership. The ASF licenses this file%n"
- + "# to you under the Apache License, Version 2.0 (the%n"
- + "# \"License\"); you may not use this file except in compliance%n"
- + "# with the License. You may obtain a copy of the License at%n"
- + "#%n"
- + "# http://www.apache.org/licenses/LICENSE-2.0%n"
- + "#%n"
- + "# Unless required by applicable law or agreed to in writing,%n"
- + "# software distributed under the License is distributed on an%n"
- + "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY%n"
- + "# KIND, either express or implied. See the License for the%n"
- + "# specific language governing permissions and limitations%n"
- + "# under the License.%n";
-
- try ( BufferedWriter out = Files.newBufferedWriter( wrapperPropertiesFile, StandardCharsets.UTF_8 ) )
- {
- out.append( String.format( Locale.ROOT, license ) );
- out.append( "distributionUrl=" + distributionUrl + System.lineSeparator() );
- if ( distributionSha256Sum != null )
- {
- out.append( "distributionSha256Sum=" + distributionSha256Sum + System.lineSeparator() );
+ + "# or more contributor license agreements. See the NOTICE file%n"
+ + "# distributed with this work for additional information%n"
+ + "# regarding copyright ownership. The ASF licenses this file%n"
+ + "# to you under the Apache License, Version 2.0 (the%n"
+ + "# \"License\"); you may not use this file except in compliance%n"
+ + "# with the License. You may obtain a copy of the License at%n"
+ + "#%n"
+ + "# http://www.apache.org/licenses/LICENSE-2.0%n"
+ + "#%n"
+ + "# Unless required by applicable law or agreed to in writing,%n"
+ + "# software distributed under the License is distributed on an%n"
+ + "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY%n"
+ + "# KIND, either express or implied. See the License for the%n"
+ + "# specific language governing permissions and limitations%n"
+ + "# under the License.%n";
+
+ try (BufferedWriter out = Files.newBufferedWriter(wrapperPropertiesFile, StandardCharsets.UTF_8)) {
+ out.append(String.format(Locale.ROOT, license));
+ out.append("distributionUrl=" + distributionUrl + System.lineSeparator());
+ if (distributionSha256Sum != null) {
+ out.append("distributionSha256Sum=" + distributionSha256Sum + System.lineSeparator());
}
- out.append( "wrapperUrl=" + wrapperUrl + System.lineSeparator() );
- if ( wrapperSha256Sum != null )
- {
- out.append( "wrapperSha256Sum=" + wrapperSha256Sum + System.lineSeparator() );
+ out.append("wrapperUrl=" + wrapperUrl + System.lineSeparator());
+ if (wrapperSha256Sum != null) {
+ out.append("wrapperSha256Sum=" + wrapperSha256Sum + System.lineSeparator());
}
- if ( alwaysDownload )
- {
- out.append( "alwaysDownload=" + Boolean.TRUE + System.lineSeparator() );
+ if (alwaysDownload) {
+ out.append("alwaysDownload=" + Boolean.TRUE + System.lineSeparator());
}
- if ( alwaysUnpack )
- {
- out.append( "alwaysUnpack=" + Boolean.TRUE + System.lineSeparator() );
+ if (alwaysUnpack) {
+ out.append("alwaysUnpack=" + Boolean.TRUE + System.lineSeparator());
}
- }
- catch ( IOException ioe )
- {
- throw new MojoExecutionException( "Can't create maven-wrapper.properties", ioe );
+ } catch (IOException ioe) {
+ throw new MojoExecutionException("Can't create maven-wrapper.properties", ioe);
}
}
- private String getVersion( String defaultVersion, Class<?> clazz, String path )
- {
+ private String getVersion(String defaultVersion, Class<?> clazz, String path) {
String version = defaultVersion;
- if ( version == null || version.trim().length() == 0 || "true".equals( version ) )
- {
+ if (version == null || version.trim().length() == 0 || "true".equals(version)) {
Properties props = new Properties();
- try ( InputStream is = clazz.getResourceAsStream( "/META-INF/maven/" + path + "/pom.properties" ) )
- {
- if ( is != null )
- {
- props.load( is );
- version = props.getProperty( "version" );
+ try (InputStream is = clazz.getResourceAsStream("/META-INF/maven/" + path + "/pom.properties")) {
+ if (is != null) {
+ props.load(is);
+ version = props.getProperty("version");
}
- }
- catch ( IOException e )
- {
+ } catch (IOException e) {
// noop
}
}
@@ -348,33 +331,28 @@ public class WrapperMojo
/**
* Determine the repository URL to download Wrapper and Maven from.
*/
- private String getRepoUrl()
- {
+ private String getRepoUrl() {
// default
String repoUrl = DEFAULT_REPOURL;
// adapt to also support MVNW_REPOURL as supported by mvnw scripts from maven-wrapper
- String mvnwRepoUrl = System.getenv( MVNW_REPOURL );
- if ( mvnwRepoUrl != null && !mvnwRepoUrl.isEmpty() )
- {
+ String mvnwRepoUrl = System.getenv(MVNW_REPOURL);
+ if (mvnwRepoUrl != null && !mvnwRepoUrl.isEmpty()) {
repoUrl = mvnwRepoUrl;
- getLog().debug( "Using repo URL from " + MVNW_REPOURL + " environment variable." );
+ getLog().debug("Using repo URL from " + MVNW_REPOURL + " environment variable.");
}
// otherwise mirror from settings
- else if ( settings.getMirrors() != null && !settings.getMirrors().isEmpty() )
- {
- for ( Mirror current : settings.getMirrors() )
- {
- if ( "*".equals( current.getMirrorOf() ) )
- {
+ else if (settings.getMirrors() != null && !settings.getMirrors().isEmpty()) {
+ for (Mirror current : settings.getMirrors()) {
+ if ("*".equals(current.getMirrorOf())) {
repoUrl = current.getUrl();
break;
}
}
- getLog().debug( "Using repo URL from * mirror in settings file." );
+ getLog().debug("Using repo URL from * mirror in settings file.");
}
- getLog().debug( "Determined repo URL to use as " + repoUrl );
+ getLog().debug("Determined repo URL to use as " + repoUrl);
return repoUrl;
}
diff --git a/maven-wrapper/pom.xml b/maven-wrapper/pom.xml
index d8415b4..7a01936 100644
--- a/maven-wrapper/pom.xml
+++ b/maven-wrapper/pom.xml
@@ -1,5 +1,4 @@
<?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,7 +17,6 @@ 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -27,7 +25,7 @@ under the License.
<artifactId>maven-wrapper-parent</artifactId>
<version>3.2.0-SNAPSHOT</version>
</parent>
-
+
<artifactId>maven-wrapper</artifactId>
<name>Maven Wrapper Jar</name>
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/BootstrapMainStarter.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/BootstrapMainStarter.java
index 71f4186..627e461 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/BootstrapMainStarter.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/BootstrapMainStarter.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.wrapper;
/*
@@ -35,40 +53,35 @@ import java.util.Locale;
*
* @author Hans Dockter
*/
-public class BootstrapMainStarter
-{
- public void start( String[] args, Path mavenHome )
- throws Exception
- {
- final Path mavenJar = findLauncherJar( mavenHome );
- URLClassLoader contextClassLoader = new URLClassLoader( new URL[] { mavenJar.toUri().toURL() },
- ClassLoader.getSystemClassLoader().getParent() );
- Thread.currentThread().setContextClassLoader( contextClassLoader );
- Class<?> mainClass = contextClassLoader.loadClass( "org.codehaus.plexus.classworlds.launcher.Launcher" );
+public class BootstrapMainStarter {
+ public void start(String[] args, Path mavenHome) throws Exception {
+ final Path mavenJar = findLauncherJar(mavenHome);
+ URLClassLoader contextClassLoader = new URLClassLoader(
+ new URL[] {mavenJar.toUri().toURL()},
+ ClassLoader.getSystemClassLoader().getParent());
+ Thread.currentThread().setContextClassLoader(contextClassLoader);
+ Class<?> mainClass = contextClassLoader.loadClass("org.codehaus.plexus.classworlds.launcher.Launcher");
- System.setProperty( "maven.home", mavenHome.toAbsolutePath().toString() );
- System.setProperty( "classworlds.conf", mavenHome.resolve( "bin/m2.conf" ).toAbsolutePath().toString() );
+ System.setProperty("maven.home", mavenHome.toAbsolutePath().toString());
+ System.setProperty(
+ "classworlds.conf",
+ mavenHome.resolve("bin/m2.conf").toAbsolutePath().toString());
- Method mainMethod = mainClass.getMethod( "main", String[].class );
- mainMethod.invoke( null, new Object[] { args } );
+ Method mainMethod = mainClass.getMethod("main", String[].class);
+ mainMethod.invoke(null, new Object[] {args});
}
- private Path findLauncherJar( Path mavenHome )
- throws IOException
- {
- final Path mavenBoot = mavenHome.resolve( "boot" );
- if ( Files.isDirectory( mavenBoot ) )
- {
- try ( DirectoryStream<Path> ds = Files.newDirectoryStream( mavenBoot, "plexus-classworlds-*.jar" ) )
- {
+ private Path findLauncherJar(Path mavenHome) throws IOException {
+ final Path mavenBoot = mavenHome.resolve("boot");
+ if (Files.isDirectory(mavenBoot)) {
+ try (DirectoryStream<Path> ds = Files.newDirectoryStream(mavenBoot, "plexus-classworlds-*.jar")) {
Iterator<Path> iterator = ds.iterator();
- if ( iterator.hasNext() )
- {
+ if (iterator.hasNext()) {
return iterator.next();
}
}
}
- throw new FileNotFoundException( String.format( Locale.ROOT, "Could not locate the Maven launcher JAR"
- + " in Maven distribution '%s'.", mavenHome ) );
+ throw new FileNotFoundException(String.format(
+ Locale.ROOT, "Could not locate the Maven launcher JAR" + " in Maven distribution '%s'.", mavenHome));
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/DefaultDownloader.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/DefaultDownloader.java
index ae165ab..a9fe0f4 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/DefaultDownloader.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/DefaultDownloader.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.wrapper;
/*
@@ -19,9 +37,6 @@ package org.apache.maven.wrapper;
* under the License.
*/
-import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_PASSWORD;
-import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_USERNAME;
-
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
@@ -36,90 +51,77 @@ import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Locale;
+import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_PASSWORD;
+import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_USERNAME;
+
/**
* @author Hans Dockter
*/
-public class DefaultDownloader
- implements Downloader
-{
+public class DefaultDownloader implements Downloader {
private final String applicationName;
private final String applicationVersion;
- public DefaultDownloader( String applicationName, String applicationVersion )
- {
+ public DefaultDownloader(String applicationName, String applicationVersion) {
this.applicationName = applicationName;
this.applicationVersion = applicationVersion;
configureProxyAuthentication();
configureAuthentication();
}
- private void configureProxyAuthentication()
- {
- if ( System.getProperty( "http.proxyUser" ) != null )
- {
- Authenticator.setDefault( new SystemPropertiesProxyAuthenticator() );
+ private void configureProxyAuthentication() {
+ if (System.getProperty("http.proxyUser") != null) {
+ Authenticator.setDefault(new SystemPropertiesProxyAuthenticator());
}
}
- private void configureAuthentication()
- {
- if ( System.getenv( MVNW_USERNAME ) != null && System.getenv( MVNW_PASSWORD ) != null
- && System.getProperty( "http.proxyUser" ) == null )
- {
- Authenticator.setDefault( new Authenticator()
- {
+ private void configureAuthentication() {
+ if (System.getenv(MVNW_USERNAME) != null
+ && System.getenv(MVNW_PASSWORD) != null
+ && System.getProperty("http.proxyUser") == null) {
+ Authenticator.setDefault(new Authenticator() {
@Override
- protected PasswordAuthentication getPasswordAuthentication()
- {
- return new PasswordAuthentication( System.getenv( MVNW_USERNAME ),
- System.getenv( MVNW_PASSWORD ).toCharArray() );
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return new PasswordAuthentication(
+ System.getenv(MVNW_USERNAME),
+ System.getenv(MVNW_PASSWORD).toCharArray());
}
- } );
+ });
}
}
@Override
- public void download( URI address, Path destination )
- throws Exception
- {
- if ( Files.exists( destination ) )
- {
+ public void download(URI address, Path destination) throws Exception {
+ if (Files.exists(destination)) {
return;
}
- Files.createDirectories( destination.getParent() );
+ Files.createDirectories(destination.getParent());
- if ( !"https".equals( address.getScheme() ) )
- {
- Logger.warn( "Using an insecure connection to download the Maven distribution."
- + " Please consider using HTTPS." );
+ if (!"https".equals(address.getScheme())) {
+ Logger.warn("Using an insecure connection to download the Maven distribution."
+ + " Please consider using HTTPS.");
}
- downloadInternal( address, destination );
+ downloadInternal(address, destination);
}
- private void downloadInternal( URI address, Path destination )
- throws IOException
- {
+ private void downloadInternal(URI address, Path destination) throws IOException {
URL url = address.toURL();
URLConnection conn = url.openConnection();
- addBasicAuthentication( address, conn );
+ addBasicAuthentication(address, conn);
final String userAgentValue = calculateUserAgent();
- conn.setRequestProperty( "User-Agent", userAgentValue );
+ conn.setRequestProperty("User-Agent", userAgentValue);
- try ( InputStream inStream = conn.getInputStream() )
- {
- Files.copy( inStream, destination, StandardCopyOption.REPLACE_EXISTING );
+ try (InputStream inStream = conn.getInputStream()) {
+ Files.copy(inStream, destination, StandardCopyOption.REPLACE_EXISTING);
}
}
- private void addBasicAuthentication( URI address, URLConnection connection )
- {
- String userInfo = calculateUserInfo( address );
- if ( userInfo == null )
- {
+ private void addBasicAuthentication(URI address, URLConnection connection) {
+ String userInfo = calculateUserInfo(address);
+ if (userInfo == null) {
return;
}
- connection.setRequestProperty( "Authorization", "Basic " + base64Encode( userInfo ) );
+ connection.setRequestProperty("Authorization", "Basic " + base64Encode(userInfo));
}
/**
@@ -132,69 +134,65 @@ public class DefaultDownloader
* @return Base64 encoded user info
* @throws RuntimeException if no public Base64 encoder is available on this JVM
*/
- private String base64Encode( String userInfo )
- {
+ private String base64Encode(String userInfo) {
ClassLoader loader = getClass().getClassLoader();
- try
- {
- Method getEncoderMethod = loader.loadClass( "java.util.Base64" ).getMethod( "getEncoder" );
+ try {
+ Method getEncoderMethod = loader.loadClass("java.util.Base64").getMethod("getEncoder");
Method encodeMethod =
- loader.loadClass( "java.util.Base64$Encoder" ).getMethod( "encodeToString", byte[].class );
- Object encoder = getEncoderMethod.invoke( null );
- return (String) encodeMethod.invoke( encoder,
- new Object[] { userInfo.getBytes( StandardCharsets.UTF_8 ) } );
- }
- catch ( Exception java7OrEarlier )
- {
- try
- {
- Method encodeMethod =
- loader.loadClass( "javax.xml.bind.DatatypeConverter" ).getMethod( "printBase64Binary",
- byte[].class );
- return (String) encodeMethod.invoke( null,
- new Object[] { userInfo.getBytes( StandardCharsets.UTF_8 ) } );
- }
- catch ( Exception java5OrEarlier )
- {
- throw new RuntimeException( "Downloading Maven distributions with HTTP Basic Authentication"
- + " is not supported on your JVM.", java5OrEarlier );
+ loader.loadClass("java.util.Base64$Encoder").getMethod("encodeToString", byte[].class);
+ Object encoder = getEncoderMethod.invoke(null);
+ return (String) encodeMethod.invoke(encoder, new Object[] {userInfo.getBytes(StandardCharsets.UTF_8)});
+ } catch (Exception java7OrEarlier) {
+ try {
+ Method encodeMethod = loader.loadClass("javax.xml.bind.DatatypeConverter")
+ .getMethod("printBase64Binary", byte[].class);
+ return (String) encodeMethod.invoke(null, new Object[] {userInfo.getBytes(StandardCharsets.UTF_8)});
+ } catch (Exception java5OrEarlier) {
+ throw new RuntimeException(
+ "Downloading Maven distributions with HTTP Basic Authentication"
+ + " is not supported on your JVM.",
+ java5OrEarlier);
}
}
}
- private String calculateUserInfo( URI uri )
- {
- String username = System.getenv( MVNW_USERNAME );
- String password = System.getenv( MVNW_PASSWORD );
- if ( username != null && password != null )
- {
+ private String calculateUserInfo(URI uri) {
+ String username = System.getenv(MVNW_USERNAME);
+ String password = System.getenv(MVNW_PASSWORD);
+ if (username != null && password != null) {
return username + ':' + password;
}
return uri.getUserInfo();
}
- private String calculateUserAgent()
- {
+ private String calculateUserAgent() {
String appVersion = applicationVersion;
- String javaVendor = System.getProperty( "java.vendor" );
- String javaVersion = System.getProperty( "java.version" );
- String javaVendorVersion = System.getProperty( "java.vm.version" );
- String osName = System.getProperty( "os.name" );
- String osVersion = System.getProperty( "os.version" );
- String osArch = System.getProperty( "os.arch" );
- return String.format( Locale.ROOT, "%s/%s (%s;%s;%s) (%s;%s;%s)", applicationName, appVersion, osName,
- osVersion, osArch, javaVendor, javaVersion, javaVendorVersion );
+ String javaVendor = System.getProperty("java.vendor");
+ String javaVersion = System.getProperty("java.version");
+ String javaVendorVersion = System.getProperty("java.vm.version");
+ String osName = System.getProperty("os.name");
+ String osVersion = System.getProperty("os.version");
+ String osArch = System.getProperty("os.arch");
+ return String.format(
+ Locale.ROOT,
+ "%s/%s (%s;%s;%s) (%s;%s;%s)",
+ applicationName,
+ appVersion,
+ osName,
+ osVersion,
+ osArch,
+ javaVendor,
+ javaVersion,
+ javaVendorVersion);
}
- private static class SystemPropertiesProxyAuthenticator
- extends Authenticator
- {
+ private static class SystemPropertiesProxyAuthenticator extends Authenticator {
@Override
- protected PasswordAuthentication getPasswordAuthentication()
- {
- return new PasswordAuthentication( System.getProperty( "http.proxyUser" ),
- System.getProperty( "http.proxyPassword", "" ).toCharArray() );
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return new PasswordAuthentication(
+ System.getProperty("http.proxyUser"),
+ System.getProperty("http.proxyPassword", "").toCharArray());
}
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Downloader.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Downloader.java
index 24be150..1c73c8a 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Downloader.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Downloader.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.wrapper;
/*
@@ -27,8 +45,6 @@ import java.nio.file.Path;
*
* @author Hans Dockter
*/
-public interface Downloader
-{
- void download( URI address, Path destination )
- throws Exception;
+public interface Downloader {
+ void download(URI address, Path destination) throws Exception;
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/HashAlgorithmVerifier.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/HashAlgorithmVerifier.java
index 2dbbd34..cf37bf0 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/HashAlgorithmVerifier.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/HashAlgorithmVerifier.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.wrapper;
/*
@@ -28,41 +46,34 @@ import java.util.Locale;
/**
* @author Rafael Winterhalter
*/
-public class HashAlgorithmVerifier implements Verifier
-{
+public class HashAlgorithmVerifier implements Verifier {
@Override
- public void verify( Path file, String property, String algorithm, String expectedSum )
- throws Exception
- {
- MessageDigest digest = MessageDigest.getInstance( algorithm );
- try ( InputStream inputStream = Files.newInputStream( file ) )
- {
- byte[] buffer = new byte[ 1024 * 8 ];
+ public void verify(Path file, String property, String algorithm, String expectedSum) throws Exception {
+ MessageDigest digest = MessageDigest.getInstance(algorithm);
+ try (InputStream inputStream = Files.newInputStream(file)) {
+ byte[] buffer = new byte[1024 * 8];
int length;
- while ( ( length = inputStream.read( buffer ) ) != -1 )
- {
- digest.update( buffer, 0, length );
+ while ((length = inputStream.read(buffer)) != -1) {
+ digest.update(buffer, 0, length);
}
}
byte[] hash = digest.digest();
- StringBuilder actualSum = new StringBuilder( hash.length * 2 );
- for ( byte aByte : hash )
- {
- actualSum.append( String.format( "%02x", aByte ) );
- }
- if ( expectedSum.contentEquals( actualSum ) )
- {
- Logger.info( String.format( Locale.ROOT,
- "Validated %s hash for %s to be equal (%s)",
- algorithm, file, expectedSum ) );
+ StringBuilder actualSum = new StringBuilder(hash.length * 2);
+ for (byte aByte : hash) {
+ actualSum.append(String.format("%02x", aByte));
}
- else
- {
- throw new RuntimeException( String.format( Locale.ROOT,
- "Failed to validate Maven distribution %s, your Maven distribution "
- + "might be compromised. If you updated your Maven version, you need to "
- + "update the specified %s property.", algorithm, property ) );
+ if (expectedSum.contentEquals(actualSum)) {
+ Logger.info(String.format(
+ Locale.ROOT, "Validated %s hash for %s to be equal (%s)", algorithm, file, expectedSum));
+ } else {
+ throw new RuntimeException(String.format(
+ Locale.ROOT,
+ "Failed to validate Maven distribution %s, your Maven distribution "
+ + "might be compromised. If you updated your Maven version, you need to "
+ + "update the specified %s property.",
+ algorithm,
+ property));
}
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Installer.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Installer.java
index 5b78414..b0682d8 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Installer.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Installer.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.wrapper;
/*
@@ -46,9 +64,8 @@ import java.util.zip.ZipFile;
*
* @author Hans Dockter
*/
-public class Installer
-{
- public static final Path DEFAULT_DISTRIBUTION_PATH = Paths.get( "wrapper", "dists" );
+public class Installer {
+ public static final Path DEFAULT_DISTRIBUTION_PATH = Paths.get("wrapper", "dists");
private final Downloader download;
@@ -56,93 +73,81 @@ public class Installer
private final PathAssembler pathAssembler;
- public Installer( Downloader download, Verifier verifier, PathAssembler pathAssembler )
- {
+ public Installer(Downloader download, Verifier verifier, PathAssembler pathAssembler) {
this.download = download;
this.verifier = verifier;
this.pathAssembler = pathAssembler;
}
- public Path createDist( WrapperConfiguration configuration )
- throws Exception
- {
+ public Path createDist(WrapperConfiguration configuration) throws Exception {
URI distributionUrl = configuration.getDistribution();
boolean alwaysDownload = configuration.isAlwaysDownload();
boolean alwaysUnpack = configuration.isAlwaysUnpack();
- boolean verifyDistributionSha256Sum = !configuration.getDistributionSha256Sum().isEmpty();
+ boolean verifyDistributionSha256Sum =
+ !configuration.getDistributionSha256Sum().isEmpty();
- PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution( configuration );
+ PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution(configuration);
Path localZipFile = localDistribution.getZipFile();
- if ( alwaysDownload || alwaysUnpack || Files.notExists( localZipFile ) )
- {
- Logger.info( "Installing Maven distribution " + localDistribution.getDistributionDir().toAbsolutePath() );
+ if (alwaysDownload || alwaysUnpack || Files.notExists(localZipFile)) {
+ Logger.info("Installing Maven distribution "
+ + localDistribution.getDistributionDir().toAbsolutePath());
}
boolean downloaded = false;
- if ( alwaysDownload || Files.notExists( localZipFile ) )
- {
- Logger.info( "Downloading " + distributionUrl );
- Path tmpZipFile = localZipFile.resolveSibling( localZipFile.getFileName() + ".part" );
- Files.deleteIfExists( tmpZipFile );
- download.download( distributionUrl, tmpZipFile );
- Files.move( tmpZipFile, localZipFile, StandardCopyOption.REPLACE_EXISTING );
- downloaded = Files.exists( localZipFile );
+ if (alwaysDownload || Files.notExists(localZipFile)) {
+ Logger.info("Downloading " + distributionUrl);
+ Path tmpZipFile = localZipFile.resolveSibling(localZipFile.getFileName() + ".part");
+ Files.deleteIfExists(tmpZipFile);
+ download.download(distributionUrl, tmpZipFile);
+ Files.move(tmpZipFile, localZipFile, StandardCopyOption.REPLACE_EXISTING);
+ downloaded = Files.exists(localZipFile);
}
Path distDir = localDistribution.getDistributionDir();
- List<Path> dirs = listDirs( distDir );
+ List<Path> dirs = listDirs(distDir);
- if ( downloaded || alwaysUnpack || dirs.isEmpty() )
- {
- if ( verifyDistributionSha256Sum )
- {
- verifier.verify( localZipFile,
+ if (downloaded || alwaysUnpack || dirs.isEmpty()) {
+ if (verifyDistributionSha256Sum) {
+ verifier.verify(
+ localZipFile,
"distributionSha256Sum",
Verifier.SHA_256_ALGORITHM,
- configuration.getDistributionSha256Sum() );
+ configuration.getDistributionSha256Sum());
}
- for ( Path dir : dirs )
- {
- Logger.info( "Deleting directory " + dir.toAbsolutePath() );
- deleteDir( dir );
+ for (Path dir : dirs) {
+ Logger.info("Deleting directory " + dir.toAbsolutePath());
+ deleteDir(dir);
}
- Logger.info( "Unzipping " + localZipFile.toAbsolutePath() + " to " + distDir.toAbsolutePath() );
- unzip( localZipFile, distDir );
- dirs = listDirs( distDir );
- if ( dirs.isEmpty() )
- {
- throw new RuntimeException( String.format( Locale.ROOT,
- "Maven distribution '%s' does not contain any directory."
- + " Expected to find exactly 1 directory.",
- distDir ) );
+ Logger.info("Unzipping " + localZipFile.toAbsolutePath() + " to " + distDir.toAbsolutePath());
+ unzip(localZipFile, distDir);
+ dirs = listDirs(distDir);
+ if (dirs.isEmpty()) {
+ throw new RuntimeException(String.format(
+ Locale.ROOT,
+ "Maven distribution '%s' does not contain any directory."
+ + " Expected to find exactly 1 directory.",
+ distDir));
}
- setExecutablePermissions( dirs.get( 0 ) );
+ setExecutablePermissions(dirs.get(0));
}
- if ( dirs.size() != 1 )
- {
- throw new RuntimeException( String.format( Locale.ROOT,
- "Maven distribution '%s' contains too many directories."
- + " Expected to find exactly 1 directory.",
- distDir ) );
+ if (dirs.size() != 1) {
+ throw new RuntimeException(String.format(
+ Locale.ROOT,
+ "Maven distribution '%s' contains too many directories." + " Expected to find exactly 1 directory.",
+ distDir));
}
- return dirs.get( 0 );
+ return dirs.get(0);
}
- private List<Path> listDirs( Path distDir )
- throws IOException
- {
+ private List<Path> listDirs(Path distDir) throws IOException {
List<Path> dirs = new ArrayList<>();
- if ( Files.exists( distDir ) )
- {
- try ( DirectoryStream<Path> dirStream = Files.newDirectoryStream( distDir ) )
- {
- for ( Path file : dirStream )
- {
- if ( Files.isDirectory( file ) )
- {
- dirs.add( file );
+ if (Files.exists(distDir)) {
+ try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(distDir)) {
+ for (Path file : dirStream) {
+ if (Files.isDirectory(file)) {
+ dirs.add(file);
}
}
}
@@ -150,86 +155,65 @@ public class Installer
return dirs;
}
- private void setExecutablePermissions( Path mavenHome )
- {
- if ( isWindows() )
- {
+ private void setExecutablePermissions(Path mavenHome) {
+ if (isWindows()) {
return;
}
- Path mavenCommand = mavenHome.resolve( "bin/mvn" );
- try
- {
- Set<PosixFilePermission> perms = PosixFilePermissions.fromString( "rwxr-xr-x" );
- Files.setPosixFilePermissions( mavenCommand, perms );
- }
- catch ( IOException e )
- {
- Logger.warn( "Could not set executable permissions for: " + mavenCommand.toAbsolutePath()
- + ". Please do this manually if you want to use Maven." );
+ Path mavenCommand = mavenHome.resolve("bin/mvn");
+ try {
+ Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-xr-x");
+ Files.setPosixFilePermissions(mavenCommand, perms);
+ } catch (IOException e) {
+ Logger.warn("Could not set executable permissions for: " + mavenCommand.toAbsolutePath()
+ + ". Please do this manually if you want to use Maven.");
}
}
- private boolean isWindows()
- {
- String osName = System.getProperty( "os.name" ).toLowerCase( Locale.US );
- return osName.contains( "windows" );
+ private boolean isWindows() {
+ String osName = System.getProperty("os.name").toLowerCase(Locale.US);
+ return osName.contains("windows");
}
- private void deleteDir( Path dirPath )
- throws IOException
- {
- Files.walkFileTree( dirPath, new SimpleFileVisitor<Path>()
- {
+ private void deleteDir(Path dirPath) throws IOException {
+ Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
@Override
- public FileVisitResult postVisitDirectory( Path dir, IOException exc )
- throws IOException
- {
- Files.delete( dir );
- if ( exc != null )
- {
+ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+ Files.delete(dir);
+ if (exc != null) {
throw exc;
}
return FileVisitResult.CONTINUE;
}
@Override
- public FileVisitResult visitFile( Path file, BasicFileAttributes attrs )
- throws IOException
- {
- Files.delete( file );
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ Files.delete(file);
return FileVisitResult.CONTINUE;
}
- } );
+ });
}
- public void unzip( Path zip, Path dest )
- throws IOException
- {
+ public void unzip(Path zip, Path dest) throws IOException {
final Path destDir = dest.normalize();
- try ( final ZipFile zipFile = new ZipFile( zip.toFile() ) )
- {
+ try (ZipFile zipFile = new ZipFile(zip.toFile())) {
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
- while ( entries.hasMoreElements() )
- {
+ while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
- Path fileEntry = destDir.resolve( entry.getName() ).normalize();
- if ( !fileEntry.startsWith( destDir ) )
- {
- throw new ZipException( "Zip includes an invalid entry: " + entry.getName() );
+ Path fileEntry = destDir.resolve(entry.getName()).normalize();
+ if (!fileEntry.startsWith(destDir)) {
+ throw new ZipException("Zip includes an invalid entry: " + entry.getName());
}
- if ( entry.isDirectory() )
- {
+ if (entry.isDirectory()) {
continue;
}
- Files.createDirectories( fileEntry.getParent() );
+ Files.createDirectories(fileEntry.getParent());
- try ( InputStream inStream = zipFile.getInputStream( entry ) )
- {
- Files.copy( inStream, fileEntry );
+ try (InputStream inStream = zipFile.getInputStream(entry)) {
+ Files.copy(inStream, fileEntry);
}
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Logger.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Logger.java
index 5968b90..53bdc55 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Logger.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Logger.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.wrapper;
/*
@@ -22,20 +40,16 @@ package org.apache.maven.wrapper;
/**
* @author <a href="mailto:konstantin.sobolev@gmail.com">Konstantin Sobolev</a>
*/
-public final class Logger
-{
- private static final boolean VERBOSE = Boolean.parseBoolean( System.getenv( MavenWrapperMain.MVNW_VERBOSE ) );
+public final class Logger {
+ private static final boolean VERBOSE = Boolean.parseBoolean(System.getenv(MavenWrapperMain.MVNW_VERBOSE));
- public static void info( String msg )
- {
- if ( VERBOSE )
- {
- System.out.printf( "[INFO] %s%n", msg );
+ public static void info(String msg) {
+ if (VERBOSE) {
+ System.out.printf("[INFO] %s%n", msg);
}
}
- public static void warn( String msg )
- {
- System.err.printf( "[WARNING] %s%n", msg );
+ public static void warn(String msg) {
+ System.err.printf("[WARNING] %s%n", msg);
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/MavenWrapperMain.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/MavenWrapperMain.java
index 09d8ab4..3253356 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/MavenWrapperMain.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/MavenWrapperMain.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.wrapper;
/*
@@ -19,8 +37,8 @@ package org.apache.maven.wrapper;
* under the License.
*/
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
@@ -38,12 +56,12 @@ import org.apache.maven.wrapper.cli.SystemPropertiesCommandLineConverter;
*
* @author Hans Dockter
*/
-public class MavenWrapperMain
-{
+public class MavenWrapperMain {
private static final String POM_PROPERTIES =
- "/META-INF/maven/org.apache.maven.wrapper/maven-wrapper/pom.properties";
+ "/META-INF/maven/org.apache.maven.wrapper/maven-wrapper/pom.properties";
- private static final Path DEFAULT_MAVEN_USER_HOME = Paths.get( System.getProperty( "user.home" ) ).resolve( ".m2" );
+ private static final Path DEFAULT_MAVEN_USER_HOME =
+ Paths.get(System.getProperty("user.home")).resolve(".m2");
public static final String MAVEN_USER_HOME_PROPERTY_KEY = "maven.user.home";
@@ -57,104 +75,91 @@ public class MavenWrapperMain
public static final String MVNW_REPOURL = "MVNW_REPOURL";
- public static void main( String[] args )
- throws Exception
- {
+ public static void main(String[] args) throws Exception {
Path wrapperJar = wrapperJar();
- Path propertiesFile = wrapperProperties( wrapperJar );
- Path rootDir = rootDir( wrapperJar );
+ Path propertiesFile = wrapperProperties(wrapperJar);
+ Path rootDir = rootDir(wrapperJar);
String wrapperVersion = wrapperVersion();
- Logger.info( "Apache Maven Wrapper " + wrapperVersion );
+ Logger.info("Apache Maven Wrapper " + wrapperVersion);
Properties systemProperties = System.getProperties();
- systemProperties.putAll( parseSystemPropertiesFromArgs( args ) );
-
- addSystemProperties( rootDir );
-
- WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile( propertiesFile );
- wrapperExecutor.execute( args, new Installer( new DefaultDownloader( "mvnw", wrapperVersion ),
- new HashAlgorithmVerifier(),
- new PathAssembler( mavenUserHome() ) ),
- new BootstrapMainStarter() );
+ systemProperties.putAll(parseSystemPropertiesFromArgs(args));
+
+ addSystemProperties(rootDir);
+
+ WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+ wrapperExecutor.execute(
+ args,
+ new Installer(
+ new DefaultDownloader("mvnw", wrapperVersion),
+ new HashAlgorithmVerifier(),
+ new PathAssembler(mavenUserHome())),
+ new BootstrapMainStarter());
}
- private static Map<String, String> parseSystemPropertiesFromArgs( String[] args )
- {
+ private static Map<String, String> parseSystemPropertiesFromArgs(String[] args) {
SystemPropertiesCommandLineConverter converter = new SystemPropertiesCommandLineConverter();
CommandLineParser commandLineParser = new CommandLineParser();
- converter.configure( commandLineParser );
+ converter.configure(commandLineParser);
commandLineParser.allowUnknownOptions();
- return converter.convert( commandLineParser.parse( args ) );
+ return converter.convert(commandLineParser.parse(args));
}
- private static void addSystemProperties( Path rootDir )
- {
- System.getProperties().putAll( SystemPropertiesHandler.getSystemProperties( mavenUserHome()
- .resolve( "maven.properties" ) ) );
- System.getProperties().putAll( SystemPropertiesHandler.getSystemProperties( rootDir
- .resolve( "maven.properties" ) ) );
+ private static void addSystemProperties(Path rootDir) {
+ System.getProperties()
+ .putAll(SystemPropertiesHandler.getSystemProperties(
+ mavenUserHome().resolve("maven.properties")));
+ System.getProperties().putAll(SystemPropertiesHandler.getSystemProperties(rootDir.resolve("maven.properties")));
}
- private static Path rootDir( Path wrapperJar )
- {
+ private static Path rootDir(Path wrapperJar) {
return wrapperJar.getParent().getParent().getParent();
}
- private static Path wrapperProperties( Path wrapperJar )
- {
- return wrapperJar.resolveSibling( wrapperJar.getFileName().toString().replaceFirst( "\\.jar$",
- ".properties" ) );
+ private static Path wrapperProperties(Path wrapperJar) {
+ return wrapperJar.resolveSibling(wrapperJar.getFileName().toString().replaceFirst("\\.jar$", ".properties"));
}
- private static Path wrapperJar()
- {
+ private static Path wrapperJar() {
URI location;
- try
- {
- location = MavenWrapperMain.class.getProtectionDomain().getCodeSource().getLocation().toURI();
+ try {
+ location = MavenWrapperMain.class
+ .getProtectionDomain()
+ .getCodeSource()
+ .getLocation()
+ .toURI();
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
}
- catch ( URISyntaxException e )
- {
- throw new RuntimeException( e );
+ if (!"file".equals(location.getScheme())) {
+ throw new RuntimeException(String.format(
+ Locale.ROOT, "Cannot determine classpath for wrapper Jar from codebase '%s'.", location));
}
- if ( !"file".equals( location.getScheme() ) )
- {
- throw new RuntimeException( String.format( Locale.ROOT,
- "Cannot determine classpath for wrapper Jar from codebase '%s'.",
- location ) );
- }
- return Paths.get( location );
+ return Paths.get(location);
}
- static String wrapperVersion()
- {
- try ( InputStream resourceAsStream = MavenWrapperMain.class.getResourceAsStream( POM_PROPERTIES ) )
- {
- if ( resourceAsStream == null )
- {
- throw new IllegalStateException( POM_PROPERTIES + " not found." );
+ static String wrapperVersion() {
+ try (InputStream resourceAsStream = MavenWrapperMain.class.getResourceAsStream(POM_PROPERTIES)) {
+ if (resourceAsStream == null) {
+ throw new IllegalStateException(POM_PROPERTIES + " not found.");
}
Properties mavenProperties = new Properties();
- mavenProperties.load( resourceAsStream );
- String version = mavenProperties.getProperty( "version" );
- Objects.requireNonNull( version, "No version specified in " + POM_PROPERTIES );
+ mavenProperties.load(resourceAsStream);
+ String version = mavenProperties.getProperty("version");
+ Objects.requireNonNull(version, "No version specified in " + POM_PROPERTIES);
return version;
- }
- catch ( IOException e )
- {
- throw new RuntimeException( "Could not determine wrapper version.", e );
+ } catch (IOException e) {
+ throw new RuntimeException("Could not determine wrapper version.", e);
}
}
- private static Path mavenUserHome()
- {
- String mavenUserHome = System.getProperty( MAVEN_USER_HOME_PROPERTY_KEY );
- if ( mavenUserHome == null )
- {
- mavenUserHome = System.getenv( MAVEN_USER_HOME_ENV_KEY );
+ private static Path mavenUserHome() {
+ String mavenUserHome = System.getProperty(MAVEN_USER_HOME_PROPERTY_KEY);
+ if (mavenUserHome == null) {
+ mavenUserHome = System.getenv(MAVEN_USER_HOME_ENV_KEY);
}
- return mavenUserHome == null ? DEFAULT_MAVEN_USER_HOME : Paths.get( mavenUserHome );
+ return mavenUserHome == null ? DEFAULT_MAVEN_USER_HOME : Paths.get(mavenUserHome);
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/PathAssembler.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/PathAssembler.java
index dd4406f..bf4f051 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/PathAssembler.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/PathAssembler.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.wrapper;
/*
@@ -26,20 +44,16 @@ import java.nio.file.Paths;
/**
* @author Hans Dockter
*/
-public class PathAssembler
-{
+public class PathAssembler {
public static final String MAVEN_USER_HOME_STRING = "MAVEN_USER_HOME";
public static final String PROJECT_STRING = "PROJECT";
private Path mavenUserHome;
- public PathAssembler()
- {
- }
+ public PathAssembler() {}
- public PathAssembler( Path mavenUserHome )
- {
+ public PathAssembler(Path mavenUserHome) {
this.mavenUserHome = mavenUserHome;
}
@@ -49,70 +63,57 @@ public class PathAssembler
* @param configuration a wrapper configuration
* @return the local distribution
*/
- public LocalDistribution getDistribution( WrapperConfiguration configuration )
- {
- String baseName = getBaseName( configuration.getDistribution() );
- String distName = removeExtension( baseName );
- Path rootDirName = rootDirName( distName, configuration );
- Path distDir = getBaseDir( configuration.getDistributionBase() )
- .resolve( configuration.getDistributionPath() )
- .resolve( rootDirName );
- Path distZip = getBaseDir( configuration.getZipBase() )
- .resolve( configuration.getZipPath() )
- .resolve( rootDirName )
- .resolve( baseName );
- return new LocalDistribution( distDir, distZip );
+ public LocalDistribution getDistribution(WrapperConfiguration configuration) {
+ String baseName = getBaseName(configuration.getDistribution());
+ String distName = removeExtension(baseName);
+ Path rootDirName = rootDirName(distName, configuration);
+ Path distDir = getBaseDir(configuration.getDistributionBase())
+ .resolve(configuration.getDistributionPath())
+ .resolve(rootDirName);
+ Path distZip = getBaseDir(configuration.getZipBase())
+ .resolve(configuration.getZipPath())
+ .resolve(rootDirName)
+ .resolve(baseName);
+ return new LocalDistribution(distDir, distZip);
}
- private Path rootDirName( String distName, WrapperConfiguration configuration )
- {
- String urlHash = getHash( configuration.getDistribution() );
- return Paths.get( distName, urlHash );
+ private Path rootDirName(String distName, WrapperConfiguration configuration) {
+ String urlHash = getHash(configuration.getDistribution());
+ return Paths.get(distName, urlHash);
}
- private String getHash( URI path )
- {
- return Integer.toHexString( path.hashCode() );
+ private String getHash(URI path) {
+ return Integer.toHexString(path.hashCode());
}
- private String removeExtension( String name )
- {
- int dot = name.lastIndexOf( "." );
- return dot > 0 ? name.substring( 0, dot ) : name;
+ private String removeExtension(String name) {
+ int dot = name.lastIndexOf(".");
+ return dot > 0 ? name.substring(0, dot) : name;
}
- private String getBaseName( URI distUrl )
- {
- return Paths.get( distUrl.getPath() ).getFileName().toString();
+ private String getBaseName(URI distUrl) {
+ return Paths.get(distUrl.getPath()).getFileName().toString();
}
- private Path getBaseDir( String base )
- {
- if ( MAVEN_USER_HOME_STRING.equals( base ) )
- {
+ private Path getBaseDir(String base) {
+ if (MAVEN_USER_HOME_STRING.equals(base)) {
return mavenUserHome;
- }
- else if ( PROJECT_STRING.equals( base ) )
- {
- return Paths.get( System.getProperty( "user.dir" ) );
- }
- else
- {
- throw new RuntimeException( "Base: " + base + " is unknown" );
+ } else if (PROJECT_STRING.equals(base)) {
+ return Paths.get(System.getProperty("user.dir"));
+ } else {
+ throw new RuntimeException("Base: " + base + " is unknown");
}
}
/**
* Local distribution
*/
- public static class LocalDistribution
- {
+ public static class LocalDistribution {
private final Path distZip;
private final Path distDir;
- public LocalDistribution( Path distDir, Path distZip )
- {
+ public LocalDistribution(Path distDir, Path distZip) {
this.distDir = distDir;
this.distZip = distZip;
}
@@ -122,8 +123,7 @@ public class PathAssembler
*
* @return the location to install the distribution into
*/
- public Path getDistributionDir()
- {
+ public Path getDistributionDir() {
return distDir;
}
@@ -132,8 +132,7 @@ public class PathAssembler
*
* @return the location to install the distribution ZIP file to
*/
- public Path getZipFile()
- {
+ public Path getZipFile() {
return distZip;
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/SystemPropertiesHandler.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/SystemPropertiesHandler.java
index 201728a..4ca0726 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/SystemPropertiesHandler.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/SystemPropertiesHandler.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.wrapper;
/*
@@ -33,37 +51,28 @@ import java.util.regex.Pattern;
/**
* @author Hans Dockter
*/
-public class SystemPropertiesHandler
-{
+public class SystemPropertiesHandler {
- private static final Pattern SYSPROP_PATTERN = Pattern.compile( "systemProp\\.(.*)" );
+ private static final Pattern SYSPROP_PATTERN = Pattern.compile("systemProp\\.(.*)");
- public static Map<String, String> getSystemProperties( Path propertiesFile )
- {
+ public static Map<String, String> getSystemProperties(Path propertiesFile) {
Map<String, String> propertyMap = new HashMap<>();
- if ( !Files.isRegularFile( propertiesFile ) )
- {
+ if (!Files.isRegularFile(propertiesFile)) {
return propertyMap;
}
Properties properties = new Properties();
- try ( InputStream inStream = Files.newInputStream( propertiesFile ) )
- {
- properties.load( inStream );
- }
- catch ( IOException e )
- {
- throw new RuntimeException( "Error when loading properties file=" + propertiesFile, e );
+ try (InputStream inStream = Files.newInputStream(propertiesFile)) {
+ properties.load(inStream);
+ } catch (IOException e) {
+ throw new RuntimeException("Error when loading properties file=" + propertiesFile, e);
}
- for ( Entry<Object, Object> entrySet : properties.entrySet() )
- {
- Matcher matcher = SYSPROP_PATTERN.matcher( entrySet.getKey().toString() );
- if ( matcher.find() )
- {
- String key = matcher.group( 1 );
- if ( key.length() > 0 )
- {
- propertyMap.put( key, entrySet.getValue().toString() );
+ for (Entry<Object, Object> entrySet : properties.entrySet()) {
+ Matcher matcher = SYSPROP_PATTERN.matcher(entrySet.getKey().toString());
+ if (matcher.find()) {
+ String key = matcher.group(1);
+ if (key.length() > 0) {
+ propertyMap.put(key, entrySet.getValue().toString());
}
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Verifier.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Verifier.java
index bcea095..da2b868 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/Verifier.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/Verifier.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.wrapper;
/*
@@ -26,11 +44,9 @@ import java.nio.file.Path;
*
* @author Rafael Winterhalter
*/
-public interface Verifier
-{
+public interface Verifier {
String SHA_256_ALGORITHM = "SHA-256";
- void verify( Path file, String property, String algorithm, String expectedSum )
- throws Exception;
+ void verify(Path file, String property, String algorithm, String expectedSum) throws Exception;
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperConfiguration.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperConfiguration.java
index bffc4e9..7bb4d88 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperConfiguration.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperConfiguration.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.wrapper;
/*
@@ -25,15 +43,14 @@ import java.nio.file.Path;
/**
* Wrapper configuration.
*/
-public class WrapperConfiguration
-{
+public class WrapperConfiguration {
public static final String ALWAYS_UNPACK_ENV = "MAVEN_WRAPPER_ALWAYS_UNPACK";
public static final String ALWAYS_DOWNLOAD_ENV = "MAVEN_WRAPPER_ALWAYS_DOWNLOAD";
- private boolean alwaysUnpack = Boolean.parseBoolean( System.getenv( ALWAYS_UNPACK_ENV ) );
+ private boolean alwaysUnpack = Boolean.parseBoolean(System.getenv(ALWAYS_UNPACK_ENV));
- private boolean alwaysDownload = Boolean.parseBoolean( System.getenv( ALWAYS_DOWNLOAD_ENV ) );
+ private boolean alwaysDownload = Boolean.parseBoolean(System.getenv(ALWAYS_DOWNLOAD_ENV));
private URI distribution;
@@ -47,83 +64,67 @@ public class WrapperConfiguration
private String distributionSha256Sum;
- public boolean isAlwaysDownload()
- {
+ public boolean isAlwaysDownload() {
return alwaysDownload;
}
- public void setAlwaysDownload( boolean alwaysDownload )
- {
+ public void setAlwaysDownload(boolean alwaysDownload) {
this.alwaysDownload = alwaysDownload;
}
- public boolean isAlwaysUnpack()
- {
+ public boolean isAlwaysUnpack() {
return alwaysUnpack;
}
- public void setAlwaysUnpack( boolean alwaysUnpack )
- {
+ public void setAlwaysUnpack(boolean alwaysUnpack) {
this.alwaysUnpack = alwaysUnpack;
}
- public URI getDistribution()
- {
+ public URI getDistribution() {
return distribution;
}
- public void setDistribution( URI distribution )
- {
+ public void setDistribution(URI distribution) {
this.distribution = distribution;
}
- public String getDistributionBase()
- {
+ public String getDistributionBase() {
return distributionBase;
}
- public void setDistributionBase( String distributionBase )
- {
+ public void setDistributionBase(String distributionBase) {
this.distributionBase = distributionBase;
}
- public Path getDistributionPath()
- {
+ public Path getDistributionPath() {
return distributionPath;
}
- public void setDistributionPath( Path distributionPath )
- {
+ public void setDistributionPath(Path distributionPath) {
this.distributionPath = distributionPath;
}
- public String getZipBase()
- {
+ public String getZipBase() {
return zipBase;
}
- public void setZipBase( String zipBase )
- {
+ public void setZipBase(String zipBase) {
this.zipBase = zipBase;
}
- public Path getZipPath()
- {
+ public Path getZipPath() {
return zipPath;
}
- public void setZipPath( Path zipPath )
- {
+ public void setZipPath(Path zipPath) {
this.zipPath = zipPath;
}
- public String getDistributionSha256Sum()
- {
+ public String getDistributionSha256Sum() {
return distributionSha256Sum;
}
- public void setDistributionSha256Sum( String distributionSha256Sum )
- {
+ public void setDistributionSha256Sum(String distributionSha256Sum) {
this.distributionSha256Sum = distributionSha256Sum;
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperExecutor.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperExecutor.java
index b5ef48b..b1a38bf 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperExecutor.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperExecutor.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.wrapper;
/*
@@ -37,8 +55,7 @@ import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_REPOURL;
*
* @author Hans Dockter
*/
-public class WrapperExecutor
-{
+public class WrapperExecutor {
public static final String DISTRIBUTION_URL_PROPERTY = "distributionUrl";
public static final String DISTRIBUTION_BASE_PROPERTY = "distributionBase";
@@ -61,105 +78,81 @@ public class WrapperExecutor
private final WrapperConfiguration config = new WrapperConfiguration();
- public static WrapperExecutor forProjectDirectory( Path projectDir )
- {
- return new WrapperExecutor( projectDir.resolve( "maven/wrapper/maven-wrapper.properties" ), new Properties() );
+ public static WrapperExecutor forProjectDirectory(Path projectDir) {
+ return new WrapperExecutor(projectDir.resolve("maven/wrapper/maven-wrapper.properties"), new Properties());
}
- public static WrapperExecutor forWrapperPropertiesFile( Path propertiesFile )
- {
- if ( Files.notExists( propertiesFile ) )
- {
- throw new RuntimeException( String.format( Locale.ROOT, "Wrapper properties file '%s' does not exist.",
- propertiesFile ) );
+ public static WrapperExecutor forWrapperPropertiesFile(Path propertiesFile) {
+ if (Files.notExists(propertiesFile)) {
+ throw new RuntimeException(
+ String.format(Locale.ROOT, "Wrapper properties file '%s' does not exist.", propertiesFile));
}
- return new WrapperExecutor( propertiesFile, new Properties() );
+ return new WrapperExecutor(propertiesFile, new Properties());
}
- WrapperExecutor( Path propertiesFile, Properties properties )
- {
+ WrapperExecutor(Path propertiesFile, Properties properties) {
this.properties = properties;
this.propertiesFile = propertiesFile;
- if ( Files.exists( propertiesFile ) )
- {
- try
- {
- loadProperties( propertiesFile, properties );
- config.setDistribution( prepareDistributionUri() );
- config.setDistributionBase( getProperty( DISTRIBUTION_BASE_PROPERTY, config.getDistributionBase() ) );
- config.setDistributionPath( Paths.get( getProperty( DISTRIBUTION_PATH_PROPERTY,
- config.getDistributionPath().toString() ) ) );
- config.setZipBase( getProperty( ZIP_STORE_BASE_PROPERTY, config.getZipBase() ) );
- config.setZipPath( Paths.get( getProperty( ZIP_STORE_PATH_PROPERTY,
- config.getZipPath().toString() ) ) );
- config.setDistributionSha256Sum( getProperty( DISTRIBUTION_SHA_256_SUM, "" ) );
- config.setAlwaysUnpack( Boolean.parseBoolean( getProperty( ALWAYS_UNPACK,
- Boolean.FALSE.toString() ) ) );
- config.setAlwaysDownload( Boolean.parseBoolean( getProperty( ALWAYS_DOWNLOAD,
- Boolean.FALSE.toString() ) ) );
- }
- catch ( Exception e )
- {
- throw new RuntimeException( String.format( Locale.ROOT, "Could not load wrapper properties from '%s'.",
- propertiesFile ),
- e );
+ if (Files.exists(propertiesFile)) {
+ try {
+ loadProperties(propertiesFile, properties);
+ config.setDistribution(prepareDistributionUri());
+ config.setDistributionBase(getProperty(DISTRIBUTION_BASE_PROPERTY, config.getDistributionBase()));
+ config.setDistributionPath(Paths.get(getProperty(
+ DISTRIBUTION_PATH_PROPERTY, config.getDistributionPath().toString())));
+ config.setZipBase(getProperty(ZIP_STORE_BASE_PROPERTY, config.getZipBase()));
+ config.setZipPath(Paths.get(
+ getProperty(ZIP_STORE_PATH_PROPERTY, config.getZipPath().toString())));
+ config.setDistributionSha256Sum(getProperty(DISTRIBUTION_SHA_256_SUM, ""));
+ config.setAlwaysUnpack(Boolean.parseBoolean(getProperty(ALWAYS_UNPACK, Boolean.FALSE.toString())));
+ config.setAlwaysDownload(Boolean.parseBoolean(getProperty(ALWAYS_DOWNLOAD, Boolean.FALSE.toString())));
+ } catch (Exception e) {
+ throw new RuntimeException(
+ String.format(Locale.ROOT, "Could not load wrapper properties from '%s'.", propertiesFile), e);
}
}
}
- protected String getEnv( String key )
- {
- return System.getenv( key );
+ protected String getEnv(String key) {
+ return System.getenv(key);
}
- private URI prepareDistributionUri()
- throws URISyntaxException
- {
+ private URI prepareDistributionUri() throws URISyntaxException {
URI source = readDistroUrl();
- if ( source.getScheme() == null )
- {
+ if (source.getScheme() == null) {
// no scheme means someone passed a relative url. In our context only file relative urls make sense.
- return propertiesFile.getParent().resolve( source.getSchemeSpecificPart() ).toUri();
- }
- else
- {
- String mvnwRepoUrl = getEnv( MVNW_REPOURL );
- if ( mvnwRepoUrl != null && !mvnwRepoUrl.isEmpty() )
- {
- Logger.info( "Detected MVNW_REPOURL environment variable " + mvnwRepoUrl );
- if ( mvnwRepoUrl.endsWith( "/" ) )
- {
- mvnwRepoUrl = mvnwRepoUrl.substring( 0, mvnwRepoUrl.length() - 1 );
+ return propertiesFile
+ .getParent()
+ .resolve(source.getSchemeSpecificPart())
+ .toUri();
+ } else {
+ String mvnwRepoUrl = getEnv(MVNW_REPOURL);
+ if (mvnwRepoUrl != null && !mvnwRepoUrl.isEmpty()) {
+ Logger.info("Detected MVNW_REPOURL environment variable " + mvnwRepoUrl);
+ if (mvnwRepoUrl.endsWith("/")) {
+ mvnwRepoUrl = mvnwRepoUrl.substring(0, mvnwRepoUrl.length() - 1);
}
String distributionPath = source.getPath();
- int index = distributionPath.indexOf( "org/apache/maven" );
- if ( index > 1 )
- {
- distributionPath = "/".concat( distributionPath.substring( index ) );
- }
- else
- {
- Logger.warn( "distributionUrl don't contain package name " + source.getPath() );
+ int index = distributionPath.indexOf("org/apache/maven");
+ if (index > 1) {
+ distributionPath = "/".concat(distributionPath.substring(index));
+ } else {
+ Logger.warn("distributionUrl don't contain package name " + source.getPath());
}
- return new URI( mvnwRepoUrl + distributionPath );
+ return new URI(mvnwRepoUrl + distributionPath);
}
return source;
}
}
- private URI readDistroUrl()
- throws URISyntaxException
- {
- return new URI( getProperty( DISTRIBUTION_URL_PROPERTY ) );
+ private URI readDistroUrl() throws URISyntaxException {
+ return new URI(getProperty(DISTRIBUTION_URL_PROPERTY));
}
- private static void loadProperties( Path propertiesFile, Properties properties )
- throws IOException
- {
- try ( InputStream inStream = Files.newInputStream( propertiesFile ) )
- {
- properties.load( inStream );
+ private static void loadProperties(Path propertiesFile, Properties properties) throws IOException {
+ try (InputStream inStream = Files.newInputStream(propertiesFile)) {
+ properties.load(inStream);
}
}
@@ -169,8 +162,7 @@ public class WrapperExecutor
*
* @return the Maven distribution which this wrapper will use
*/
- public URI getDistribution()
- {
+ public URI getDistribution() {
return config.getDistribution();
}
@@ -179,37 +171,32 @@ public class WrapperExecutor
*
* @return the configuration for this wrapper
*/
- public WrapperConfiguration getConfiguration()
- {
+ public WrapperConfiguration getConfiguration() {
return config;
}
- public void execute( String[] args, Installer install, BootstrapMainStarter bootstrapMainStarter )
- throws Exception
- {
- Path mavenHome = install.createDist( config );
- bootstrapMainStarter.start( args, mavenHome );
+ public void execute(String[] args, Installer install, BootstrapMainStarter bootstrapMainStarter) throws Exception {
+ Path mavenHome = install.createDist(config);
+ bootstrapMainStarter.start(args, mavenHome);
}
- private String getProperty( String propertyName )
- {
- return getProperty( propertyName, null );
+ private String getProperty(String propertyName) {
+ return getProperty(propertyName, null);
}
- private String getProperty( String propertyName, String defaultValue )
- {
- String value = properties.getProperty( propertyName, defaultValue );
- if ( value == null )
- {
- reportMissingProperty( propertyName );
+ private String getProperty(String propertyName, String defaultValue) {
+ String value = properties.getProperty(propertyName, defaultValue);
+ if (value == null) {
+ reportMissingProperty(propertyName);
}
return value;
}
- private void reportMissingProperty( String propertyName )
- {
- throw new RuntimeException( String.format( Locale.ROOT,
- "No value with key '%s' specified in wrapper properties file '%s'.",
- propertyName, propertiesFile ) );
+ private void reportMissingProperty(String propertyName) {
+ throw new RuntimeException(String.format(
+ Locale.ROOT,
+ "No value with key '%s' specified in wrapper properties file '%s'.",
+ propertyName,
+ propertiesFile));
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractCommandLineConverter.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractCommandLineConverter.java
index 9ad5b3c..a94dbe7 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractCommandLineConverter.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractCommandLineConverter.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.wrapper.cli;
/*
@@ -24,29 +42,21 @@ package org.apache.maven.wrapper.cli;
*
* @param <T> type
*/
-public abstract class AbstractCommandLineConverter<T>
- implements CommandLineConverter<T>
-{
- public T convert( Iterable<String> args )
- throws CommandLineArgumentException
- {
+public abstract class AbstractCommandLineConverter<T> implements CommandLineConverter<T> {
+ public T convert(Iterable<String> args) throws CommandLineArgumentException {
CommandLineParser parser = new CommandLineParser();
- configure( parser );
- return convert( parser.parse( args ) );
+ configure(parser);
+ return convert(parser.parse(args));
}
- public T convert( ParsedCommandLine args )
- throws CommandLineArgumentException
- {
- return convert( args, newInstance() );
+ public T convert(ParsedCommandLine args) throws CommandLineArgumentException {
+ return convert(args, newInstance());
}
- public T convert( Iterable<String> args, T target )
- throws CommandLineArgumentException
- {
+ public T convert(Iterable<String> args, T target) throws CommandLineArgumentException {
CommandLineParser parser = new CommandLineParser();
- configure( parser );
- return convert( parser.parse( args ), target );
+ configure(parser);
+ return convert(parser.parse(args), target);
}
protected abstract T newInstance();
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractPropertiesCommandLineConverter.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractPropertiesCommandLineConverter.java
index fee974c..69a1158 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractPropertiesCommandLineConverter.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractPropertiesCommandLineConverter.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.wrapper.cli;
/*
@@ -25,40 +43,31 @@ import java.util.Map;
/**
* Converter form properties.
*/
-public abstract class AbstractPropertiesCommandLineConverter
- extends AbstractCommandLineConverter<Map<String, String>>
-{
+public abstract class AbstractPropertiesCommandLineConverter extends AbstractCommandLineConverter<Map<String, String>> {
protected abstract String getPropertyOption();
protected abstract String getPropertyOptionDetailed();
protected abstract String getPropertyOptionDescription();
- public void configure( CommandLineParser parser )
- {
- CommandLineOption option = parser.option( getPropertyOption(), getPropertyOptionDetailed() );
+ public void configure(CommandLineParser parser) {
+ CommandLineOption option = parser.option(getPropertyOption(), getPropertyOptionDetailed());
option = option.hasArguments();
- option.hasDescription( getPropertyOptionDescription() );
+ option.hasDescription(getPropertyOptionDescription());
}
- protected Map<String, String> newInstance()
- {
+ protected Map<String, String> newInstance() {
return new HashMap<String, String>();
}
- public Map<String, String> convert( ParsedCommandLine options, Map<String, String> properties )
- throws CommandLineArgumentException
- {
- for ( String keyValueExpression : options.option( getPropertyOption() ).getValues() )
- {
- int pos = keyValueExpression.indexOf( "=" );
- if ( pos < 0 )
- {
- properties.put( keyValueExpression, "" );
- }
- else
- {
- properties.put( keyValueExpression.substring( 0, pos ), keyValueExpression.substring( pos + 1 ) );
+ public Map<String, String> convert(ParsedCommandLine options, Map<String, String> properties)
+ throws CommandLineArgumentException {
+ for (String keyValueExpression : options.option(getPropertyOption()).getValues()) {
+ int pos = keyValueExpression.indexOf("=");
+ if (pos < 0) {
+ properties.put(keyValueExpression, "");
+ } else {
+ properties.put(keyValueExpression.substring(0, pos), keyValueExpression.substring(pos + 1));
}
}
return properties;
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineArgumentException.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineArgumentException.java
index 588b6f5..25ffa96 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineArgumentException.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineArgumentException.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.wrapper.cli;
/*
@@ -21,19 +39,15 @@ package org.apache.maven.wrapper.cli;
/**
* A {@code CommandLineArgumentException} is thrown when command-line arguments cannot be parsed.
- *
+ *
* @author Hans Dockter
*/
-public class CommandLineArgumentException
- extends RuntimeException
-{
- public CommandLineArgumentException( String message )
- {
- super( message );
+public class CommandLineArgumentException extends RuntimeException {
+ public CommandLineArgumentException(String message) {
+ super(message);
}
- public CommandLineArgumentException( String message, Throwable cause )
- {
- super( message, cause );
+ public CommandLineArgumentException(String message, Throwable cause) {
+ super(message, cause);
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineConverter.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineConverter.java
index f863901..fd18e4a 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineConverter.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineConverter.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.wrapper.cli;
/*
@@ -23,19 +41,14 @@ package org.apache.maven.wrapper.cli;
* @author Hans Dockter
* @param <T> type
*/
-public interface CommandLineConverter<T>
-{
- T convert( Iterable<String> args )
- throws CommandLineArgumentException;
+public interface CommandLineConverter<T> {
+ T convert(Iterable<String> args) throws CommandLineArgumentException;
- T convert( Iterable<String> args, T target )
- throws CommandLineArgumentException;
+ T convert(Iterable<String> args, T target) throws CommandLineArgumentException;
- T convert( ParsedCommandLine args )
- throws CommandLineArgumentException;
+ T convert(ParsedCommandLine args) throws CommandLineArgumentException;
- T convert( ParsedCommandLine args, T target )
- throws CommandLineArgumentException;
+ T convert(ParsedCommandLine args, T target) throws CommandLineArgumentException;
- void configure( CommandLineParser parser );
+ void configure(CommandLineParser parser);
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineOption.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineOption.java
index ededc45..582c0ec 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineOption.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineOption.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.wrapper.cli;
/*
@@ -24,10 +42,9 @@ import java.util.List;
import java.util.Set;
/**
- * Command line option.
+ * Command line option.
*/
-public class CommandLineOption
-{
+public class CommandLineOption {
private final Set<String> options = new HashSet<String>();
private Class<?> argumentType = Void.TYPE;
@@ -40,100 +57,81 @@ public class CommandLineOption
private boolean incubating;
- public CommandLineOption( Iterable<String> options )
- {
- for ( String option : options )
- {
- this.options.add( option );
+ public CommandLineOption(Iterable<String> options) {
+ for (String option : options) {
+ this.options.add(option);
}
}
- public Set<String> getOptions()
- {
+ public Set<String> getOptions() {
return options;
}
- public CommandLineOption hasArgument()
- {
+ public CommandLineOption hasArgument() {
argumentType = String.class;
return this;
}
- public CommandLineOption hasArguments()
- {
+ public CommandLineOption hasArguments() {
argumentType = List.class;
return this;
}
- public String getSubcommand()
- {
+ public String getSubcommand() {
return subcommand;
}
- public CommandLineOption mapsToSubcommand( String command )
- {
+ public CommandLineOption mapsToSubcommand(String command) {
this.subcommand = command;
return this;
}
- public String getDescription()
- {
+ public String getDescription() {
StringBuilder result = new StringBuilder();
- if ( description != null )
- {
- result.append( description );
+ if (description != null) {
+ result.append(description);
}
- if ( deprecationWarning != null )
- {
- if ( result.length() > 0 )
- {
- result.append( ' ' );
+ if (deprecationWarning != null) {
+ if (result.length() > 0) {
+ result.append(' ');
}
- result.append( "[deprecated - " );
- result.append( deprecationWarning );
- result.append( "]" );
+ result.append("[deprecated - ");
+ result.append(deprecationWarning);
+ result.append("]");
}
- if ( incubating )
- {
- if ( result.length() > 0 )
- {
- result.append( ' ' );
+ if (incubating) {
+ if (result.length() > 0) {
+ result.append(' ');
}
- result.append( "[incubating]" );
+ result.append("[incubating]");
}
return result.toString();
}
- public CommandLineOption hasDescription( String description )
- {
+ public CommandLineOption hasDescription(String description) {
this.description = description;
return this;
}
- public boolean getAllowsArguments()
- {
+ public boolean getAllowsArguments() {
return argumentType != Void.TYPE;
}
- public boolean getAllowsMultipleArguments()
- {
+ public boolean getAllowsMultipleArguments() {
return argumentType == List.class;
}
- public CommandLineOption deprecated( String deprecationWarning )
- {
+ public CommandLineOption deprecated(String deprecationWarning) {
this.deprecationWarning = deprecationWarning;
return this;
}
- public CommandLineOption incubating()
- {
+ public CommandLineOption incubating() {
incubating = true;
return this;
}
- public String getDeprecationWarning()
- {
+ public String getDeprecationWarning() {
return deprecationWarning;
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineParser.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineParser.java
index c2853ad..f85e7e2 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineParser.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineParser.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.wrapper.cli;
/*
@@ -41,7 +59,7 @@ import java.util.TreeSet;
* A command-line parser which supports a command/sub-command style command-line interface. Supports the following
* syntax:
* </p>
- *
+ *
* <pre>
* <option>* (<sub-command> <sub-command-option>*)*
* </pre>
@@ -60,8 +78,7 @@ import java.util.TreeSet;
* time. Use {@link ParsedCommandLine#getExtraArguments()} to obtain the non-option command-line arguments.</li>
* </ul>
*/
-public class CommandLineParser
-{
+public class CommandLineParser {
private Map<String, CommandLineOption> optionsByString = new HashMap<String, CommandLineOption>();
private boolean allowMixedOptions;
@@ -70,119 +87,87 @@ public class CommandLineParser
private final PrintWriter deprecationPrinter;
- public CommandLineParser()
- {
- this( new OutputStreamWriter( System.out ) );
+ public CommandLineParser() {
+ this(new OutputStreamWriter(System.out));
}
- public CommandLineParser( Writer deprecationPrinter )
- {
- this.deprecationPrinter = new PrintWriter( deprecationPrinter );
+ public CommandLineParser(Writer deprecationPrinter) {
+ this.deprecationPrinter = new PrintWriter(deprecationPrinter);
}
/**
* Parses the given command-line.
- *
+ *
* @param commandLine The command-line.
* @return The parsed command line.
* @throws org.apache.maven.wrapper.cli.CommandLineArgumentException On parse failure.
*/
- public ParsedCommandLine parse( String... commandLine )
- throws CommandLineArgumentException
- {
- return parse( Arrays.asList( commandLine ) );
+ public ParsedCommandLine parse(String... commandLine) throws CommandLineArgumentException {
+ return parse(Arrays.asList(commandLine));
}
/**
* Parses the given command-line.
- *
+ *
* @param commandLine The command-line.
* @return The parsed command line.
* @throws org.apache.maven.wrapper.cli.CommandLineArgumentException On parse failure.
*/
- public ParsedCommandLine parse( Iterable<String> commandLine )
- throws CommandLineArgumentException
- {
+ public ParsedCommandLine parse(Iterable<String> commandLine) throws CommandLineArgumentException {
ParsedCommandLine parsedCommandLine =
- new ParsedCommandLine( new HashSet<CommandLineOption>( optionsByString.values() ) );
- ParserState parseState = new BeforeFirstSubCommand( parsedCommandLine );
- for ( String arg : commandLine )
- {
- if ( parseState.maybeStartOption( arg ) )
- {
- if ( arg.equals( "--" ) )
- {
- parseState = new AfterOptions( parsedCommandLine );
- }
- else if ( arg.matches( "--[^=]+" ) )
- {
- OptionParserState parsedOption = parseState.onStartOption( arg, arg.substring( 2 ) );
+ new ParsedCommandLine(new HashSet<CommandLineOption>(optionsByString.values()));
+ ParserState parseState = new BeforeFirstSubCommand(parsedCommandLine);
+ for (String arg : commandLine) {
+ if (parseState.maybeStartOption(arg)) {
+ if (arg.equals("--")) {
+ parseState = new AfterOptions(parsedCommandLine);
+ } else if (arg.matches("--[^=]+")) {
+ OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2));
parseState = parsedOption.onStartNextArg();
- }
- else if ( arg.matches( "--[^=]+=.*" ) )
- {
- int endArg = arg.indexOf( '=' );
- OptionParserState parsedOption = parseState.onStartOption( arg, arg.substring( 2, endArg ) );
- parseState = parsedOption.onArgument( arg.substring( endArg + 1 ) );
- }
- else if ( arg.matches( "-[^=]=.*" ) )
- {
- OptionParserState parsedOption = parseState.onStartOption( arg, arg.substring( 1, 2 ) );
- parseState = parsedOption.onArgument( arg.substring( 3 ) );
- }
- else
- {
- assert arg.matches( "-[^-].*" );
- String option = arg.substring( 1 );
- if ( optionsByString.containsKey( option ) )
- {
- OptionParserState parsedOption = parseState.onStartOption( arg, option );
+ } else if (arg.matches("--[^=]+=.*")) {
+ int endArg = arg.indexOf('=');
+ OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2, endArg));
+ parseState = parsedOption.onArgument(arg.substring(endArg + 1));
+ } else if (arg.matches("-[^=]=.*")) {
+ OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(1, 2));
+ parseState = parsedOption.onArgument(arg.substring(3));
+ } else {
+ assert arg.matches("-[^-].*");
+ String option = arg.substring(1);
+ if (optionsByString.containsKey(option)) {
+ OptionParserState parsedOption = parseState.onStartOption(arg, option);
parseState = parsedOption.onStartNextArg();
- }
- else
- {
- String option1 = arg.substring( 1, 2 );
+ } else {
+ String option1 = arg.substring(1, 2);
OptionParserState parsedOption;
- if ( optionsByString.containsKey( option1 ) )
- {
- parsedOption = parseState.onStartOption( "-" + option1, option1 );
- if ( parsedOption.getHasArgument() )
- {
- parseState = parsedOption.onArgument( arg.substring( 2 ) );
- }
- else
- {
+ if (optionsByString.containsKey(option1)) {
+ parsedOption = parseState.onStartOption("-" + option1, option1);
+ if (parsedOption.getHasArgument()) {
+ parseState = parsedOption.onArgument(arg.substring(2));
+ } else {
parseState = parsedOption.onComplete();
- for ( int i = 2; i < arg.length(); i++ )
- {
- String optionStr = arg.substring( i, i + 1 );
- parsedOption = parseState.onStartOption( "-" + optionStr, optionStr );
+ for (int i = 2; i < arg.length(); i++) {
+ String optionStr = arg.substring(i, i + 1);
+ parsedOption = parseState.onStartOption("-" + optionStr, optionStr);
parseState = parsedOption.onComplete();
}
}
- }
- else
- {
- if ( allowUnknownOptions )
- {
+ } else {
+ if (allowUnknownOptions) {
// if we are allowing unknowns, just pass through the whole arg
- parsedOption = parseState.onStartOption( arg, option );
+ parsedOption = parseState.onStartOption(arg, option);
parseState = parsedOption.onComplete();
- }
- else
- {
+ } else {
// We are going to throw a CommandLineArgumentException below, but want the message
// to reflect that we didn't recognise the first char (i.e. the option specifier)
- parsedOption = parseState.onStartOption( "-" + option1, option1 );
+ parsedOption = parseState.onStartOption("-" + option1, option1);
parseState = parsedOption.onComplete();
}
}
}
}
- }
- else
- {
- parseState = parseState.onNonOption( arg );
+ } else {
+ parseState = parseState.onNonOption(arg);
}
}
@@ -190,91 +175,73 @@ public class CommandLineParser
return parsedCommandLine;
}
- public CommandLineParser allowMixedSubcommandsAndOptions()
- {
+ public CommandLineParser allowMixedSubcommandsAndOptions() {
allowMixedOptions = true;
return this;
}
- public CommandLineParser allowUnknownOptions()
- {
+ public CommandLineParser allowUnknownOptions() {
allowUnknownOptions = true;
return this;
}
/**
* Prints a usage message to the given stream.
- *
+ *
* @param out The output stream to write to.
*/
- public void printUsage( Appendable out )
- {
- Formatter formatter = new Formatter( out );
- Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>( new OptionComparator() );
- orderedOptions.addAll( optionsByString.values() );
+ public void printUsage(Appendable out) {
+ Formatter formatter = new Formatter(out);
+ Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>(new OptionComparator());
+ orderedOptions.addAll(optionsByString.values());
Map<String, String> lines = new LinkedHashMap<String, String>();
- for ( CommandLineOption option : orderedOptions )
- {
- Set<String> orderedOptionStrings = new TreeSet<String>( new OptionStringComparator() );
- orderedOptionStrings.addAll( option.getOptions() );
+ for (CommandLineOption option : orderedOptions) {
+ Set<String> orderedOptionStrings = new TreeSet<String>(new OptionStringComparator());
+ orderedOptionStrings.addAll(option.getOptions());
List<String> prefixedStrings = new ArrayList<String>();
- for ( String optionString : orderedOptionStrings )
- {
- if ( optionString.length() == 1 )
- {
- prefixedStrings.add( "-" + optionString );
- }
- else
- {
- prefixedStrings.add( "--" + optionString );
+ for (String optionString : orderedOptionStrings) {
+ if (optionString.length() == 1) {
+ prefixedStrings.add("-" + optionString);
+ } else {
+ prefixedStrings.add("--" + optionString);
}
}
- String key = join( prefixedStrings, ", " );
+ String key = join(prefixedStrings, ", ");
String value = option.getDescription();
- if ( value == null || value.length() == 0 )
- {
+ if (value == null || value.length() == 0) {
value = "";
}
- lines.put( key, value );
+ lines.put(key, value);
}
int max = 0;
- for ( String optionStr : lines.keySet() )
- {
- max = Math.max( max, optionStr.length() );
- }
- for ( Map.Entry<String, String> entry : lines.entrySet() )
- {
- if ( entry.getValue().length() == 0 )
- {
- formatter.format( "%s%n", entry.getKey() );
- }
- else
- {
- formatter.format( "%-" + max + "s %s%n", entry.getKey(), entry.getValue() );
+ for (String optionStr : lines.keySet()) {
+ max = Math.max(max, optionStr.length());
+ }
+ for (Map.Entry<String, String> entry : lines.entrySet()) {
+ if (entry.getValue().length() == 0) {
+ formatter.format("%s%n", entry.getKey());
+ } else {
+ formatter.format("%-" + max + "s %s%n", entry.getKey(), entry.getValue());
}
}
formatter.flush();
}
- private static String join( Collection<?> things, String separator )
- {
+ private static String join(Collection<?> things, String separator) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
- if ( separator == null )
- {
+ if (separator == null) {
separator = "";
}
- for ( Object thing : things )
- {
- if ( !first )
- {
- buffer.append( separator );
+ for (Object thing : things) {
+ if (!first) {
+ buffer.append(separator);
}
- buffer.append( thing.toString() );
+ buffer.append(thing.toString());
first = false;
}
return buffer.toString();
@@ -282,226 +249,179 @@ public class CommandLineParser
/**
* Defines a new option. By default, the option takes no arguments and has no description.
- *
+ *
* @param options The options values.
* @return The option, which can be further configured.
*/
- public CommandLineOption option( String... options )
- {
- for ( String option : options )
- {
- if ( optionsByString.containsKey( option ) )
- {
- throw new IllegalArgumentException( String.format( "Option '%s' is already defined.", option ) );
+ public CommandLineOption option(String... options) {
+ for (String option : options) {
+ if (optionsByString.containsKey(option)) {
+ throw new IllegalArgumentException(String.format("Option '%s' is already defined.", option));
}
- if ( option.startsWith( "-" ) )
- {
- throw new IllegalArgumentException( String.format( "Cannot add option '%s' as an option cannot"
- + " start with '-'.", option ) );
+ if (option.startsWith("-")) {
+ throw new IllegalArgumentException(
+ String.format("Cannot add option '%s' as an option cannot" + " start with '-'.", option));
}
}
- CommandLineOption option = new CommandLineOption( Arrays.asList( options ) );
- for ( String optionStr : option.getOptions() )
- {
- this.optionsByString.put( optionStr, option );
+ CommandLineOption option = new CommandLineOption(Arrays.asList(options));
+ for (String optionStr : option.getOptions()) {
+ this.optionsByString.put(optionStr, option);
}
return option;
}
- private static class OptionString
- {
+ private static class OptionString {
private final String arg;
private final String option;
- private OptionString( String arg, String option )
- {
+ private OptionString(String arg, String option) {
this.arg = arg;
this.option = option;
}
- public String getDisplayName()
- {
- return arg.startsWith( "--" ) ? "--" + option : "-" + option;
+ public String getDisplayName() {
+ return arg.startsWith("--") ? "--" + option : "-" + option;
}
@Override
- public String toString()
- {
+ public String toString() {
return getDisplayName();
}
}
- private abstract static class ParserState
- {
- public abstract boolean maybeStartOption( String arg );
+ private abstract static class ParserState {
+ public abstract boolean maybeStartOption(String arg);
- boolean isOption( String arg )
- {
- return arg.matches( "-.+" );
+ boolean isOption(String arg) {
+ return arg.matches("-.+");
}
- public abstract OptionParserState onStartOption( String arg, String option );
+ public abstract OptionParserState onStartOption(String arg, String option);
- public abstract ParserState onNonOption( String arg );
+ public abstract ParserState onNonOption(String arg);
- public void onCommandLineEnd()
- {
- }
+ public void onCommandLineEnd() {}
}
- private abstract class OptionAwareParserState
- extends ParserState
- {
+ private abstract class OptionAwareParserState extends ParserState {
protected final ParsedCommandLine commandLine;
- protected OptionAwareParserState( ParsedCommandLine commandLine )
- {
+ protected OptionAwareParserState(ParsedCommandLine commandLine) {
this.commandLine = commandLine;
}
@Override
- public boolean maybeStartOption( String arg )
- {
- return isOption( arg );
+ public boolean maybeStartOption(String arg) {
+ return isOption(arg);
}
@Override
- public ParserState onNonOption( String arg )
- {
- commandLine.addExtraValue( arg );
- return allowMixedOptions ? new AfterFirstSubCommand( commandLine ) : new AfterOptions( commandLine );
+ public ParserState onNonOption(String arg) {
+ commandLine.addExtraValue(arg);
+ return allowMixedOptions ? new AfterFirstSubCommand(commandLine) : new AfterOptions(commandLine);
}
}
- private class BeforeFirstSubCommand
- extends OptionAwareParserState
- {
- private BeforeFirstSubCommand( ParsedCommandLine commandLine )
- {
- super( commandLine );
+ private class BeforeFirstSubCommand extends OptionAwareParserState {
+ private BeforeFirstSubCommand(ParsedCommandLine commandLine) {
+ super(commandLine);
}
@Override
- public OptionParserState onStartOption( String arg, String option )
- {
- OptionString optionString = new OptionString( arg, option );
- CommandLineOption commandLineOption = optionsByString.get( option );
- if ( commandLineOption == null )
- {
- if ( allowUnknownOptions )
- {
- return new UnknownOptionParserState( arg, commandLine, this );
- }
- else
- {
- throw new CommandLineArgumentException( String.format( "Unknown command-line option '%s'.",
- optionString ) );
+ public OptionParserState onStartOption(String arg, String option) {
+ OptionString optionString = new OptionString(arg, option);
+ CommandLineOption commandLineOption = optionsByString.get(option);
+ if (commandLineOption == null) {
+ if (allowUnknownOptions) {
+ return new UnknownOptionParserState(arg, commandLine, this);
+ } else {
+ throw new CommandLineArgumentException(
+ String.format("Unknown command-line option '%s'.", optionString));
}
}
- return new KnownOptionParserState( optionString, commandLineOption, commandLine, this );
+ return new KnownOptionParserState(optionString, commandLineOption, commandLine, this);
}
}
- private class AfterFirstSubCommand
- extends OptionAwareParserState
- {
- private AfterFirstSubCommand( ParsedCommandLine commandLine )
- {
- super( commandLine );
+ private class AfterFirstSubCommand extends OptionAwareParserState {
+ private AfterFirstSubCommand(ParsedCommandLine commandLine) {
+ super(commandLine);
}
@Override
- public OptionParserState onStartOption( String arg, String option )
- {
- CommandLineOption commandLineOption = optionsByString.get( option );
- if ( commandLineOption == null )
- {
- return new UnknownOptionParserState( arg, commandLine, this );
+ public OptionParserState onStartOption(String arg, String option) {
+ CommandLineOption commandLineOption = optionsByString.get(option);
+ if (commandLineOption == null) {
+ return new UnknownOptionParserState(arg, commandLine, this);
}
- return new KnownOptionParserState( new OptionString( arg, option ), commandLineOption, commandLine, this );
+ return new KnownOptionParserState(new OptionString(arg, option), commandLineOption, commandLine, this);
}
}
- private static class AfterOptions
- extends ParserState
- {
+ private static class AfterOptions extends ParserState {
private final ParsedCommandLine commandLine;
- private AfterOptions( ParsedCommandLine commandLine )
- {
+ private AfterOptions(ParsedCommandLine commandLine) {
this.commandLine = commandLine;
}
@Override
- public boolean maybeStartOption( String arg )
- {
+ public boolean maybeStartOption(String arg) {
return false;
}
@Override
- public OptionParserState onStartOption( String arg, String option )
- {
- return new UnknownOptionParserState( arg, commandLine, this );
+ public OptionParserState onStartOption(String arg, String option) {
+ return new UnknownOptionParserState(arg, commandLine, this);
}
@Override
- public ParserState onNonOption( String arg )
- {
- commandLine.addExtraValue( arg );
+ public ParserState onNonOption(String arg) {
+ commandLine.addExtraValue(arg);
return this;
}
}
- private static class MissingOptionArgState
- extends ParserState
- {
+ private static class MissingOptionArgState extends ParserState {
private final OptionParserState option;
- private MissingOptionArgState( OptionParserState option )
- {
+ private MissingOptionArgState(OptionParserState option) {
this.option = option;
}
@Override
- public boolean maybeStartOption( String arg )
- {
- return isOption( arg );
+ public boolean maybeStartOption(String arg) {
+ return isOption(arg);
}
@Override
- public OptionParserState onStartOption( String arg, String option )
- {
- return this.option.onComplete().onStartOption( arg, option );
+ public OptionParserState onStartOption(String arg, String option) {
+ return this.option.onComplete().onStartOption(arg, option);
}
@Override
- public ParserState onNonOption( String arg )
- {
- return option.onArgument( arg );
+ public ParserState onNonOption(String arg) {
+ return option.onArgument(arg);
}
@Override
- public void onCommandLineEnd()
- {
+ public void onCommandLineEnd() {
option.onComplete();
}
}
- private abstract static class OptionParserState
- {
+ private abstract static class OptionParserState {
public abstract ParserState onStartNextArg();
- public abstract ParserState onArgument( String argument );
+ public abstract ParserState onArgument(String argument);
public abstract boolean getHasArgument();
public abstract ParserState onComplete();
}
- private class KnownOptionParserState
- extends OptionParserState
- {
+ private class KnownOptionParserState extends OptionParserState {
private final OptionString optionString;
private final CommandLineOption option;
@@ -512,9 +432,8 @@ public class CommandLineParser
private final List<String> values = new ArrayList<String>();
- private KnownOptionParserState( OptionString optionString, CommandLineOption option,
- ParsedCommandLine commandLine, ParserState state )
- {
+ private KnownOptionParserState(
+ OptionString optionString, CommandLineOption option, ParsedCommandLine commandLine, ParserState state) {
this.optionString = optionString;
this.option = option;
this.commandLine = commandLine;
@@ -522,154 +441,123 @@ public class CommandLineParser
}
@Override
- public ParserState onArgument( String argument )
- {
- if ( !getHasArgument() )
- {
- throw new CommandLineArgumentException( String.format( "Command-line option '%s' does not"
- + " take an argument.", optionString ) );
+ public ParserState onArgument(String argument) {
+ if (!getHasArgument()) {
+ throw new CommandLineArgumentException(
+ String.format("Command-line option '%s' does not" + " take an argument.", optionString));
}
- if ( argument.length() == 0 )
- {
- throw new CommandLineArgumentException( String.format( "An empty argument was provided"
- + " for command-line option '%s'.", optionString ) );
+ if (argument.length() == 0) {
+ throw new CommandLineArgumentException(String.format(
+ "An empty argument was provided" + " for command-line option '%s'.", optionString));
}
- values.add( argument );
+ values.add(argument);
return onComplete();
}
@Override
- public ParserState onStartNextArg()
- {
- if ( option.getAllowsArguments() && values.isEmpty() )
- {
- return new MissingOptionArgState( this );
+ public ParserState onStartNextArg() {
+ if (option.getAllowsArguments() && values.isEmpty()) {
+ return new MissingOptionArgState(this);
}
return onComplete();
}
@Override
- public boolean getHasArgument()
- {
+ public boolean getHasArgument() {
return option.getAllowsArguments();
}
@Override
- public ParserState onComplete()
- {
- if ( getHasArgument() && values.isEmpty() )
- {
- throw new CommandLineArgumentException( String.format( "No argument was provided"
- + " for command-line option '%s'.", optionString ) );
+ public ParserState onComplete() {
+ if (getHasArgument() && values.isEmpty()) {
+ throw new CommandLineArgumentException(
+ String.format("No argument was provided" + " for command-line option '%s'.", optionString));
}
- ParsedCommandLineOption parsedOption = commandLine.addOption( optionString.option, option );
- if ( values.size() + parsedOption.getValues().size() > 1 && !option.getAllowsMultipleArguments() )
- {
- throw new CommandLineArgumentException( String.format( "Multiple arguments were provided"
- + " for command-line option '%s'.", optionString ) );
+ ParsedCommandLineOption parsedOption = commandLine.addOption(optionString.option, option);
+ if (values.size() + parsedOption.getValues().size() > 1 && !option.getAllowsMultipleArguments()) {
+ throw new CommandLineArgumentException(String.format(
+ "Multiple arguments were provided" + " for command-line option '%s'.", optionString));
}
- for ( String value : values )
- {
- parsedOption.addArgument( value );
+ for (String value : values) {
+ parsedOption.addArgument(value);
}
- if ( option.getDeprecationWarning() != null )
- {
- deprecationPrinter.println( "The " + optionString + " option is deprecated - "
- + option.getDeprecationWarning() );
+ if (option.getDeprecationWarning() != null) {
+ deprecationPrinter.println(
+ "The " + optionString + " option is deprecated - " + option.getDeprecationWarning());
}
- if ( option.getSubcommand() != null )
- {
- return state.onNonOption( option.getSubcommand() );
+ if (option.getSubcommand() != null) {
+ return state.onNonOption(option.getSubcommand());
}
return state;
}
}
- private static class UnknownOptionParserState
- extends OptionParserState
- {
+ private static class UnknownOptionParserState extends OptionParserState {
private final ParserState state;
private final String arg;
private final ParsedCommandLine commandLine;
- private UnknownOptionParserState( String arg, ParsedCommandLine commandLine, ParserState state )
- {
+ private UnknownOptionParserState(String arg, ParsedCommandLine commandLine, ParserState state) {
this.arg = arg;
this.commandLine = commandLine;
this.state = state;
}
@Override
- public boolean getHasArgument()
- {
+ public boolean getHasArgument() {
return true;
}
@Override
- public ParserState onStartNextArg()
- {
+ public ParserState onStartNextArg() {
return onComplete();
}
@Override
- public ParserState onArgument( String argument )
- {
+ public ParserState onArgument(String argument) {
return onComplete();
}
@Override
- public ParserState onComplete()
- {
- commandLine.addExtraValue( arg );
+ public ParserState onComplete() {
+ commandLine.addExtraValue(arg);
return state;
}
}
- private static final class OptionComparator
- implements Comparator<CommandLineOption>
- {
- public int compare( CommandLineOption option1, CommandLineOption option2 )
- {
- String min1 = Collections.min( option1.getOptions(), new OptionStringComparator() );
- String min2 = Collections.min( option2.getOptions(), new OptionStringComparator() );
- return new CaseInsensitiveStringComparator().compare( min1, min2 );
+ private static final class OptionComparator implements Comparator<CommandLineOption> {
+ public int compare(CommandLineOption option1, CommandLineOption option2) {
+ String min1 = Collections.min(option1.getOptions(), new OptionStringComparator());
+ String min2 = Collections.min(option2.getOptions(), new OptionStringComparator());
+ return new CaseInsensitiveStringComparator().compare(min1, min2);
}
}
- private static final class CaseInsensitiveStringComparator
- implements Comparator<String>
- {
- public int compare( String option1, String option2 )
- {
- int diff = option1.compareToIgnoreCase( option2 );
- if ( diff != 0 )
- {
+ private static final class CaseInsensitiveStringComparator implements Comparator<String> {
+ public int compare(String option1, String option2) {
+ int diff = option1.compareToIgnoreCase(option2);
+ if (diff != 0) {
return diff;
}
- return option1.compareTo( option2 );
+ return option1.compareTo(option2);
}
}
- private static final class OptionStringComparator
- implements Comparator<String>
- {
- public int compare( String option1, String option2 )
- {
+ private static final class OptionStringComparator implements Comparator<String> {
+ public int compare(String option1, String option2) {
boolean short1 = option1.length() == 1;
boolean short2 = option2.length() == 1;
- if ( short1 && !short2 )
- {
+ if (short1 && !short2) {
return -1;
}
- if ( !short1 && short2 )
- {
+ if (!short1 && short2) {
return 1;
}
- return new CaseInsensitiveStringComparator().compare( option1, option2 );
+ return new CaseInsensitiveStringComparator().compare(option1, option2);
}
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLine.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLine.java
index 5e0abcb..6912abb 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLine.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLine.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.wrapper.cli;
/*
@@ -30,46 +48,38 @@ import java.util.Set;
/**
* Parsed command line.
*/
-public class ParsedCommandLine
-{
+public class ParsedCommandLine {
private final Map<String, ParsedCommandLineOption> optionsByString = new HashMap<String, ParsedCommandLineOption>();
private final Set<String> presentOptions = new HashSet<String>();
private final List<String> extraArguments = new ArrayList<String>();
- ParsedCommandLine( Iterable<CommandLineOption> options )
- {
- for ( CommandLineOption option : options )
- {
+ ParsedCommandLine(Iterable<CommandLineOption> options) {
+ for (CommandLineOption option : options) {
ParsedCommandLineOption parsedOption = new ParsedCommandLineOption();
- for ( String optionStr : option.getOptions() )
- {
- optionsByString.put( optionStr, parsedOption );
+ for (String optionStr : option.getOptions()) {
+ optionsByString.put(optionStr, parsedOption);
}
}
}
@Override
- public String toString()
- {
- return String.format( "options: %s, extraArguments: %s", quoteAndJoin( presentOptions ),
- quoteAndJoin( extraArguments ) );
+ public String toString() {
+ return String.format(
+ "options: %s, extraArguments: %s", quoteAndJoin(presentOptions), quoteAndJoin(extraArguments));
}
- private String quoteAndJoin( Iterable<String> strings )
- {
+ private String quoteAndJoin(Iterable<String> strings) {
StringBuilder output = new StringBuilder();
boolean isFirst = true;
- for ( String string : strings )
- {
- if ( !isFirst )
- {
- output.append( ", " );
+ for (String string : strings) {
+ if (!isFirst) {
+ output.append(", ");
}
- output.append( "'" );
- output.append( string );
- output.append( "'" );
+ output.append("'");
+ output.append(string);
+ output.append("'");
isFirst = false;
}
return output.toString();
@@ -77,28 +87,24 @@ public class ParsedCommandLine
/**
* Returns true if the given option is present in this command-line.
- *
+ *
* @param option The option, without the '-' or '--' prefix.
* @return true if the option is present.
*/
- public boolean hasOption( String option )
- {
- option( option );
- return presentOptions.contains( option );
+ public boolean hasOption(String option) {
+ option(option);
+ return presentOptions.contains(option);
}
/**
* See also {@link #hasOption}.
- *
+ *
* @param logLevelOptions the options to check
* @return true if any of the passed options is present
*/
- public boolean hasAnyOption( Collection<String> logLevelOptions )
- {
- for ( String option : logLevelOptions )
- {
- if ( hasOption( option ) )
- {
+ public boolean hasAnyOption(Collection<String> logLevelOptions) {
+ for (String option : logLevelOptions) {
+ if (hasOption(option)) {
return true;
}
}
@@ -107,34 +113,29 @@ public class ParsedCommandLine
/**
* Returns the value of the given option.
- *
+ *
* @param option The option, without the '-' or '--' prefix.
* @return The option. never returns null.
*/
- public ParsedCommandLineOption option( String option )
- {
- ParsedCommandLineOption parsedOption = optionsByString.get( option );
- if ( parsedOption == null )
- {
- throw new IllegalArgumentException( String.format( "Option '%s' not defined.", option ) );
+ public ParsedCommandLineOption option(String option) {
+ ParsedCommandLineOption parsedOption = optionsByString.get(option);
+ if (parsedOption == null) {
+ throw new IllegalArgumentException(String.format("Option '%s' not defined.", option));
}
return parsedOption;
}
- public List<String> getExtraArguments()
- {
+ public List<String> getExtraArguments() {
return extraArguments;
}
- void addExtraValue( String value )
- {
- extraArguments.add( value );
+ void addExtraValue(String value) {
+ extraArguments.add(value);
}
- ParsedCommandLineOption addOption( String optionStr, CommandLineOption option )
- {
- ParsedCommandLineOption parsedOption = optionsByString.get( optionStr );
- presentOptions.addAll( option.getOptions() );
+ ParsedCommandLineOption addOption(String optionStr, CommandLineOption option) {
+ ParsedCommandLineOption parsedOption = optionsByString.get(optionStr);
+ presentOptions.addAll(option.getOptions());
return parsedOption;
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLineOption.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLineOption.java
index 7139ec5..e2036e1 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLineOption.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLineOption.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.wrapper.cli;
/*
@@ -25,35 +43,28 @@ import java.util.List;
/**
* Parsed command line option.
*/
-public class ParsedCommandLineOption
-{
+public class ParsedCommandLineOption {
private final List<String> values = new ArrayList<String>();
- public String getValue()
- {
- if ( !hasValue() )
- {
- throw new IllegalStateException( "Option does not have any value." );
+ public String getValue() {
+ if (!hasValue()) {
+ throw new IllegalStateException("Option does not have any value.");
}
- if ( values.size() > 1 )
- {
- throw new IllegalStateException( "Option has multiple values." );
+ if (values.size() > 1) {
+ throw new IllegalStateException("Option has multiple values.");
}
- return values.get( 0 );
+ return values.get(0);
}
- public List<String> getValues()
- {
+ public List<String> getValues() {
return values;
}
- public void addArgument( String argument )
- {
- values.add( argument );
+ public void addArgument(String argument) {
+ values.add(argument);
}
- public boolean hasValue()
- {
+ public boolean hasValue() {
return !values.isEmpty();
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ProjectPropertiesCommandLineConverter.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ProjectPropertiesCommandLineConverter.java
index 90c8c6b..b33c2a7 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ProjectPropertiesCommandLineConverter.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ProjectPropertiesCommandLineConverter.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.wrapper.cli;
/*
@@ -22,25 +40,20 @@ package org.apache.maven.wrapper.cli;
/**
* Converter from project properties.
*/
-public class ProjectPropertiesCommandLineConverter
- extends AbstractPropertiesCommandLineConverter
-{
+public class ProjectPropertiesCommandLineConverter extends AbstractPropertiesCommandLineConverter {
@Override
- protected String getPropertyOption()
- {
+ protected String getPropertyOption() {
return "P";
}
@Override
- protected String getPropertyOptionDetailed()
- {
+ protected String getPropertyOptionDetailed() {
return "project-prop";
}
@Override
- protected String getPropertyOptionDescription()
- {
+ protected String getPropertyOptionDescription() {
return "Set project property for the build script (e.g. -Pmyprop=myvalue).";
}
}
diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/SystemPropertiesCommandLineConverter.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/SystemPropertiesCommandLineConverter.java
index 70f5edf..eda5b35 100644
--- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/SystemPropertiesCommandLineConverter.java
+++ b/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/SystemPropertiesCommandLineConverter.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.wrapper.cli;
/*
@@ -22,25 +40,20 @@ package org.apache.maven.wrapper.cli;
/**
* Converter from system properties.
*/
-public class SystemPropertiesCommandLineConverter
- extends AbstractPropertiesCommandLineConverter
-{
+public class SystemPropertiesCommandLineConverter extends AbstractPropertiesCommandLineConverter {
@Override
- protected String getPropertyOption()
- {
+ protected String getPropertyOption() {
return "D";
}
@Override
- protected String getPropertyOptionDetailed()
- {
+ protected String getPropertyOptionDetailed() {
return "system-prop";
}
@Override
- protected String getPropertyOptionDescription()
- {
+ protected String getPropertyOptionDescription() {
return "Set system property of the JVM (e.g. -Dmyprop=myvalue).";
}
-}
\ No newline at end of file
+}
diff --git a/maven-wrapper/src/test/java/org/apache/maven/wrapper/DownloaderTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/DownloaderTest.java
index f0383ca..6cf3158 100644
--- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/DownloaderTest.java
+++ b/maven-wrapper/src/test/java/org/apache/maven/wrapper/DownloaderTest.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.wrapper;
/*
@@ -19,9 +37,6 @@ package org.apache.maven.wrapper;
* under the License.
*/
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.net.URI;
@@ -33,49 +48,45 @@ import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Test;
-public class DownloaderTest
-{
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class DownloaderTest {
- private DefaultDownloader download;
+ private DefaultDownloader download;
- private Path testDir;
+ private Path testDir;
- private Path downloadFile;
+ private Path downloadFile;
- private Path rootDir;
+ private Path rootDir;
- private URI sourceRoot;
+ private URI sourceRoot;
- private Path remoteFile;
+ private Path remoteFile;
- @Before
- public void setUp()
- throws Exception
- {
- download = new DefaultDownloader( "mvnw", "aVersion" );
- testDir = Paths.get( "target/test-files/DownloadTest" );
- Files.createDirectories( testDir );
- rootDir = testDir.resolve( "root" );
- downloadFile = rootDir.resolve( "file" );
- Files.deleteIfExists( downloadFile );
- remoteFile = testDir.resolve( "remoteFile" );
- try ( BufferedWriter writer = Files.newBufferedWriter( remoteFile, StandardCharsets.UTF_8 ) )
- {
- writer.write( "sometext" );
+ @Before
+ public void setUp() throws Exception {
+ download = new DefaultDownloader("mvnw", "aVersion");
+ testDir = Paths.get("target/test-files/DownloadTest");
+ Files.createDirectories(testDir);
+ rootDir = testDir.resolve("root");
+ downloadFile = rootDir.resolve("file");
+ Files.deleteIfExists(downloadFile);
+ remoteFile = testDir.resolve("remoteFile");
+ try (BufferedWriter writer = Files.newBufferedWriter(remoteFile, StandardCharsets.UTF_8)) {
+ writer.write("sometext");
+ }
+ sourceRoot = remoteFile.toUri();
}
- sourceRoot = remoteFile.toUri();
- }
- @Test
- public void testDownload()
- throws Exception
- {
- assertTrue( Files.notExists( downloadFile ) );
- download.download( sourceRoot, downloadFile );
- assertTrue( Files.exists( downloadFile ) );
- try ( BufferedReader reader = Files.newBufferedReader( downloadFile, StandardCharsets.UTF_8 ) )
- {
- assertEquals( "sometext", reader.readLine() );
+ @Test
+ public void testDownload() throws Exception {
+ assertTrue(Files.notExists(downloadFile));
+ download.download(sourceRoot, downloadFile);
+ assertTrue(Files.exists(downloadFile));
+ try (BufferedReader reader = Files.newBufferedReader(downloadFile, StandardCharsets.UTF_8)) {
+ assertEquals("sometext", reader.readLine());
+ }
}
- }
}
diff --git a/maven-wrapper/src/test/java/org/apache/maven/wrapper/HashAlgorithmVerifierTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/HashAlgorithmVerifierTest.java
index 19110e5..03e9b6f 100644
--- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/HashAlgorithmVerifierTest.java
+++ b/maven-wrapper/src/test/java/org/apache/maven/wrapper/HashAlgorithmVerifierTest.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.wrapper;
/*
@@ -19,19 +37,18 @@ package org.apache.maven.wrapper;
* under the License.
*/
+import java.io.BufferedWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import java.io.BufferedWriter;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-public class HashAlgorithmVerifierTest
-{
+public class HashAlgorithmVerifierTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@@ -41,34 +58,37 @@ public class HashAlgorithmVerifierTest
private Path file;
@Before
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
file = temporaryFolder.newFile().toPath();
- try ( BufferedWriter writer = Files.newBufferedWriter( file, StandardCharsets.UTF_8 ) )
- {
+ try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
writer.write("Sample file with content");
}
}
@Test
- public void sha256SumsMatch() throws Exception
- {
- verifier.verify(file, "property", Verifier.SHA_256_ALGORITHM, "7e0c63c6a99639e57cc64375d6717d72e301d8ab829fef2e145ee860317bc3cb");
+ public void sha256SumsMatch() throws Exception {
+ verifier.verify(
+ file,
+ "property",
+ Verifier.SHA_256_ALGORITHM,
+ "7e0c63c6a99639e57cc64375d6717d72e301d8ab829fef2e145ee860317bc3cb");
}
@Test
- public void sha256SumsDoNotMatch() throws Exception
- {
- try
- {
- verifier.verify(file, "prop", Verifier.SHA_256_ALGORITHM, "d3b572c45972921782287d8edafa5b19533212f2ebbc61c13c375a67c8f2c48f");
- Assert.fail( "Expected RuntimeException" );
- }
- catch (RuntimeException e)
- {
- Assert.assertEquals( "Failed to validate Maven distribution SHA-256, your Maven "
- + "distribution might be compromised. If you updated your Maven version, "
- + "you need to update the specified prop property.", e.getMessage() );
+ public void sha256SumsDoNotMatch() throws Exception {
+ try {
+ verifier.verify(
+ file,
+ "prop",
+ Verifier.SHA_256_ALGORITHM,
+ "d3b572c45972921782287d8edafa5b19533212f2ebbc61c13c375a67c8f2c48f");
+ Assert.fail("Expected RuntimeException");
+ } catch (RuntimeException e) {
+ Assert.assertEquals(
+ "Failed to validate Maven distribution SHA-256, your Maven "
+ + "distribution might be compromised. If you updated your Maven version, "
+ + "you need to update the specified prop property.",
+ e.getMessage());
}
}
}
diff --git a/maven-wrapper/src/test/java/org/apache/maven/wrapper/InstallerTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/InstallerTest.java
index b6b1c76..1ec6cac 100644
--- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/InstallerTest.java
+++ b/maven-wrapper/src/test/java/org/apache/maven/wrapper/InstallerTest.java
@@ -1,8 +1,3 @@
-package org.apache.maven.wrapper;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -12,7 +7,7 @@ import static org.junit.Assert.fail;
* "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
+ * 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
@@ -21,9 +16,7 @@ import static org.junit.Assert.fail;
* specific language governing permissions and limitations
* under the License.
*/
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+package org.apache.maven.wrapper;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -51,246 +44,223 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
/**
* @author Hans Dockter
*/
-public class InstallerTest
-{
- @Rule
- public TemporaryFolder tempFolder = TemporaryFolder.builder().assureDeletion().build();
+public class InstallerTest {
+ @Rule
+ public TemporaryFolder tempFolder =
+ TemporaryFolder.builder().assureDeletion().build();
- private Path testDir;
+ private Path testDir;
- private Installer install;
+ private Installer install;
- private Path distributionDir;
+ private Path distributionDir;
- private Path zipStore;
+ private Path zipStore;
- private Path mavenHomeDir;
+ private Path mavenHomeDir;
- private Path zipDestination;
+ private Path zipDestination;
- private WrapperConfiguration configuration = new WrapperConfiguration();
+ private WrapperConfiguration configuration = new WrapperConfiguration();
- private Downloader download;
+ private Downloader download;
- private Verifier verifier;
+ private Verifier verifier;
- private PathAssembler pathAssembler;
+ private PathAssembler pathAssembler;
- private PathAssembler.LocalDistribution localDistribution;
+ private PathAssembler.LocalDistribution localDistribution;
- @Before
- public void setup()
- throws Exception
- {
- testDir = tempFolder.getRoot().toPath();
+ @Before
+ public void setup() throws Exception {
+ testDir = tempFolder.getRoot().toPath();
- configuration.setZipBase( PathAssembler.PROJECT_STRING );
- configuration.setZipPath( Paths.get( "someZipPath" ) );
- configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING );
- configuration.setDistributionPath( Paths.get( "someDistPath" ) );
- configuration.setDistribution( new URI( "http://server/maven-0.9.zip" ) );
- configuration.setAlwaysDownload( false );
- configuration.setAlwaysUnpack( false );
- configuration.setDistributionSha256Sum( "" );
- distributionDir = testDir.resolve( "someDistPath" );
- mavenHomeDir = distributionDir.resolve( "maven-0.9" );
- zipStore = testDir.resolve( "zips" );
- zipDestination = zipStore.resolve( "maven-0.9.zip" );
+ configuration.setZipBase(PathAssembler.PROJECT_STRING);
+ configuration.setZipPath(Paths.get("someZipPath"));
+ configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
+ configuration.setDistributionPath(Paths.get("someDistPath"));
+ configuration.setDistribution(new URI("http://server/maven-0.9.zip"));
+ configuration.setAlwaysDownload(false);
+ configuration.setAlwaysUnpack(false);
+ configuration.setDistributionSha256Sum("");
+ distributionDir = testDir.resolve("someDistPath");
+ mavenHomeDir = distributionDir.resolve("maven-0.9");
+ zipStore = testDir.resolve("zips");
+ zipDestination = zipStore.resolve("maven-0.9.zip");
- download = mock( Downloader.class );
- verifier = mock ( Verifier.class );
- pathAssembler = mock( PathAssembler.class );
- localDistribution = mock( PathAssembler.LocalDistribution.class );
+ download = mock(Downloader.class);
+ verifier = mock(Verifier.class);
+ pathAssembler = mock(PathAssembler.class);
+ localDistribution = mock(PathAssembler.LocalDistribution.class);
- when( localDistribution.getZipFile() ).thenReturn( zipDestination );
- when( localDistribution.getDistributionDir() ).thenReturn( distributionDir );
- when( pathAssembler.getDistribution( configuration ) ).thenReturn( localDistribution );
+ when(localDistribution.getZipFile()).thenReturn(zipDestination);
+ when(localDistribution.getDistributionDir()).thenReturn(distributionDir);
+ when(pathAssembler.getDistribution(configuration)).thenReturn(localDistribution);
- install = new Installer( download, verifier, pathAssembler );
- }
+ install = new Installer(download, verifier, pathAssembler);
+ }
- private void createTestZip( Path zipDestination )
- throws Exception
- {
- Path explodedZipDir = testDir.resolve( "explodedZip" );
- Files.createDirectories( explodedZipDir );
- Files.createDirectories( zipDestination.getParent() );
- Path mavenScript = explodedZipDir.resolve( "maven-0.9/bin/mvn" );
- Path mavenLib = explodedZipDir.resolve( "maven-0.9/lib/maven-core-0.9.jar" );
- Files.createDirectories( mavenScript.getParent() );
- Files.createDirectories( mavenLib.getParent() );
- try ( BufferedWriter writer = Files.newBufferedWriter( mavenScript, StandardCharsets.UTF_8 ) )
- {
- writer.write( "something" );
+ private void createTestZip(Path zipDestination) throws Exception {
+ Path explodedZipDir = testDir.resolve("explodedZip");
+ Files.createDirectories(explodedZipDir);
+ Files.createDirectories(zipDestination.getParent());
+ Path mavenScript = explodedZipDir.resolve("maven-0.9/bin/mvn");
+ Path mavenLib = explodedZipDir.resolve("maven-0.9/lib/maven-core-0.9.jar");
+ Files.createDirectories(mavenScript.getParent());
+ Files.createDirectories(mavenLib.getParent());
+ try (BufferedWriter writer = Files.newBufferedWriter(mavenScript, StandardCharsets.UTF_8)) {
+ writer.write("something");
+ }
+ try (OutputStream os = Files.newOutputStream(mavenLib);
+ JarOutputStream jar = new JarOutputStream(os, new Manifest())) {
+ jar.putNextEntry(new ZipEntry("test"));
+ jar.closeEntry();
+ }
+
+ zipTo(explodedZipDir, zipDestination);
}
- try ( OutputStream os = Files.newOutputStream( mavenLib );
- JarOutputStream jar = new JarOutputStream( os, new Manifest() ) )
- {
- jar.putNextEntry( new ZipEntry( "test" ) );
- jar.closeEntry();
+
+ public void testCreateDist() throws Exception {
+ Path homeDir = install.createDist(configuration);
+
+ Assert.assertEquals(mavenHomeDir, homeDir);
+ Assert.assertTrue(Files.isDirectory(homeDir));
+ Assert.assertTrue(Files.exists(homeDir.resolve("bin/mvn")));
+ Assert.assertTrue(Files.exists(zipDestination));
+
+ Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
+ Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
+ Assert.assertEquals(zipDestination, localDistribution.getZipFile());
+
+ // download.download(new URI("http://some/test"), distributionDir);
+ // verify(download).download(new URI("http://some/test"), distributionDir);
}
- zipTo( explodedZipDir, zipDestination );
- }
-
- public void testCreateDist()
- throws Exception
- {
- Path homeDir = install.createDist( configuration );
-
- Assert.assertEquals( mavenHomeDir, homeDir );
- Assert.assertTrue( Files.isDirectory( homeDir ) );
- Assert.assertTrue( Files.exists( homeDir.resolve( "bin/mvn" ) ) );
- Assert.assertTrue( Files.exists( zipDestination ) );
-
- Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) );
- Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() );
- Assert.assertEquals( zipDestination, localDistribution.getZipFile() );
-
- // download.download(new URI("http://some/test"), distributionDir);
- // verify(download).download(new URI("http://some/test"), distributionDir);
- }
-
- @Test
- public void testCreateDistWithExistingDistribution()
- throws Exception
- {
-
- createTestZip( zipDestination );
- Files.createDirectories( mavenHomeDir );
- Path someFile = mavenHomeDir.resolve( "some-file" );
- touchFile( someFile );
-
- Path homeDir = install.createDist( configuration );
-
- Assert.assertEquals( mavenHomeDir, homeDir );
- Assert.assertTrue( Files.isDirectory( mavenHomeDir ) );
- Assert.assertTrue( Files.exists( homeDir.resolve( "some-file" ) ) );
- Assert.assertTrue( Files.exists( zipDestination ) );
-
- Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) );
- Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() );
- Assert.assertEquals( zipDestination, localDistribution.getZipFile() );
- }
-
- @Test
- public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue()
- throws Exception
- {
-
- createTestZip( zipDestination );
- Files.createDirectories( mavenHomeDir );
- Path garbage = mavenHomeDir.resolve( "garbage" );
- touchFile( garbage );
- configuration.setAlwaysUnpack( true );
-
- Path homeDir = install.createDist( configuration );
-
- Assert.assertEquals( mavenHomeDir, homeDir );
- Assert.assertTrue( Files.isDirectory( mavenHomeDir ) );
- Assert.assertFalse( Files.exists( homeDir.resolve( "garbage" ) ) );
- Assert.assertTrue( Files.exists( zipDestination ) );
-
- Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) );
- Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() );
- Assert.assertEquals( zipDestination, localDistribution.getZipFile() );
- }
-
- @Test
- public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue()
- throws Exception
- {
-
- createTestZip( zipDestination );
- Path garbage = mavenHomeDir.resolve( "garbage" );
- touchFile( garbage );
- configuration.setAlwaysUnpack( true );
-
- Path homeDir = install.createDist( configuration );
-
- Assert.assertEquals( mavenHomeDir, homeDir );
- Assert.assertTrue( Files.isDirectory( mavenHomeDir ) );
- Assert.assertTrue( Files.exists( homeDir.resolve( "bin/mvn" ) ) );
- Assert.assertFalse( Files.exists( homeDir.resolve( "garbage" ) ) );
- Assert.assertTrue( Files.exists( zipDestination ) );
-
- Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) );
- Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() );
- Assert.assertEquals( zipDestination, localDistribution.getZipFile() );
-
- // download.download(new URI("http://some/test"), distributionDir);
- // verify(download).download(new URI("http://some/test"), distributionDir);
- }
-
- @Test
- public void testZipSlip()
- throws URISyntaxException
- {
- URL resource = getClass().getClassLoader().getResource( "zip-slip.zip" );
- Path zipSlip = Paths.get( resource.toURI() );
- when( localDistribution.getZipFile() ).thenReturn( zipSlip );
- configuration.setAlwaysUnpack( true );
-
- try
- {
- install.createDist( configuration );
- fail( "Should fail as it contains a zip slip." );
+ @Test
+ public void testCreateDistWithExistingDistribution() throws Exception {
+
+ createTestZip(zipDestination);
+ Files.createDirectories(mavenHomeDir);
+ Path someFile = mavenHomeDir.resolve("some-file");
+ touchFile(someFile);
+
+ Path homeDir = install.createDist(configuration);
+
+ Assert.assertEquals(mavenHomeDir, homeDir);
+ Assert.assertTrue(Files.isDirectory(mavenHomeDir));
+ Assert.assertTrue(Files.exists(homeDir.resolve("some-file")));
+ Assert.assertTrue(Files.exists(zipDestination));
+
+ Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
+ Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
+ Assert.assertEquals(zipDestination, localDistribution.getZipFile());
}
- catch ( Exception ex )
- {
- assertTrue( ex instanceof ZipException );
+
+ @Test
+ public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue() throws Exception {
+
+ createTestZip(zipDestination);
+ Files.createDirectories(mavenHomeDir);
+ Path garbage = mavenHomeDir.resolve("garbage");
+ touchFile(garbage);
+ configuration.setAlwaysUnpack(true);
+
+ Path homeDir = install.createDist(configuration);
+
+ Assert.assertEquals(mavenHomeDir, homeDir);
+ Assert.assertTrue(Files.isDirectory(mavenHomeDir));
+ Assert.assertFalse(Files.exists(homeDir.resolve("garbage")));
+ Assert.assertTrue(Files.exists(zipDestination));
+
+ Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
+ Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
+ Assert.assertEquals(zipDestination, localDistribution.getZipFile());
}
- }
-
- public void zipTo( final Path directoryToZip, final Path zipFile )
- throws IOException
- {
- // Creating a ZipOutputStream by wrapping a OutputStream
- try ( OutputStream fos = Files.newOutputStream( zipFile ); ZipOutputStream zos = new ZipOutputStream( fos ) )
- {
- // Walk the tree structure using WalkFileTree method
- Files.walkFileTree( directoryToZip, new SimpleFileVisitor<Path>()
- {
- @Override
- // Before visiting the directory create the directory in zip archive
- public FileVisitResult preVisitDirectory( final Path dir, final BasicFileAttributes attrs )
- throws IOException
- {
- // Don't create dir for root folder as it is already created with .zip name
- if ( !directoryToZip.equals( dir ) )
- {
- zos.putNextEntry( new ZipEntry( directoryToZip.relativize( dir ).toString() + "/" ) );
- zos.closeEntry();
- }
- return FileVisitResult.CONTINUE;
- }
- @Override
- // For each visited file add it to zip entry
- public FileVisitResult visitFile( final Path file, final BasicFileAttributes attrs )
- throws IOException
- {
- zos.putNextEntry( new ZipEntry( directoryToZip.relativize( file ).toString() ) );
- Files.copy( file, zos );
- zos.closeEntry();
- return FileVisitResult.CONTINUE;
+ @Test
+ public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue() throws Exception {
+
+ createTestZip(zipDestination);
+ Path garbage = mavenHomeDir.resolve("garbage");
+ touchFile(garbage);
+ configuration.setAlwaysUnpack(true);
+
+ Path homeDir = install.createDist(configuration);
+
+ Assert.assertEquals(mavenHomeDir, homeDir);
+ Assert.assertTrue(Files.isDirectory(mavenHomeDir));
+ Assert.assertTrue(Files.exists(homeDir.resolve("bin/mvn")));
+ Assert.assertFalse(Files.exists(homeDir.resolve("garbage")));
+ Assert.assertTrue(Files.exists(zipDestination));
+
+ Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
+ Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
+ Assert.assertEquals(zipDestination, localDistribution.getZipFile());
+
+ // download.download(new URI("http://some/test"), distributionDir);
+ // verify(download).download(new URI("http://some/test"), distributionDir);
+ }
+
+ @Test
+ public void testZipSlip() throws URISyntaxException {
+ URL resource = getClass().getClassLoader().getResource("zip-slip.zip");
+ Path zipSlip = Paths.get(resource.toURI());
+ when(localDistribution.getZipFile()).thenReturn(zipSlip);
+ configuration.setAlwaysUnpack(true);
+
+ try {
+ install.createDist(configuration);
+ fail("Should fail as it contains a zip slip.");
+ } catch (Exception ex) {
+ assertTrue(ex instanceof ZipException);
}
- } );
}
- }
-
- private void touchFile( Path file )
- throws IOException
- {
- if ( Files.notExists( file ) )
- {
- Files.createDirectories( file.getParent() );
- Files.createFile( file );
+
+ public void zipTo(final Path directoryToZip, final Path zipFile) throws IOException {
+ // Creating a ZipOutputStream by wrapping a OutputStream
+ try (OutputStream fos = Files.newOutputStream(zipFile);
+ ZipOutputStream zos = new ZipOutputStream(fos)) {
+ // Walk the tree structure using WalkFileTree method
+ Files.walkFileTree(directoryToZip, new SimpleFileVisitor<Path>() {
+ @Override
+ // Before visiting the directory create the directory in zip archive
+ public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
+ throws IOException {
+ // Don't create dir for root folder as it is already created with .zip name
+ if (!directoryToZip.equals(dir)) {
+ zos.putNextEntry(
+ new ZipEntry(directoryToZip.relativize(dir).toString() + "/"));
+ zos.closeEntry();
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ // For each visited file add it to zip entry
+ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
+ zos.putNextEntry(
+ new ZipEntry(directoryToZip.relativize(file).toString()));
+ Files.copy(file, zos);
+ zos.closeEntry();
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ }
}
- Files.setLastModifiedTime( file, FileTime.fromMillis( System.currentTimeMillis() ) );
- }
+ private void touchFile(Path file) throws IOException {
+ if (Files.notExists(file)) {
+ Files.createDirectories(file.getParent());
+ Files.createFile(file);
+ }
+ Files.setLastModifiedTime(file, FileTime.fromMillis(System.currentTimeMillis()));
+ }
}
diff --git a/maven-wrapper/src/test/java/org/apache/maven/wrapper/PathAssemblerTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/PathAssemblerTest.java
index 17b6425..df2435c 100644
--- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/PathAssemblerTest.java
+++ b/maven-wrapper/src/test/java/org/apache/maven/wrapper/PathAssemblerTest.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.wrapper;
/*
@@ -19,11 +37,6 @@ package org.apache.maven.wrapper;
* under the License.
*/
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -35,117 +48,101 @@ import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
/**
* @author Hans Dockter
*/
-public class PathAssemblerTest
-{
- public static final String TEST_MAVEN_USER_HOME = "someUserHome";
-
- private PathAssembler pathAssembler = new PathAssembler( Paths.get( TEST_MAVEN_USER_HOME ) );
-
- final WrapperConfiguration configuration = new WrapperConfiguration();
-
- @Before
- public void setup()
- {
- configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING );
- configuration.setDistributionPath( Paths.get( "somePath" ) );
- configuration.setZipBase( PathAssembler.MAVEN_USER_HOME_STRING );
- configuration.setZipPath( Paths.get( "somePath" ) );
- }
-
- @Test
- public void distributionDirWithMavenUserHomeBase()
- throws Exception
- {
- configuration.setDistribution( new URI( "http://server/dist/maven-0.9-bin.zip" ) );
-
- Path distributionDir = pathAssembler.getDistribution( configuration ).getDistributionDir();
- assertThat( distributionDir.getFileName().toString(), matchesRegexp( "[a-z0-9]+" ) );
- assertThat( distributionDir.getParent(), equalTo( file( TEST_MAVEN_USER_HOME + "/somePath/maven-0.9-bin" ) ) );
- }
-
- @Test
- public void distributionDirWithProjectBase()
- throws Exception
- {
- configuration.setDistributionBase( PathAssembler.PROJECT_STRING );
- configuration.setDistribution( new URI( "http://server/dist/maven-0.9-bin.zip" ) );
-
- Path distributionDir = pathAssembler.getDistribution( configuration ).getDistributionDir();
- assertThat( distributionDir.getFileName().toString(), matchesRegexp( "[a-z0-9]+" ) );
- assertThat( distributionDir.getParent(), equalTo( file( currentDirPath() + "/somePath/maven-0.9-bin" ) ) );
- }
-
- @Test
- public void distributionDirWithUnknownBase()
- throws Exception
- {
- configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
- configuration.setDistributionBase( "unknownBase" );
-
- try
- {
- pathAssembler.getDistribution( configuration );
- fail();
+public class PathAssemblerTest {
+ public static final String TEST_MAVEN_USER_HOME = "someUserHome";
+
+ private PathAssembler pathAssembler = new PathAssembler(Paths.get(TEST_MAVEN_USER_HOME));
+
+ final WrapperConfiguration configuration = new WrapperConfiguration();
+
+ @Before
+ public void setup() {
+ configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
+ configuration.setDistributionPath(Paths.get("somePath"));
+ configuration.setZipBase(PathAssembler.MAVEN_USER_HOME_STRING);
+ configuration.setZipPath(Paths.get("somePath"));
+ }
+
+ @Test
+ public void distributionDirWithMavenUserHomeBase() throws Exception {
+ configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip"));
+
+ Path distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir();
+ assertThat(distributionDir.getFileName().toString(), matchesRegexp("[a-z0-9]+"));
+ assertThat(distributionDir.getParent(), equalTo(file(TEST_MAVEN_USER_HOME + "/somePath/maven-0.9-bin")));
+ }
+
+ @Test
+ public void distributionDirWithProjectBase() throws Exception {
+ configuration.setDistributionBase(PathAssembler.PROJECT_STRING);
+ configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip"));
+
+ Path distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir();
+ assertThat(distributionDir.getFileName().toString(), matchesRegexp("[a-z0-9]+"));
+ assertThat(distributionDir.getParent(), equalTo(file(currentDirPath() + "/somePath/maven-0.9-bin")));
+ }
+
+ @Test
+ public void distributionDirWithUnknownBase() throws Exception {
+ configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
+ configuration.setDistributionBase("unknownBase");
+
+ try {
+ pathAssembler.getDistribution(configuration);
+ fail();
+ } catch (RuntimeException e) {
+ assertEquals("Base: unknownBase is unknown", e.getMessage());
+ }
+ }
+
+ @Test
+ public void distZipWithMavenUserHomeBase() throws Exception {
+ configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
+
+ Path dist = pathAssembler.getDistribution(configuration).getZipFile();
+ assertThat(dist.getFileName().toString(), equalTo("maven-1.0.zip"));
+ assertThat(dist.getParent().getFileName().toString(), matchesRegexp("[a-z0-9]+"));
+ assertThat(dist.getParent().getParent(), equalTo(file(TEST_MAVEN_USER_HOME + "/somePath/maven-1.0")));
+ }
+
+ @Test
+ public void distZipWithProjectBase() throws Exception {
+ configuration.setZipBase(PathAssembler.PROJECT_STRING);
+ configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
+
+ Path dist = pathAssembler.getDistribution(configuration).getZipFile();
+ assertThat(dist.getFileName().toString(), equalTo("maven-1.0.zip"));
+ assertThat(dist.getParent().getFileName().toString(), matchesRegexp("[a-z0-9]+"));
+ assertThat(dist.getParent().getParent(), equalTo(file(currentDirPath() + "/somePath/maven-1.0")));
+ }
+
+ private Path file(String path) {
+ return Paths.get(path);
}
- catch ( RuntimeException e )
- {
- assertEquals( "Base: unknownBase is unknown", e.getMessage() );
+
+ private String currentDirPath() {
+ return System.getProperty("user.dir");
+ }
+
+ public static <T extends CharSequence> Matcher<T> matchesRegexp(final String pattern) {
+ return new BaseMatcher<T>() {
+ @Override
+ public boolean matches(Object o) {
+ return Pattern.compile(pattern).matcher((CharSequence) o).matches();
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("a CharSequence that matches regexp ").appendValue(pattern);
+ }
+ };
}
- }
-
- @Test
- public void distZipWithMavenUserHomeBase()
- throws Exception
- {
- configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
-
- Path dist = pathAssembler.getDistribution( configuration ).getZipFile();
- assertThat( dist.getFileName().toString(), equalTo( "maven-1.0.zip" ) );
- assertThat( dist.getParent().getFileName().toString(), matchesRegexp( "[a-z0-9]+" ) );
- assertThat( dist.getParent().getParent(), equalTo( file( TEST_MAVEN_USER_HOME + "/somePath/maven-1.0" ) ) );
- }
-
- @Test
- public void distZipWithProjectBase()
- throws Exception
- {
- configuration.setZipBase( PathAssembler.PROJECT_STRING );
- configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
-
- Path dist = pathAssembler.getDistribution( configuration ).getZipFile();
- assertThat( dist.getFileName().toString(), equalTo( "maven-1.0.zip" ) );
- assertThat( dist.getParent().getFileName().toString(), matchesRegexp( "[a-z0-9]+" ) );
- assertThat( dist.getParent().getParent(), equalTo( file( currentDirPath() + "/somePath/maven-1.0" ) ) );
- }
-
- private Path file( String path )
- {
- return Paths.get( path );
- }
-
- private String currentDirPath()
- {
- return System.getProperty( "user.dir" );
- }
-
- public static <T extends CharSequence> Matcher<T> matchesRegexp( final String pattern )
- {
- return new BaseMatcher<T>()
- {
- @Override
- public boolean matches( Object o )
- {
- return Pattern.compile( pattern ).matcher( (CharSequence) o ).matches();
- }
-
- @Override
- public void describeTo( Description description )
- {
- description.appendText( "a CharSequence that matches regexp " ).appendValue( pattern );
- }
- };
- }
}
diff --git a/maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.java
index b984f8e..b0752b5 100644
--- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.java
+++ b/maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.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.wrapper;
/*
@@ -19,9 +37,6 @@ package org.apache.maven.wrapper;
* under the License.
*/
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
@@ -34,43 +49,39 @@ import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
-public class SystemPropertiesHandlerTest
-{
-
- private Path tmpDir = Paths.get( "target/test-files/SystemPropertiesHandlerTest" );
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
- @Before
- public void setupTempDir()
- throws IOException
- {
- Files.createDirectories( tmpDir );
- }
+public class SystemPropertiesHandlerTest {
- @Test
- public void testParsePropertiesFile()
- throws Exception
- {
- Path propFile = tmpDir.resolve( "props" );
- Properties props = new Properties();
- props.put( "a", "b" );
- props.put( "systemProp.c", "d" );
- props.put( "systemProp.", "e" );
+ private Path tmpDir = Paths.get("target/test-files/SystemPropertiesHandlerTest");
- try ( OutputStream fos = Files.newOutputStream( propFile ) )
- {
- props.store( fos, "" );
+ @Before
+ public void setupTempDir() throws IOException {
+ Files.createDirectories(tmpDir);
}
- Map<String, String> expected = new HashMap<String, String>();
- expected.put( "c", "d" );
+ @Test
+ public void testParsePropertiesFile() throws Exception {
+ Path propFile = tmpDir.resolve("props");
+ Properties props = new Properties();
+ props.put("a", "b");
+ props.put("systemProp.c", "d");
+ props.put("systemProp.", "e");
+
+ try (OutputStream fos = Files.newOutputStream(propFile)) {
+ props.store(fos, "");
+ }
- assertThat( SystemPropertiesHandler.getSystemProperties( propFile ), equalTo( expected ) );
- }
+ Map<String, String> expected = new HashMap<String, String>();
+ expected.put("c", "d");
- @Test
- public void ifNoPropertyFileExistShouldReturnEmptyMap()
- {
- Map<String, String> expected = new HashMap<String, String>();
- assertThat( SystemPropertiesHandler.getSystemProperties( tmpDir.resolve( "unknown" ) ), equalTo( expected ) );
- }
+ assertThat(SystemPropertiesHandler.getSystemProperties(propFile), equalTo(expected));
+ }
+
+ @Test
+ public void ifNoPropertyFileExistShouldReturnEmptyMap() {
+ Map<String, String> expected = new HashMap<String, String>();
+ assertThat(SystemPropertiesHandler.getSystemProperties(tmpDir.resolve("unknown")), equalTo(expected));
+ }
}
diff --git a/maven-wrapper/src/test/java/org/apache/maven/wrapper/WrapperExecutorTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/WrapperExecutorTest.java
index fb91f2d..d2380bb 100644
--- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/WrapperExecutorTest.java
+++ b/maven-wrapper/src/test/java/org/apache/maven/wrapper/WrapperExecutorTest.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.wrapper;
/*
@@ -19,11 +37,6 @@ package org.apache.maven.wrapper;
* under the License.
*/
-import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_REPOURL;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Files;
@@ -37,242 +50,236 @@ import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
-public class WrapperExecutorTest
-{
- private final Installer install;
-
- private final BootstrapMainStarter start;
-
- private Path propertiesFile;
-
- private Properties properties = new Properties();
-
- private Path testDir = Paths.get( "target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis() );
-
- private Path mockInstallDir = testDir.resolve( "mock-dir" );
-
- public WrapperExecutorTest()
- throws Exception
- {
- install = mock( Installer.class );
- when( install.createDist( Mockito.any( WrapperConfiguration.class ) ) ).thenReturn( mockInstallDir );
- start = mock( BootstrapMainStarter.class );
-
- Files.createDirectories( testDir );
- propertiesFile = testDir.resolve( "maven/wrapper/maven-wrapper.properties" );
-
- properties.put( "distributionUrl", "http://server/test/maven.zip" );
- properties.put( "distributionBase", "testDistBase" );
- properties.put( "distributionPath", "testDistPath" );
- properties.put( "zipStoreBase", "testZipBase" );
- properties.put( "zipStorePath", "testZipPath" );
-
- writePropertiesFile( properties, propertiesFile, "header" );
-
- }
-
- @Test
- public void loadWrapperMetadataFromFile()
- throws Exception
- {
- WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile );
-
- Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() );
- Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() );
- Assert.assertEquals( "testDistBase", wrapper.getConfiguration().getDistributionBase() );
- Assert.assertEquals( "testDistPath", wrapper.getConfiguration().getDistributionPath().toString() );
- Assert.assertEquals( "testZipBase", wrapper.getConfiguration().getZipBase() );
- Assert.assertEquals( "testZipPath", wrapper.getConfiguration().getZipPath().toString() );
- }
-
- @Test
- public void loadWrapperMetadataFromDirectory()
- throws Exception
- {
- WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir );
-
- Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() );
- Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() );
- Assert.assertEquals( "testDistBase", wrapper.getConfiguration().getDistributionBase() );
- Assert.assertEquals( "testDistPath", wrapper.getConfiguration().getDistributionPath().toString() );
- Assert.assertEquals( "testZipBase", wrapper.getConfiguration().getZipBase() );
- Assert.assertEquals( "testZipPath", wrapper.getConfiguration().getZipPath().toString() );
- }
-
- @Test
- public void useDefaultMetadataNoProeprtiesFile()
- throws Exception
- {
- WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir.resolve( "unknown" ) );
-
- Assert.assertNull( wrapper.getDistribution() );
- Assert.assertNull( wrapper.getConfiguration().getDistribution() );
- Assert.assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase() );
- Assert.assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath() );
- Assert.assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase() );
- Assert.assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getZipPath() );
- }
-
- @Test
- public void propertiesFileOnlyContainsDistURL()
- throws Exception
- {
-
- properties = new Properties();
- properties.put( "distributionUrl", "http://server/test/maven.zip" );
- writePropertiesFile( properties, propertiesFile, "header" );
-
- WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile );
-
- Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() );
- Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() );
- Assert.assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase() );
- Assert.assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath() );
- Assert.assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase() );
- Assert.assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getZipPath() );
- }
-
- @Test
- public void executeInstallAndLaunch()
- throws Exception
- {
- WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( propertiesFile );
-
- wrapper.execute( new String[] { "arg" }, install, start );
- verify( install ).createDist( Mockito.any( WrapperConfiguration.class ) );
- verify( start ).start( new String[] { "arg" }, mockInstallDir );
- }
-
- @Test( )
- public void failWhenDistNotSetInProperties()
- throws Exception
- {
- properties = new Properties();
- writePropertiesFile( properties, propertiesFile, "header" );
-
- try
- {
- WrapperExecutor.forWrapperPropertiesFile( propertiesFile );
- Assert.fail( "Expected RuntimeException" );
+import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_REPOURL;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class WrapperExecutorTest {
+ private final Installer install;
+
+ private final BootstrapMainStarter start;
+
+ private Path propertiesFile;
+
+ private Properties properties = new Properties();
+
+ private Path testDir = Paths.get("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis());
+
+ private Path mockInstallDir = testDir.resolve("mock-dir");
+
+ public WrapperExecutorTest() throws Exception {
+ install = mock(Installer.class);
+ when(install.createDist(Mockito.any(WrapperConfiguration.class))).thenReturn(mockInstallDir);
+ start = mock(BootstrapMainStarter.class);
+
+ Files.createDirectories(testDir);
+ propertiesFile = testDir.resolve("maven/wrapper/maven-wrapper.properties");
+
+ properties.put("distributionUrl", "http://server/test/maven.zip");
+ properties.put("distributionBase", "testDistBase");
+ properties.put("distributionPath", "testDistPath");
+ properties.put("zipStoreBase", "testZipBase");
+ properties.put("zipStorePath", "testZipPath");
+
+ writePropertiesFile(properties, propertiesFile, "header");
+ }
+
+ @Test
+ public void loadWrapperMetadataFromFile() throws Exception {
+ WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+
+ Assert.assertEquals(new URI("http://server/test/maven.zip"), wrapper.getDistribution());
+ Assert.assertEquals(
+ new URI("http://server/test/maven.zip"),
+ wrapper.getConfiguration().getDistribution());
+ Assert.assertEquals("testDistBase", wrapper.getConfiguration().getDistributionBase());
+ Assert.assertEquals(
+ "testDistPath", wrapper.getConfiguration().getDistributionPath().toString());
+ Assert.assertEquals("testZipBase", wrapper.getConfiguration().getZipBase());
+ Assert.assertEquals(
+ "testZipPath", wrapper.getConfiguration().getZipPath().toString());
+ }
+
+ @Test
+ public void loadWrapperMetadataFromDirectory() throws Exception {
+ WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(testDir);
+
+ Assert.assertEquals(new URI("http://server/test/maven.zip"), wrapper.getDistribution());
+ Assert.assertEquals(
+ new URI("http://server/test/maven.zip"),
+ wrapper.getConfiguration().getDistribution());
+ Assert.assertEquals("testDistBase", wrapper.getConfiguration().getDistributionBase());
+ Assert.assertEquals(
+ "testDistPath", wrapper.getConfiguration().getDistributionPath().toString());
+ Assert.assertEquals("testZipBase", wrapper.getConfiguration().getZipBase());
+ Assert.assertEquals(
+ "testZipPath", wrapper.getConfiguration().getZipPath().toString());
+ }
+
+ @Test
+ public void useDefaultMetadataNoProeprtiesFile() throws Exception {
+ WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(testDir.resolve("unknown"));
+
+ Assert.assertNull(wrapper.getDistribution());
+ Assert.assertNull(wrapper.getConfiguration().getDistribution());
+ Assert.assertEquals(
+ PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase());
+ Assert.assertEquals(
+ Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath());
+ Assert.assertEquals(
+ PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase());
+ Assert.assertEquals(
+ Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getZipPath());
+ }
+
+ @Test
+ public void propertiesFileOnlyContainsDistURL() throws Exception {
+
+ properties = new Properties();
+ properties.put("distributionUrl", "http://server/test/maven.zip");
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+
+ Assert.assertEquals(new URI("http://server/test/maven.zip"), wrapper.getDistribution());
+ Assert.assertEquals(
+ new URI("http://server/test/maven.zip"),
+ wrapper.getConfiguration().getDistribution());
+ Assert.assertEquals(
+ PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase());
+ Assert.assertEquals(
+ Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath());
+ Assert.assertEquals(
+ PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase());
+ Assert.assertEquals(
+ Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getZipPath());
}
- catch ( RuntimeException e )
- {
- Assert.assertEquals( "Could not load wrapper properties from '" + propertiesFile + "'.", e.getMessage() );
- Assert.assertEquals( "No value with key 'distributionUrl' specified in wrapper properties file '" + propertiesFile
- + "'.", e.getCause().getMessage() );
+
+ @Test
+ public void executeInstallAndLaunch() throws Exception {
+ WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(propertiesFile);
+
+ wrapper.execute(new String[] {"arg"}, install, start);
+ verify(install).createDist(Mockito.any(WrapperConfiguration.class));
+ verify(start).start(new String[] {"arg"}, mockInstallDir);
}
- }
+ @Test()
+ public void failWhenDistNotSetInProperties() throws Exception {
+ properties = new Properties();
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ try {
+ WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+ Assert.fail("Expected RuntimeException");
+ } catch (RuntimeException e) {
+ Assert.assertEquals("Could not load wrapper properties from '" + propertiesFile + "'.", e.getMessage());
+ Assert.assertEquals(
+ "No value with key 'distributionUrl' specified in wrapper properties file '" + propertiesFile
+ + "'.",
+ e.getCause().getMessage());
+ }
+ }
- @Test
- public void failWhenPropertiesFileDoesNotExist()
- {
- propertiesFile = testDir.resolve( "unknown.properties" );
+ @Test
+ public void failWhenPropertiesFileDoesNotExist() {
+ propertiesFile = testDir.resolve("unknown.properties");
- try
- {
- WrapperExecutor.forWrapperPropertiesFile( propertiesFile );
- Assert.fail( "Expected RuntimeException" );
+ try {
+ WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+ Assert.fail("Expected RuntimeException");
+ } catch (RuntimeException e) {
+ Assert.assertEquals("Wrapper properties file '" + propertiesFile + "' does not exist.", e.getMessage());
+ }
}
- catch ( RuntimeException e )
- {
- Assert.assertEquals( "Wrapper properties file '" + propertiesFile + "' does not exist.", e.getMessage() );
+
+ @Test
+ public void testRelativeDistUrl() throws Exception {
+
+ properties = new Properties();
+ properties.put("distributionUrl", "some/relative/url/to/bin.zip");
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+ Assert.assertNotEquals(
+ "some/relative/url/to/bin.zip", wrapper.getDistribution().getSchemeSpecificPart());
+ Assert.assertTrue(wrapper.getDistribution().getSchemeSpecificPart().endsWith("some/relative/url/to/bin.zip"));
}
- }
-
- @Test
- public void testRelativeDistUrl()
- throws Exception
- {
-
- properties = new Properties();
- properties.put( "distributionUrl", "some/relative/url/to/bin.zip" );
- writePropertiesFile( properties, propertiesFile, "header" );
-
- WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile );
- Assert.assertNotEquals( "some/relative/url/to/bin.zip", wrapper.getDistribution().getSchemeSpecificPart() );
- Assert.assertTrue( wrapper.getDistribution().getSchemeSpecificPart().endsWith( "some/relative/url/to/bin.zip" ) );
- }
-
- @Test
- public void testEnvironmentVariableOverwrite_simpleCase()
- throws Exception
- {
- final Map<String, String> environmentVariables = new HashMap<>();
- environmentVariables.put( MVNW_REPOURL, "https://repo/test" );
-
- properties = new Properties();
- properties.put( "distributionUrl", "https://server/path/to/bin.zip" );
- writePropertiesFile( properties, propertiesFile, "header" );
-
- WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
-
- Assert.assertEquals( "https://repo/test/path/to/bin.zip", wrapper.getDistribution().toString() );
- }
-
- @Test
- public void testEnvironmentVariableOverwrite_mvnwRepoUrl_trailingSlash()
- throws Exception
- {
- final Map<String, String> environmentVariables = new HashMap<>();
- environmentVariables.put( MVNW_REPOURL, "https://repo/test/" );
- properties = new Properties();
- properties.put( "distributionUrl", "https://server/path/to/bin.zip" );
- writePropertiesFile( properties, propertiesFile, "header" );
-
- WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
-
- Assert.assertEquals( "https://repo/test/path/to/bin.zip", wrapper.getDistribution().toString() );
- }
-
- @Test
- public void testEnvironmentVariableOverwrite_packageName()
- throws Exception
- {
- final Map<String, String> environmentVariables = new HashMap<>();
- environmentVariables.put( MVNW_REPOURL, "https://repo/test" );
- properties = new Properties();
- properties.put( "distributionUrl", "https://server/org/apache/maven/to/bin.zip" );
- writePropertiesFile( properties, propertiesFile, "header" );
-
- WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
-
- Assert.assertEquals( "https://repo/test/org/apache/maven/to/bin.zip", wrapper.getDistribution().toString() );
- }
-
- @Test
- public void testEnvironmentVariableOverwrite_packageName_trailingSpace()
- throws Exception
- {
- final Map<String, String> environmentVariables = new HashMap<>();
- environmentVariables.put( MVNW_REPOURL, "https://repo/test/" );
- properties = new Properties();
- properties.put( "distributionUrl", "https://server/whatever/org/apache/maven/to/bin.zip" );
- writePropertiesFile( properties, propertiesFile, "header" );
-
- WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
-
- Assert.assertEquals( "https://repo/test/org/apache/maven/to/bin.zip", wrapper.getDistribution().toString() );
- }
-
- private WrapperExecutor prepareWrapperExecutorWithEnvironmentVariables(final Map<String, String> environmentVariables )
- {
- return new WrapperExecutor( propertiesFile, new Properties() ) {
- @Override
- protected String getEnv( String key )
- {
- return environmentVariables.get( key );
- }
- };
- }
-
- private void writePropertiesFile( Properties properties, Path propertiesFile, String message )
- throws Exception
- {
- Files.createDirectories( propertiesFile.getParent() );
- try ( OutputStream outStream = Files.newOutputStream( propertiesFile ) )
- {
- properties.store( outStream, message );
+
+ @Test
+ public void testEnvironmentVariableOverwrite_simpleCase() throws Exception {
+ final Map<String, String> environmentVariables = new HashMap<>();
+ environmentVariables.put(MVNW_REPOURL, "https://repo/test");
+
+ properties = new Properties();
+ properties.put("distributionUrl", "https://server/path/to/bin.zip");
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
+
+ Assert.assertEquals(
+ "https://repo/test/path/to/bin.zip", wrapper.getDistribution().toString());
+ }
+
+ @Test
+ public void testEnvironmentVariableOverwrite_mvnwRepoUrl_trailingSlash() throws Exception {
+ final Map<String, String> environmentVariables = new HashMap<>();
+ environmentVariables.put(MVNW_REPOURL, "https://repo/test/");
+ properties = new Properties();
+ properties.put("distributionUrl", "https://server/path/to/bin.zip");
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
+
+ Assert.assertEquals(
+ "https://repo/test/path/to/bin.zip", wrapper.getDistribution().toString());
+ }
+
+ @Test
+ public void testEnvironmentVariableOverwrite_packageName() throws Exception {
+ final Map<String, String> environmentVariables = new HashMap<>();
+ environmentVariables.put(MVNW_REPOURL, "https://repo/test");
+ properties = new Properties();
+ properties.put("distributionUrl", "https://server/org/apache/maven/to/bin.zip");
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
+
+ Assert.assertEquals(
+ "https://repo/test/org/apache/maven/to/bin.zip",
+ wrapper.getDistribution().toString());
+ }
+
+ @Test
+ public void testEnvironmentVariableOverwrite_packageName_trailingSpace() throws Exception {
+ final Map<String, String> environmentVariables = new HashMap<>();
+ environmentVariables.put(MVNW_REPOURL, "https://repo/test/");
+ properties = new Properties();
+ properties.put("distributionUrl", "https://server/whatever/org/apache/maven/to/bin.zip");
+ writePropertiesFile(properties, propertiesFile, "header");
+
+ WrapperExecutor wrapper = prepareWrapperExecutorWithEnvironmentVariables(environmentVariables);
+
+ Assert.assertEquals(
+ "https://repo/test/org/apache/maven/to/bin.zip",
+ wrapper.getDistribution().toString());
+ }
+
+ private WrapperExecutor prepareWrapperExecutorWithEnvironmentVariables(
+ final Map<String, String> environmentVariables) {
+ return new WrapperExecutor(propertiesFile, new Properties()) {
+ @Override
+ protected String getEnv(String key) {
+ return environmentVariables.get(key);
+ }
+ };
+ }
+
+ private void writePropertiesFile(Properties properties, Path propertiesFile, String message) throws Exception {
+ Files.createDirectories(propertiesFile.getParent());
+ try (OutputStream outStream = Files.newOutputStream(propertiesFile)) {
+ properties.store(outStream, message);
+ }
}
- }
}
diff --git a/pom.xml b/pom.xml
index 789ac9c..589c5bd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,5 +1,4 @@
<?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,16 +17,15 @@ 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.maven</groupId>
<artifactId>maven-parent</artifactId>
- <version>36</version>
+ <version>39</version>
</parent>
-
+
<groupId>org.apache.maven.wrapper</groupId>
<artifactId>maven-wrapper-parent</artifactId>
<version>3.2.0-SNAPSHOT</version>
@@ -36,11 +34,17 @@ under the License.
<name>Apache Maven Wrapper</name>
<inceptionYear>2013</inceptionYear>
+ <modules>
+ <module>maven-wrapper</module>
+ <module>maven-wrapper-distribution</module>
+ <module>maven-wrapper-plugin</module>
+ </modules>
+
<scm>
<connection>scm:git:https://gitbox.apache.org/repos/asf/maven-wrapper.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/maven-wrapper.git</developerConnection>
- <url>https://github.com/apache/maven-wrapper/tree/${project.scm.tag}</url>
<tag>HEAD</tag>
+ <url>https://github.com/apache/maven-wrapper/tree/${project.scm.tag}</url>
</scm>
<issueManagement>
<system>JIRA</system>
@@ -64,12 +68,6 @@ under the License.
<project.build.outputTimestamp>2022-05-08T09:15:34Z</project.build.outputTimestamp>
</properties>
- <modules>
- <module>maven-wrapper</module>
- <module>maven-wrapper-distribution</module>
- <module>maven-wrapper-plugin</module>
- </modules>
-
<build>
<plugins>
<plugin>