This is an automated email from the ASF dual-hosted git repository. rfscholte pushed a commit to branch adopt-changes-maven-core in repository https://gitbox.apache.org/repos/asf/maven-wrapper.git
commit b88acc28212a15f74872d1cc8b8ae3bfcf3ade30 Author: rfscholte <rfscho...@apache.org> AuthorDate: Fri Dec 10 14:57:48 2021 +0100 Apply code changes done while Maven Wrapper was module of Maven Core --- maven-wrapper/pom.xml | 37 +- .../apache/maven/wrapper/BootstrapMainStarter.java | 11 +- .../apache/maven/wrapper/DefaultDownloader.java | 88 +-- .../java/org/apache/maven/wrapper/Downloader.java | 26 +- .../java/org/apache/maven/wrapper/Installer.java | 198 +++--- .../org/apache/maven/wrapper/MavenWrapperMain.java | 112 +--- .../org/apache/maven/wrapper/PathAssembler.java | 71 +-- .../maven/wrapper/SystemPropertiesHandler.java | 77 --- .../apache/maven/wrapper/WrapperConfiguration.java | 2 +- .../org/apache/maven/wrapper/WrapperExecutor.java | 50 +- .../wrapper/cli/AbstractCommandLineConverter.java | 53 -- .../AbstractPropertiesCommandLineConverter.java | 66 -- .../wrapper/cli/CommandLineArgumentException.java | 39 -- .../maven/wrapper/cli/CommandLineConverter.java | 41 -- .../maven/wrapper/cli/CommandLineOption.java | 139 ----- .../maven/wrapper/cli/CommandLineParser.java | 675 --------------------- .../maven/wrapper/cli/ParsedCommandLine.java | 140 ----- .../maven/wrapper/cli/ParsedCommandLineOption.java | 59 -- .../cli/ProjectPropertiesCommandLineConverter.java | 46 -- .../cli/SystemPropertiesCommandLineConverter.java | 46 -- .../org/apache/maven/wrapper/DownloaderTest.java | 70 ++- .../org/apache/maven/wrapper/InstallerTest.java | 315 +++++----- .../apache/maven/wrapper/PathAssemblerTest.java | 180 +++--- .../maven/wrapper/SystemPropertiesHandlerTest.java | 71 --- .../apache/maven/wrapper/WrapperExecutorTest.java | 299 ++++----- pom.xml | 2 +- 26 files changed, 685 insertions(+), 2228 deletions(-) diff --git a/maven-wrapper/pom.xml b/maven-wrapper/pom.xml index 84df636..a0ae664 100644 --- a/maven-wrapper/pom.xml +++ b/maven-wrapper/pom.xml @@ -35,15 +35,21 @@ under the License. <dependencies> <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <version>5.8.0</version> + <scope>test</scope> + </dependency> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> - <dependency> + <dependency> <groupId>org.hamcrest</groupId> - <artifactId>hamcrest-all</artifactId> - <version>1.3</version> + <artifactId>hamcrest</artifactId> + <version>2.2</version> <scope>test</scope> </dependency> <dependency> @@ -52,18 +58,6 @@ under the License. <version>4.1.0</version> <scope>test</scope> </dependency> - <dependency> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - <version>2.6</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - <version>2.6</version> - <scope>test</scope> - </dependency> <!-- Using zip util class, should be replaced with a zip lib --> <dependency> <groupId>org.apache.ant</groupId> @@ -85,6 +79,19 @@ under the License. <build> <plugins> <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <executions> + <execution> + <id>default-testCompile</id> + <configuration> + <source>8</source> + <target>8</target> + </configuration> + </execution> + </executions> + </plugin> + <plugin> <!-- should be removed after switch to java 8 --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> 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 acc56f3..fc59058 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 @@ -23,6 +23,7 @@ import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; +import java.nio.file.Path; /** * Maven starter, from a provided Maven home directory. @@ -31,17 +32,17 @@ import java.net.URLClassLoader; */ public class BootstrapMainStarter { - public void start( String[] args, File mavenHome ) + public void start( String[] args, Path mavenHome ) throws Exception { - File mavenJar = findLauncherJar( mavenHome ); - URLClassLoader contextClassLoader = new URLClassLoader( new URL[] { mavenJar.toURI().toURL() }, + Path mavenJar = findLauncherJar( mavenHome.toFile() ).toPath(); + 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.getAbsolutePath() ); - System.setProperty( "classworlds.conf", new File( mavenHome, "/bin/m2.conf" ).getAbsolutePath() ); + 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 } ); 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 69483d1..f5dd89c 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 @@ -23,17 +23,18 @@ import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_PASSWORD; import static org.apache.maven.wrapper.MavenWrapperMain.MVNW_USERNAME; import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.lang.reflect.Method; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URI; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; /** * @author Hans Dockter @@ -67,47 +68,44 @@ public class DefaultDownloader private void configureAuthentication() { - if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null + 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() ); + return new PasswordAuthentication( System.getenv( MVNW_USERNAME ), + System.getenv( MVNW_PASSWORD ).toCharArray() ); } } ); } } - public void download( URI address, File destination ) - throws Exception + @Override + public void download( URI address, Path destination ) throws IOException { - if ( destination.exists() ) + if ( Files.exists( destination ) ) { return; } - destination.getParentFile().mkdirs(); + Files.createDirectories( destination.getParent() ); downloadInternal( address, destination ); } - private void downloadInternal( URI address, File destination ) - throws Exception + private void downloadInternal( URI address, Path destination ) throws IOException { - OutputStream out = null; - URLConnection conn; - InputStream in = null; - try + URL url = address.toURL(); + URLConnection conn = url.openConnection(); + addBasicAuthentication( address, conn ); + final String userAgentValue = calculateUserAgent(); + conn.setRequestProperty( "User-Agent", userAgentValue ); + + try ( OutputStream out = new BufferedOutputStream( Files.newOutputStream( destination ) ); + InputStream in = conn.getInputStream() ) { - URL url = address.toURL(); - out = new BufferedOutputStream( new FileOutputStream( destination ) ); - conn = url.openConnection(); - addBasicAuthentication( address, conn ); - final String userAgentValue = calculateUserAgent(); - conn.setRequestProperty( "User-Agent", userAgentValue ); - in = conn.getInputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int numRead; long progressCounter = 0; @@ -125,14 +123,6 @@ public class DefaultDownloader finally { Logger.info( "" ); - if ( in != null ) - { - in.close(); - } - if ( out != null ) - { - out.close(); - } } } @@ -153,10 +143,7 @@ public class DefaultDownloader } /** - * Base64 encode user info for HTTP Basic Authentication. Try to use {@literal java.util.Base64} encoder which is - * available starting with Java 8. Fallback to {@literal javax.xml.bind.DatatypeConverter} from JAXB which is - * available starting with Java 6 but is not anymore in Java 9. Fortunately, both of these two Base64 encoders - * implement the right Base64 flavor, the one that does not split the output in multiple lines. + * Base64 encode user info for HTTP Basic Authentication. * * @param userInfo user info * @return Base64 encoded user info @@ -164,30 +151,7 @@ public class DefaultDownloader */ private String base64Encode( String userInfo ) { - ClassLoader loader = getClass().getClassLoader(); - 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( "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( "UTF-8" ) } ); - } - catch ( Exception java5OrEarlier ) - { - throw new RuntimeException( "Downloading Maven distributions with HTTP Basic Authentication" - + " is not supported on your JVM.", java5OrEarlier ); - } - } + return Base64.getEncoder().encodeToString( userInfo.getBytes( StandardCharsets.UTF_8 ) ); } private String calculateUserInfo( URI uri ) @@ -203,16 +167,14 @@ public class DefaultDownloader 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( "%s/%s (%s;%s;%s) (%s;%s;%s)", applicationName, appVersion, osName, osVersion, osArch, - javaVendor, javaVersion, javaVendorVersion ); + return String.format( "%s/%s (%s;%s;%s) (%s;%s;%s)", applicationName, applicationVersion, osName, osVersion, + osArch, javaVendor, javaVersion, javaVendorVersion ); } private static class SystemPropertiesProxyAuthenticator 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 9e11ae6..90dc089 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 @@ -19,8 +19,29 @@ package org.apache.maven.wrapper; * under the License. */ -import java.io.File; +import java.io.IOException; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + import java.net.URI; +import java.nio.file.Path; /** * Maven distribution downloader. @@ -29,6 +50,5 @@ import java.net.URI; */ public interface Downloader { - void download( URI address, File destination ) - throws Exception; + void download( URI address, Path destination ) throws IOException; } 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 bf0359f..8230c3b 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 @@ -19,15 +19,17 @@ package org.apache.maven.wrapper; * under the License. */ -import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.InputStreamReader; -import java.io.OutputStream; import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Enumeration; import java.util.Formatter; @@ -56,69 +58,92 @@ public class Installer this.pathAssembler = pathAssembler; } - public File createDist( WrapperConfiguration configuration ) - throws Exception + public Path createDist( WrapperConfiguration configuration ) + throws IOException, URISyntaxException { - URI distributionUrl = configuration.getDistribution(); - + URI distributionUrl; String mvnwRepoUrl = System.getenv( MavenWrapperMain.MVNW_REPOURL ); if ( mvnwRepoUrl != null && !mvnwRepoUrl.isEmpty() ) { + distributionUrl = new URI( mvnwRepoUrl + "/" + MavenWrapperMain.MVN_PATH ); Logger.info( "Detected MVNW_REPOURL environment variable " + mvnwRepoUrl ); - String mvnPath = distributionUrl.toURL().toString(); - mvnPath = mvnPath.substring( mvnPath.indexOf( "org/apache/maven" ) ); - distributionUrl = new URI( mvnwRepoUrl + "/" + mvnPath ); } - + else + { + distributionUrl = configuration.getDistribution(); + } + Logger.info( "Downloading Maven binary from " + distributionUrl ); boolean alwaysDownload = configuration.isAlwaysDownload(); boolean alwaysUnpack = configuration.isAlwaysUnpack(); PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution( configuration ); - Logger.info( "Installing Maven distribution " + localDistribution.getDistributionDir().getAbsolutePath() ); - File localZipFile = localDistribution.getZipFile(); + Path localZipFile = localDistribution.getZipFile(); boolean downloaded = false; - if ( alwaysDownload || !localZipFile.exists() ) + if ( alwaysDownload || !Files.exists( localZipFile ) ) { - File tmpZipFile = new File( localZipFile.getParentFile(), localZipFile.getName() + ".part" ); - tmpZipFile.delete(); + Path tmpZipFile = localZipFile.resolveSibling( localZipFile.getFileName() + ".part" ); + Files.deleteIfExists( tmpZipFile ); Logger.info( "Downloading " + distributionUrl ); download.download( distributionUrl, tmpZipFile ); - tmpZipFile.renameTo( localZipFile ); + Files.move( tmpZipFile, localZipFile ); downloaded = true; } - File distDir = localDistribution.getDistributionDir(); - List<File> dirs = listDirs( distDir ); + final Path distDir = localDistribution.getDistributionDir(); + List<File> dirs = listDirs( distDir.toFile() ); if ( downloaded || alwaysUnpack || dirs.isEmpty() ) { - for ( File dir : dirs ) + Files.walkFileTree( distDir.toAbsolutePath(), new SimpleFileVisitor<Path>() { - Logger.info( "Deleting directory " + dir.getAbsolutePath() ); - deleteDir( dir ); - } - Logger.info( "Unzipping " + localZipFile.getAbsolutePath() + " to " + distDir.getAbsolutePath() ); + @Override + public FileVisitResult postVisitDirectory( Path dir, IOException exc ) + throws IOException + { + if ( dir.getParent().equals( distDir ) ) + { + Logger.info( "Deleting directory " + distDir.toAbsolutePath() ); + Files.delete( dir ); + } + return FileVisitResult.CONTINUE; + } + + public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) + throws IOException + { + if ( !file.getParent().equals( distDir ) ) + { + Files.delete( file ); + } + return FileVisitResult.CONTINUE; + }; + } ); + + Logger.info( "Unzipping " + localZipFile.toAbsolutePath() + " to " + distDir.toAbsolutePath() ); unzip( localZipFile, distDir ); - dirs = listDirs( distDir ); + + dirs = listDirs( distDir.toFile() ); if ( dirs.isEmpty() ) { - throw new RuntimeException( String.format( "Maven distribution '%s' does not contain any directory." - + " Expected to find exactly 1 directory.", distDir ) ); + throw new RuntimeException( String.format( + "Maven distribution '%s' does not contain any directories. Expected to find exactly 1 directory.", + distributionUrl ) ); } - setExecutablePermissions( dirs.get( 0 ) ); + setExecutablePermissions( dirs.get( 0 ).toPath() ); } if ( dirs.size() != 1 ) { - throw new RuntimeException( String.format( "Maven distribution '%s' contains too many directories." - + " Expected to find exactly 1 directory.", distDir ) ); + throw new IllegalStateException( String.format( + "Maven distribution '%s' contains too many directories. Expected to find exactly 1 directory.", + distributionUrl ) ); } - return dirs.get( 0 ); + return dirs.get( 0 ).toPath(); } private List<File> listDirs( File distDir ) { - List<File> dirs = new ArrayList<File>(); + List<File> dirs = new ArrayList<>(); if ( distDir.exists() ) { for ( File file : distDir.listFiles() ) @@ -132,118 +157,81 @@ public class Installer return dirs; } - private void setExecutablePermissions( File mavenHome ) + private void setExecutablePermissions( Path mavenHome ) { if ( isWindows() ) { return; } - File mavenCommand = new File( mavenHome, "bin/mvn" ); + Path mavenCommand = mavenHome.resolve( "bin/mvn" ); String errorMessage = null; try { - ProcessBuilder pb = new ProcessBuilder( "chmod", "755", mavenCommand.getCanonicalPath() ); + ProcessBuilder pb = new ProcessBuilder( "chmod", "755", mavenCommand.toString() ); Process p = pb.start(); if ( p.waitFor() == 0 ) { - Logger.info( "Set executable permissions for: " + mavenCommand.getAbsolutePath() ); + Logger.info( "Set executable permissions for: " + mavenCommand.toString() ); } else { - BufferedReader is = new BufferedReader( new InputStreamReader( p.getInputStream() ) ); - Formatter stdout = new Formatter(); - String line; - while ( ( line = is.readLine() ) != null ) + + try ( BufferedReader is = new BufferedReader( new InputStreamReader( p.getInputStream() ) ); + Formatter stdout = new Formatter() ) { - stdout.format( "%s%n", line ); + String line; + while ( ( line = is.readLine() ) != null ) + { + stdout.format( "%s%n", line ); + } + errorMessage = stdout.toString(); } - errorMessage = stdout.toString(); } } - catch ( IOException e ) - { - errorMessage = e.getMessage(); - } - catch ( InterruptedException e ) + catch ( IOException | InterruptedException e ) { errorMessage = e.getMessage(); } if ( errorMessage != null ) { - Logger.warn( "Could not set executable permissions for: " + mavenCommand.getAbsolutePath() ); - Logger.warn( "Please do this manually if you want to use Maven." ); + Logger.warn( "Could not set executable permissions for: " + mavenCommand ); + Logger.warn( "Please do this manually if you want to use maven." ); } } private boolean isWindows() { String osName = System.getProperty( "os.name" ).toLowerCase( Locale.US ); - if ( osName.indexOf( "windows" ) > -1 ) - { - return true; - } - return false; - } - - private boolean deleteDir( File dir ) - { - if ( dir.isDirectory() ) - { - String[] children = dir.list(); - for ( int i = 0; i < children.length; i++ ) - { - boolean success = deleteDir( new File( dir, children[i] ) ); - if ( !success ) - { - return false; - } - } - } - // The directory is now empty so delete it - return dir.delete(); + return ( osName.indexOf( "windows" ) > -1 ); } - public void unzip( File zip, File dest ) + private void unzip( Path zip, Path dest ) throws IOException { - Enumeration entries; - ZipFile zipFile; - - zipFile = new ZipFile( zip ); - - entries = zipFile.entries(); - - while ( entries.hasMoreElements() ) + try ( ZipFile zipFile = new ZipFile( zip.toFile() ) ) { - ZipEntry entry = (ZipEntry) entries.nextElement(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); - if ( entry.isDirectory() ) + while ( entries.hasMoreElements() ) { - ( new File( dest, entry.getName() ) ).mkdirs(); - continue; - } + ZipEntry entry = entries.nextElement(); - new File( dest, entry.getName() ).getParentFile().mkdirs(); - copyInputStream( zipFile.getInputStream( entry ), - new BufferedOutputStream( new FileOutputStream( new File( dest, entry.getName() ) ) ) ); - } - zipFile.close(); - } + if ( entry.isDirectory() ) + { + continue; + } - public void copyInputStream( InputStream in, OutputStream out ) - throws IOException - { - byte[] buffer = new byte[1024]; - int len; + Path targetFile = dest.resolve( entry.getName() ).normalize(); - while ( ( len = in.read( buffer ) ) >= 0 ) - { - out.write( buffer, 0, len ); - } + // prevent Zip Slip + if ( targetFile.startsWith( dest ) ) + { + Files.createDirectories( targetFile.getParent() ); - in.close(); - out.close(); + Files.copy( zipFile.getInputStream( entry ), targetFile ); + } + } + } } - } 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 b5a9c3c..16cf2f8 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 @@ -19,16 +19,14 @@ package org.apache.maven.wrapper; * under the License. */ -import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; -import java.util.Map; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Properties; -import org.apache.maven.wrapper.cli.CommandLineParser; -import org.apache.maven.wrapper.cli.SystemPropertiesCommandLineConverter; - /** * Main entry point for the Maven Wrapper, delegating wrapper execution to {@link WrapperExecutor}. * @@ -36,11 +34,9 @@ import org.apache.maven.wrapper.cli.SystemPropertiesCommandLineConverter; */ public class MavenWrapperMain { - public static final String DEFAULT_MAVEN_USER_HOME = System.getProperty( "user.home" ) + "/.m2"; + private static final String POM_PROPERTIES = "/META-INF/maven/org.apache.maven/maven-wrapper/pom.properties"; - public static final String MAVEN_USER_HOME_PROPERTY_KEY = "maven.user.home"; - - public static final String MAVEN_USER_HOME_ENV_KEY = "MAVEN_USER_HOME"; + public static final String DEFAULT_MAVEN_USER_HOME = System.getProperty( "user.home" ) + "/.m2"; public static final String MVNW_VERBOSE = "MVNW_VERBOSE"; @@ -50,116 +46,62 @@ public class MavenWrapperMain public static final String MVNW_REPOURL = "MVNW_REPOURL"; + public static final String MVN_PATH = + "org/apache/maven/apache-maven/" + wrapperVersion() + "/apache-maven-" + wrapperVersion() + "-bin.zip"; + public static void main( String[] args ) throws Exception { - File wrapperJar = wrapperJar(); - File propertiesFile = wrapperProperties( wrapperJar ); - File rootDir = rootDir( wrapperJar ); + Path wrapperJar = wrapperJar(); + Path propertiesFile = wrapperProperties( wrapperJar ); String wrapperVersion = wrapperVersion(); Logger.info( "Apache Maven Wrapper " + wrapperVersion ); - Properties systemProperties = System.getProperties(); - systemProperties.putAll( parseSystemPropertiesFromArgs( args ) ); - - addSystemProperties( rootDir ); - - WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); + WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); wrapperExecutor.execute( args, new Installer( new DefaultDownloader( "mvnw", wrapperVersion ), new PathAssembler( mavenUserHome() ) ), new BootstrapMainStarter() ); } - private static Map<String, String> parseSystemPropertiesFromArgs( String[] args ) + private static Path wrapperProperties( Path wrapperJar ) throws URISyntaxException { - SystemPropertiesCommandLineConverter converter = new SystemPropertiesCommandLineConverter(); - CommandLineParser commandLineParser = new CommandLineParser(); - converter.configure( commandLineParser ); - commandLineParser.allowUnknownOptions(); - return converter.convert( commandLineParser.parse( args ) ); + return wrapperJar().resolveSibling( wrapperJar.getFileName().toString().replaceFirst( "\\.jar$", + ".properties" ) ); } - private static void addSystemProperties( File rootDir ) + private static Path wrapperJar() throws URISyntaxException { - System.getProperties().putAll( SystemPropertiesHandler.getSystemProperties( new File( mavenUserHome(), - "maven.properties" ) ) ); - System.getProperties().putAll( SystemPropertiesHandler.getSystemProperties( new File( rootDir, - "maven.properties" ) ) ); - } + URI location = MavenWrapperMain.class.getProtectionDomain().getCodeSource().getLocation().toURI(); - private static File rootDir( File wrapperJar ) - { - return wrapperJar.getParentFile().getParentFile().getParentFile(); - } - - private static File wrapperProperties( File wrapperJar ) - { - return new File( wrapperJar.getParent(), wrapperJar.getName().replaceFirst( "\\.jar$", ".properties" ) ); - } - - private static File wrapperJar() - { - URI location; - try - { - location = MavenWrapperMain.class.getProtectionDomain().getCodeSource().getLocation().toURI(); - } - catch ( URISyntaxException e ) - { - throw new RuntimeException( e ); - } - if ( !location.getScheme().equals( "file" ) ) - { - throw new RuntimeException( String.format( "Cannot determine classpath for wrapper Jar from codebase '%s'.", - location ) ); - } - return new File( location.getPath() ); + return Paths.get( location ); } static String wrapperVersion() { - try + try ( InputStream resourceAsStream = MavenWrapperMain.class.getResourceAsStream( POM_PROPERTIES ) ) { - InputStream resourceAsStream = - MavenWrapperMain.class.getResourceAsStream( "/META-INF/maven/org.apache.maven.wrapper/" - + "maven-wrapper/pom.properties" ); if ( resourceAsStream == null ) { - throw new RuntimeException( "No maven properties found." ); + throw new IllegalStateException( POM_PROPERTIES + " not found." ); } Properties mavenProperties = new Properties(); - try + mavenProperties.load( resourceAsStream ); + String version = mavenProperties.getProperty( "version" ); + if ( version == null ) { - mavenProperties.load( resourceAsStream ); - String version = mavenProperties.getProperty( "version" ); - if ( version == null ) - { - throw new RuntimeException( "No version number specified in build receipt resource." ); - } - return version; - } - finally - { - resourceAsStream.close(); + throw new NullPointerException( "No version specified in " + POM_PROPERTIES ); } + return version; } - catch ( Exception e ) + catch ( IOException e ) { throw new RuntimeException( "Could not determine wrapper version.", e ); } } - private static File mavenUserHome() + private static Path mavenUserHome() { - String mavenUserHome = System.getProperty( MAVEN_USER_HOME_PROPERTY_KEY ); - if ( mavenUserHome != null ) - { - return new File( mavenUserHome ); - } - - mavenUserHome = System.getenv( MAVEN_USER_HOME_ENV_KEY ); - - return new File( mavenUserHome == null ? DEFAULT_MAVEN_USER_HOME : mavenUserHome ); + return Paths.get( DEFAULT_MAVEN_USER_HOME ); } } 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 8c4c98d..fd99986 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 @@ -19,10 +19,9 @@ package org.apache.maven.wrapper; * under the License. */ -import java.io.File; -import java.math.BigInteger; import java.net.URI; -import java.security.MessageDigest; +import java.nio.file.Path; +import java.nio.file.Paths; /** * @author Hans Dockter @@ -33,56 +32,34 @@ public class PathAssembler public static final String PROJECT_STRING = "PROJECT"; - private File mavenUserHome; + private Path mavenUserHome; public PathAssembler() { } - public PathAssembler( File mavenUserHome ) + public PathAssembler( Path mavenUserHome ) { this.mavenUserHome = mavenUserHome; } /** * Determines the local locations for the distribution to use given the supplied configuration. - * - * @param configuration a wrapper configuration - * @return the local distribution */ public LocalDistribution getDistribution( WrapperConfiguration configuration ) { String baseName = getDistName( configuration.getDistribution() ); - String distName = removeExtension( baseName ); - String rootDirName = rootDirName( distName, configuration ); - File distDir = new File( getBaseDir( configuration.getDistributionBase() ), - configuration.getDistributionPath() + "/" + rootDirName ); - File distZip = new File( getBaseDir( configuration.getZipBase() ), - configuration.getZipPath() + "/" + rootDirName + "/" + baseName ); + String rootDirName = removeExtension( baseName ); + 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 String rootDirName( String distName, WrapperConfiguration configuration ) - { - String urlHash = getMd5Hash( configuration.getDistribution().toString() ); - return String.format( "%s/%s", distName, urlHash ); - } - - private String getMd5Hash( String string ) - { - try - { - MessageDigest messageDigest = MessageDigest.getInstance( "MD5" ); - byte[] bytes = string.getBytes(); - messageDigest.update( bytes ); - return new BigInteger( 1, messageDigest.digest() ).toString( 32 ); - } - catch ( Exception e ) - { - throw new RuntimeException( "Could not hash input string.", e ); - } - } - private String removeExtension( String name ) { int p = name.lastIndexOf( "." ); @@ -104,32 +81,32 @@ public class PathAssembler return path.substring( p + 1 ); } - private File getBaseDir( String base ) + private Path getBaseDir( String base ) { - if ( base.equals( MAVEN_USER_HOME_STRING ) ) + if ( MAVEN_USER_HOME_STRING.equals( base ) ) { return mavenUserHome; } - else if ( base.equals( PROJECT_STRING ) ) + else if ( PROJECT_STRING.equals( base ) ) { - return new File( System.getProperty( "user.dir" ) ); + return Paths.get( System.getProperty( "user.dir" ) ); } else { - throw new RuntimeException( "Base: " + base + " is unknown" ); + throw new IllegalArgumentException( "Base: " + base + " is unknown" ); } } /** - * Local distribution + * The Local Distribution */ public class LocalDistribution { - private final File distZip; + private final Path distZip; - private final File distDir; + private final Path distDir; - public LocalDistribution( File distDir, File distZip ) + public LocalDistribution( Path distDir, Path distZip ) { this.distDir = distDir; this.distZip = distZip; @@ -137,18 +114,16 @@ public class PathAssembler /** * Returns the location to install the distribution into. - * @return the location to install the distribution into */ - public File getDistributionDir() + public Path getDistributionDir() { return distDir; } /** * Returns the location to install the distribution ZIP file to. - * @return the location to install the distribution ZIP file to */ - public File 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 deleted file mode 100644 index ac45478..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/SystemPropertiesHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.apache.maven.wrapper; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author Hans Dockter - */ -public class SystemPropertiesHandler -{ - - public static Map<String, String> getSystemProperties( File propertiesFile ) - { - Map<String, String> propertyMap = new HashMap<String, String>(); - if ( !propertiesFile.isFile() ) - { - return propertyMap; - } - Properties properties = new Properties(); - try - { - FileInputStream inStream = new FileInputStream( propertiesFile ); - try - { - properties.load( inStream ); - } - finally - { - inStream.close(); - } - } - catch ( IOException e ) - { - throw new RuntimeException( "Error when loading properties file=" + propertiesFile, e ); - } - - Pattern pattern = Pattern.compile( "systemProp\\.(.*)" ); - for ( Object argument : properties.keySet() ) - { - Matcher matcher = pattern.matcher( argument.toString() ); - if ( matcher.find() ) - { - String key = matcher.group( 1 ); - if ( key.length() > 0 ) - { - propertyMap.put( key, properties.get( argument ).toString() ); - } - } - } - return propertyMap; - } -} 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 dfbd1a6..d7be04e 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 @@ -22,7 +22,7 @@ package org.apache.maven.wrapper; import java.net.URI; /** - * Wrapper configuration. + * The Wrapper Configuration */ public class WrapperConfiguration { 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 c2f5266..42d5677 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 @@ -19,17 +19,17 @@ package org.apache.maven.wrapper; * under the License. */ -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Properties; /** - * Wrapper executor, running {@link Installer} to get a Maven distribution ready, followed by - * {@link BootstrapMainStarter} to launch the Maven bootstrap. + * Wrapper executor, running {@link Installer} to get a Maven distribution ready, followed by {@BootstrapMainStarter} + * to launch the Maven bootstrap. * * @author Hans Dockter */ @@ -47,34 +47,31 @@ public class WrapperExecutor private final Properties properties; - private final File propertiesFile; - - private final Appendable warningOutput; + private final Path propertiesFile; private final WrapperConfiguration config = new WrapperConfiguration(); - public static WrapperExecutor forProjectDirectory( File projectDir, Appendable warningOutput ) + public static WrapperExecutor forProjectDirectory( Path projectDir ) { - return new WrapperExecutor( new File( projectDir, "maven/wrapper/maven-wrapper.properties" ), new Properties(), - warningOutput ); + return new WrapperExecutor( projectDir.resolve( "maven/wrapper/maven-wrapper.properties" ), + new Properties() ); } - public static WrapperExecutor forWrapperPropertiesFile( File propertiesFile, Appendable warningOutput ) + public static WrapperExecutor forWrapperPropertiesFile( Path propertiesFile ) { - if ( !propertiesFile.exists() ) + if ( !Files.exists( propertiesFile ) ) { throw new RuntimeException( String.format( "Wrapper properties file '%s' does not exist.", propertiesFile ) ); } - return new WrapperExecutor( propertiesFile, new Properties(), warningOutput ); + return new WrapperExecutor( propertiesFile, new Properties() ); } - WrapperExecutor( File propertiesFile, Properties properties, Appendable warningOutput ) + WrapperExecutor( Path propertiesFile, Properties properties ) { this.properties = properties; this.propertiesFile = propertiesFile; - this.warningOutput = warningOutput; - if ( propertiesFile.exists() ) + if ( Files.exists( propertiesFile ) ) { try { @@ -85,7 +82,7 @@ public class WrapperExecutor config.setZipBase( getProperty( ZIP_STORE_BASE_PROPERTY, config.getZipBase() ) ); config.setZipPath( getProperty( ZIP_STORE_PATH_PROPERTY, config.getZipPath() ) ); } - catch ( Exception e ) + catch ( IOException | URISyntaxException e ) { throw new RuntimeException( String.format( "Could not load wrapper properties from '%s'.", propertiesFile ), @@ -101,7 +98,7 @@ public class WrapperExecutor if ( source.getScheme() == null ) { // no scheme means someone passed a relative url. In our context only file relative urls make sense. - return new File( propertiesFile.getParentFile(), source.getSchemeSpecificPart() ).toURI(); + return propertiesFile.getParent().resolve( source.getSchemeSpecificPart() ).toUri(); } else { @@ -121,24 +118,18 @@ public class WrapperExecutor return null; // previous line will fail } - private static void loadProperties( File propertiesFile, Properties properties ) - throws IOException + private static void loadProperties( Path propertiesFile, Properties properties ) + throws IOException { - InputStream inStream = new FileInputStream( propertiesFile ); - try + try ( InputStream inStream = Files.newInputStream( propertiesFile ) ) { properties.load( inStream ); } - finally - { - inStream.close(); - } } /** - * Returns the Maven distribution which this wrapper will use. Returns null if no wrapper meta-data was found in the + * Returns the distribution which this wrapper will use. Returns null if no wrapper meta-data was found in the * specified project directory. - * @return the Maven distribution which this wrapper will use */ public URI getDistribution() { @@ -147,7 +138,6 @@ public class WrapperExecutor /** * Returns the configuration for this wrapper. - * @return the configuration for this wrapper */ public WrapperConfiguration getConfiguration() { @@ -157,7 +147,7 @@ public class WrapperExecutor public void execute( String[] args, Installer install, BootstrapMainStarter bootstrapMainStarter ) throws Exception { - File mavenHome = install.createDist( config ); + Path mavenHome = install.createDist( config ); bootstrapMainStarter.start( args, mavenHome ); } 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 deleted file mode 100644 index 9ad5b3c..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractCommandLineConverter.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * 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. - */ - -/** - * Command line converter. - * - * @param <T> type - */ -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 ) ); - } - - public T convert( ParsedCommandLine args ) - throws CommandLineArgumentException - { - return convert( args, newInstance() ); - } - - public T convert( Iterable<String> args, T target ) - throws CommandLineArgumentException - { - CommandLineParser parser = new CommandLineParser(); - 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 deleted file mode 100644 index fee974c..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/AbstractPropertiesCommandLineConverter.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.HashMap; -import java.util.Map; - -/** - * Converter form properties. - */ -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() ); - option = option.hasArguments(); - option.hasDescription( getPropertyOptionDescription() ); - } - - 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 ) ); - } - } - 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 deleted file mode 100644 index 588b6f5..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineArgumentException.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * 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. - */ - -/** - * 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 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 deleted file mode 100644 index f863901..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineConverter.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * 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. - */ - -/** - * @author Hans Dockter - * @param <T> type - */ -public interface CommandLineConverter<T> -{ - T convert( Iterable<String> args ) - throws CommandLineArgumentException; - - T convert( Iterable<String> args, T target ) - throws CommandLineArgumentException; - - T convert( ParsedCommandLine args ) - throws CommandLineArgumentException; - - T convert( ParsedCommandLine args, T target ) - throws CommandLineArgumentException; - - 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 deleted file mode 100644 index ededc45..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineOption.java +++ /dev/null @@ -1,139 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Command line option. - */ -public class CommandLineOption -{ - private final Set<String> options = new HashSet<String>(); - - private Class<?> argumentType = Void.TYPE; - - private String description; - - private String subcommand; - - private String deprecationWarning; - - private boolean incubating; - - public CommandLineOption( Iterable<String> options ) - { - for ( String option : options ) - { - this.options.add( option ); - } - } - - public Set<String> getOptions() - { - return options; - } - - public CommandLineOption hasArgument() - { - argumentType = String.class; - return this; - } - - public CommandLineOption hasArguments() - { - argumentType = List.class; - return this; - } - - public String getSubcommand() - { - return subcommand; - } - - public CommandLineOption mapsToSubcommand( String command ) - { - this.subcommand = command; - return this; - } - - public String getDescription() - { - StringBuilder result = new StringBuilder(); - if ( description != null ) - { - result.append( description ); - } - if ( deprecationWarning != null ) - { - if ( result.length() > 0 ) - { - result.append( ' ' ); - } - result.append( "[deprecated - " ); - result.append( deprecationWarning ); - result.append( "]" ); - } - if ( incubating ) - { - if ( result.length() > 0 ) - { - result.append( ' ' ); - } - result.append( "[incubating]" ); - } - return result.toString(); - } - - public CommandLineOption hasDescription( String description ) - { - this.description = description; - return this; - } - - public boolean getAllowsArguments() - { - return argumentType != Void.TYPE; - } - - public boolean getAllowsMultipleArguments() - { - return argumentType == List.class; - } - - public CommandLineOption deprecated( String deprecationWarning ) - { - this.deprecationWarning = deprecationWarning; - return this; - } - - public CommandLineOption incubating() - { - incubating = true; - return this; - } - - 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 deleted file mode 100644 index c2853ad..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/CommandLineParser.java +++ /dev/null @@ -1,675 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Formatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -/** - * <p> - * 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> - * <ul> - * <li>Short options are a '-' followed by a single character. For example: {@code -a}.</li> - * <li>Long options are '--' followed by multiple characters. For example: {@code --long-option}.</li> - * <li>Options can take arguments. The argument follows the option. For example: {@code -a arg} or - * {@code --long arg}.</li> - * <li>Arguments can be attached to the option using '='. For example: {@code -a=arg} or {@code --long=arg}.</li> - * <li>Arguments can be attached to short options. For example: {@code -aarg}.</li> - * <li>Short options can be combined. For example {@code -ab} is equivalent to {@code -a -b}.</li> - * <li>Anything else is treated as an extra argument. This includes a single {@code -} character.</li> - * <li>'--' indicates the end of the options. Anything following is not parsed and is treated as extra arguments.</li> - * <li>The parser is forgiving, and allows '--' to be used with short options and '-' to be used with long options.</li> - * <li>The set of options must be known at parse time. Sub-commands and their options do not need to be known at parse - * time. Use {@link ParsedCommandLine#getExtraArguments()} to obtain the non-option command-line arguments.</li> - * </ul> - */ -public class CommandLineParser -{ - private Map<String, CommandLineOption> optionsByString = new HashMap<String, CommandLineOption>(); - - private boolean allowMixedOptions; - - private boolean allowUnknownOptions; - - private final PrintWriter deprecationPrinter; - - public CommandLineParser() - { - this( new OutputStreamWriter( System.out ) ); - } - - 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 ) ); - } - - /** - * 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 - { - 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 ) ); - 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 ); - parseState = parsedOption.onStartNextArg(); - } - 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 - { - parseState = parsedOption.onComplete(); - 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 ) - { - // if we are allowing unknowns, just pass through the whole arg - parsedOption = parseState.onStartOption( arg, option ); - parseState = parsedOption.onComplete(); - } - 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 ); - parseState = parsedOption.onComplete(); - } - } - } - } - } - else - { - parseState = parseState.onNonOption( arg ); - } - } - - parseState.onCommandLineEnd(); - return parsedCommandLine; - } - - public CommandLineParser allowMixedSubcommandsAndOptions() - { - allowMixedOptions = true; - return this; - } - - 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() ); - Map<String, String> lines = new LinkedHashMap<String, String>(); - 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 ); - } - } - - String key = join( prefixedStrings, ", " ); - String value = option.getDescription(); - if ( value == null || value.length() == 0 ) - { - 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() ); - } - } - formatter.flush(); - } - - private static String join( Collection<?> things, String separator ) - { - StringBuffer buffer = new StringBuffer(); - boolean first = true; - - if ( separator == null ) - { - separator = ""; - } - - for ( Object thing : things ) - { - if ( !first ) - { - buffer.append( separator ); - } - buffer.append( thing.toString() ); - first = false; - } - return buffer.toString(); - } - - /** - * 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 ) ); - } - 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 ); - } - return option; - } - - private static class OptionString - { - private final String arg; - - private final String option; - - private OptionString( String arg, String option ) - { - this.arg = arg; - this.option = option; - } - - public String getDisplayName() - { - return arg.startsWith( "--" ) ? "--" + option : "-" + option; - } - - @Override - public String toString() - { - return getDisplayName(); - } - } - - private abstract static class ParserState - { - public abstract boolean maybeStartOption( String arg ); - - boolean isOption( String arg ) - { - return arg.matches( "-.+" ); - } - - public abstract OptionParserState onStartOption( String arg, String option ); - - public abstract ParserState onNonOption( String arg ); - - public void onCommandLineEnd() - { - } - } - - private abstract class OptionAwareParserState - extends ParserState - { - protected final ParsedCommandLine commandLine; - - protected OptionAwareParserState( ParsedCommandLine commandLine ) - { - this.commandLine = commandLine; - } - - @Override - 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 ); - } - } - - 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 ) ); - } - } - return new KnownOptionParserState( optionString, commandLineOption, commandLine, this ); - } - } - - 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 ); - } - return new KnownOptionParserState( new OptionString( arg, option ), commandLineOption, commandLine, this ); - } - } - - private static class AfterOptions - extends ParserState - { - private final ParsedCommandLine commandLine; - - private AfterOptions( ParsedCommandLine commandLine ) - { - this.commandLine = commandLine; - } - - @Override - public boolean maybeStartOption( String arg ) - { - return false; - } - - @Override - public OptionParserState onStartOption( String arg, String option ) - { - return new UnknownOptionParserState( arg, commandLine, this ); - } - - @Override - public ParserState onNonOption( String arg ) - { - commandLine.addExtraValue( arg ); - return this; - } - } - - private static class MissingOptionArgState - extends ParserState - { - private final OptionParserState option; - - private MissingOptionArgState( OptionParserState option ) - { - this.option = option; - } - - @Override - public boolean maybeStartOption( String arg ) - { - return isOption( arg ); - } - - @Override - public OptionParserState onStartOption( String arg, String option ) - { - return this.option.onComplete().onStartOption( arg, option ); - } - - @Override - public ParserState onNonOption( String arg ) - { - return option.onArgument( arg ); - } - - @Override - public void onCommandLineEnd() - { - option.onComplete(); - } - } - - private abstract static class OptionParserState - { - public abstract ParserState onStartNextArg(); - - public abstract ParserState onArgument( String argument ); - - public abstract boolean getHasArgument(); - - public abstract ParserState onComplete(); - } - - private class KnownOptionParserState - extends OptionParserState - { - private final OptionString optionString; - - private final CommandLineOption option; - - private final ParsedCommandLine commandLine; - - private final ParserState state; - - private final List<String> values = new ArrayList<String>(); - - private KnownOptionParserState( OptionString optionString, CommandLineOption option, - ParsedCommandLine commandLine, ParserState state ) - { - this.optionString = optionString; - this.option = option; - this.commandLine = commandLine; - this.state = state; - } - - @Override - 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 ) ); - } - values.add( argument ); - return onComplete(); - } - - @Override - public ParserState onStartNextArg() - { - if ( option.getAllowsArguments() && values.isEmpty() ) - { - return new MissingOptionArgState( this ); - } - return onComplete(); - } - - @Override - 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 ) ); - } - - 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 ); - } - if ( option.getDeprecationWarning() != null ) - { - deprecationPrinter.println( "The " + optionString + " option is deprecated - " - + option.getDeprecationWarning() ); - } - if ( option.getSubcommand() != null ) - { - return state.onNonOption( option.getSubcommand() ); - } - - return state; - } - } - - 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 ) - { - this.arg = arg; - this.commandLine = commandLine; - this.state = state; - } - - @Override - public boolean getHasArgument() - { - return true; - } - - @Override - public ParserState onStartNextArg() - { - return onComplete(); - } - - @Override - public ParserState onArgument( String argument ) - { - return onComplete(); - } - - @Override - 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 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 ); - } - } - - 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 ) - { - return -1; - } - if ( !short1 && short2 ) - { - return 1; - } - 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 deleted file mode 100644 index 5e0abcb..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLine.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Parsed command line. - */ -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 ) - { - ParsedCommandLineOption parsedOption = new ParsedCommandLineOption(); - for ( String optionStr : option.getOptions() ) - { - optionsByString.put( optionStr, parsedOption ); - } - } - } - - @Override - public String toString() - { - return String.format( "options: %s, extraArguments: %s", quoteAndJoin( presentOptions ), - quoteAndJoin( extraArguments ) ); - } - - private String quoteAndJoin( Iterable<String> strings ) - { - StringBuilder output = new StringBuilder(); - boolean isFirst = true; - for ( String string : strings ) - { - if ( !isFirst ) - { - output.append( ", " ); - } - output.append( "'" ); - output.append( string ); - output.append( "'" ); - isFirst = false; - } - return output.toString(); - } - - /** - * 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 ); - } - - /** - * 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 ) ) - { - return true; - } - } - return false; - } - - /** - * 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 ) ); - } - return parsedOption; - } - - public List<String> getExtraArguments() - { - return extraArguments; - } - - void addExtraValue( String value ) - { - extraArguments.add( value ); - } - - 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 deleted file mode 100644 index 7139ec5..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ParsedCommandLineOption.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.ArrayList; -import java.util.List; - -/** - * Parsed command line option. - */ -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." ); - } - if ( values.size() > 1 ) - { - throw new IllegalStateException( "Option has multiple values." ); - } - return values.get( 0 ); - } - - public List<String> getValues() - { - return values; - } - - public void addArgument( String argument ) - { - values.add( argument ); - } - - 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 deleted file mode 100644 index 90c8c6b..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/ProjectPropertiesCommandLineConverter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * 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. - */ - -/** - * Converter from project properties. - */ -public class ProjectPropertiesCommandLineConverter - extends AbstractPropertiesCommandLineConverter -{ - - @Override - protected String getPropertyOption() - { - return "P"; - } - - @Override - protected String getPropertyOptionDetailed() - { - return "project-prop"; - } - - @Override - 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 deleted file mode 100644 index 70f5edf..0000000 --- a/maven-wrapper/src/main/java/org/apache/maven/wrapper/cli/SystemPropertiesCommandLineConverter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.apache.maven.wrapper.cli; - -/* - * 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. - */ - -/** - * Converter from system properties. - */ -public class SystemPropertiesCommandLineConverter - extends AbstractPropertiesCommandLineConverter -{ - - @Override - protected String getPropertyOption() - { - return "D"; - } - - @Override - protected String getPropertyOptionDetailed() - { - return "system-prop"; - } - - @Override - 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 2027a4a..c0e84c7 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 @@ -19,47 +19,53 @@ package org.apache.maven.wrapper; * under the License. */ -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.File; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.stream.Collectors; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class DownloaderTest { +public class DownloaderTest +{ + @TempDir + public Path testDir; - private DefaultDownloader download; + private DefaultDownloader download; - private File testDir; + private Path downloadFile; - private File downloadFile; + private Path rootDir; - private File rootDir; + private URI sourceRoot; - private URI sourceRoot; + private Path remoteFile; - private File remoteFile; + @BeforeEach + public void setUp() + throws Exception + { + download = new DefaultDownloader( "mvnw", "aVersion" ); + rootDir = testDir.resolve( "root" ); + downloadFile = rootDir.resolve( "file" ); + remoteFile = testDir.resolve( "remoteFile" ); + Files.write( remoteFile, Arrays.asList( "sometext" ) ); + sourceRoot = remoteFile.toUri(); + } - @Before - public void setUp() throws Exception { - download = new DefaultDownloader("mvnw", "aVersion"); - testDir = new File("target/test-files/DownloadTest"); - rootDir = new File(testDir, "root"); - downloadFile = new File(rootDir, "file"); - if (downloadFile.exists()) - downloadFile.delete(); - remoteFile = new File(testDir, "remoteFile"); - FileUtils.write(remoteFile, "sometext"); - sourceRoot = remoteFile.toURI(); - } - - @Test - public void testDownload() throws Exception { - assert !downloadFile.exists(); - download.download(sourceRoot, downloadFile); - assert downloadFile.exists(); - assertEquals("sometext", FileUtils.readFileToString(downloadFile)); - } + @Test + public void testDownload() + throws Exception + { + assert !Files.exists( downloadFile ); + download.download( sourceRoot, downloadFile ); + assert Files.exists( downloadFile ); + assertEquals( "sometext", + Files.readAllLines( downloadFile ).stream().collect( Collectors.joining() ) ); + } } 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 9320be0..bef2057 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 @@ -24,178 +24,191 @@ import static org.mockito.Mockito.when; import java.io.File; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; -import org.apache.commons.io.FileUtils; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Zip; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author Hans Dockter */ -public class InstallerTest { - private File testDir = new File("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis()); +public class InstallerTest +{ + @TempDir + public Path temporaryFolder; - private Installer install; + private Installer install; - private Downloader downloadMock; + private Path distributionDir; - private PathAssembler pathAssemblerMock; + private Path zipStore; - private boolean downloadCalled; + private Path mavenHomeDir; - private File zip; + private Path zipDestination; - private File distributionDir; + private WrapperConfiguration configuration = new WrapperConfiguration(); + + private Downloader download; - private File zipStore; + private PathAssembler pathAssembler; - private File mavenHomeDir; + private PathAssembler.LocalDistribution localDistribution; - private File zipDestination; + @BeforeEach + public void setup() + throws Exception + { + configuration.setZipBase( PathAssembler.PROJECT_STRING ); + configuration.setZipPath( "someZipPath" ); + configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING ); + configuration.setDistributionPath( "someDistPath" ); + configuration.setDistribution( new URI( "http://server/maven-0.9.zip" ) ); + configuration.setAlwaysDownload( false ); + configuration.setAlwaysUnpack( false ); + distributionDir = temporaryFolder.resolve( "someDistPath" ); + Files.createDirectories( distributionDir ); + mavenHomeDir = distributionDir.resolve( "maven-0.9" ); + zipStore = temporaryFolder.resolve( "zips" ); + Files.createDirectories( zipStore ); + zipDestination = zipStore.resolve( "maven-0.9.zip" ); + + download = mock( Downloader.class ); + pathAssembler = mock( PathAssembler.class ); + localDistribution = mock( PathAssembler.LocalDistribution.class ); - private WrapperConfiguration configuration = new WrapperConfiguration(); + when( localDistribution.getZipFile() ).thenReturn( zipDestination ); + when( localDistribution.getDistributionDir() ).thenReturn( distributionDir ); + when( pathAssembler.getDistribution( configuration ) ).thenReturn( localDistribution ); - private Downloader download; + install = new Installer( download, pathAssembler ); + } - private PathAssembler pathAssembler; + private void createTestZip( Path zipDestination ) + throws Exception + { + Files.createDirectories( zipDestination.getParent() ); - private PathAssembler.LocalDistribution localDistribution; + Path explodedZipDir = temporaryFolder.resolve( "explodedZip" ); - @Before - public void setup() throws Exception { - - testDir.mkdirs(); - - downloadCalled = false; - configuration.setZipBase(PathAssembler.PROJECT_STRING); - configuration.setZipPath("someZipPath"); - configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING); - configuration.setDistributionPath("someDistPath"); - configuration.setDistribution(new URI("http://server/maven-0.9.zip")); - configuration.setAlwaysDownload(false); - configuration.setAlwaysUnpack(false); - distributionDir = new File(testDir, "someDistPath"); - mavenHomeDir = new File(distributionDir, "maven-0.9"); - zipStore = new File(testDir, "zips"); - zipDestination = new File(zipStore, "maven-0.9.zip"); - - download = mock(Downloader.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); - - install = new Installer(download, pathAssembler); - - } - - private void createTestZip(File zipDestination) throws Exception { - File explodedZipDir = new File(testDir, "explodedZip"); - explodedZipDir.mkdirs(); - zipDestination.getParentFile().mkdirs(); - File mavenScript = new File(explodedZipDir, "maven-0.9/bin/mvn"); - mavenScript.getParentFile().mkdirs(); - FileUtils.write(mavenScript, "something"); - - zipTo(explodedZipDir, zipDestination); - } - - public void testCreateDist() throws Exception { - File homeDir = install.createDist(configuration); - - Assert.assertEquals(mavenHomeDir, homeDir); - Assert.assertTrue(homeDir.isDirectory()); - Assert.assertTrue(new File(homeDir, "bin/mvn").exists()); - Assert.assertTrue(zipDestination.exists()); - - 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 { - - FileUtils.touch(zipDestination); - mavenHomeDir.mkdirs(); - File someFile = new File(mavenHomeDir, "some-file"); - FileUtils.touch(someFile); - - File homeDir = install.createDist(configuration); - - Assert.assertEquals(mavenHomeDir, homeDir); - Assert.assertTrue(mavenHomeDir.isDirectory()); - Assert.assertTrue(new File(homeDir, "some-file").exists()); - Assert.assertTrue(zipDestination.exists()); - - Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration)); - Assert.assertEquals(distributionDir, localDistribution.getDistributionDir()); - Assert.assertEquals(zipDestination, localDistribution.getZipFile()); - } - - @Test - public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue() throws Exception { - - createTestZip(zipDestination); - mavenHomeDir.mkdirs(); - File garbage = new File(mavenHomeDir, "garbage"); - FileUtils.touch(garbage); - configuration.setAlwaysUnpack(true); - - File homeDir = install.createDist(configuration); - - Assert.assertEquals(mavenHomeDir, homeDir); - Assert.assertTrue(mavenHomeDir.isDirectory()); - Assert.assertFalse(new File(homeDir, "garbage").exists()); - Assert.assertTrue(zipDestination.exists()); - - Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration)); - Assert.assertEquals(distributionDir, localDistribution.getDistributionDir()); - Assert.assertEquals(zipDestination, localDistribution.getZipFile()); - } - - @Test - public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue() throws Exception { - - createTestZip(zipDestination); - File garbage = new File(mavenHomeDir, "garbage"); - FileUtils.touch(garbage); - configuration.setAlwaysUnpack(true); - - File homeDir = install.createDist(configuration); - - Assert.assertEquals(mavenHomeDir, homeDir); - Assert.assertTrue(mavenHomeDir.isDirectory()); - Assert.assertTrue(new File(homeDir, "bin/mvn").exists()); - Assert.assertFalse(new File(homeDir, "garbage").exists()); - Assert.assertTrue(zipDestination.exists()); - - 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); - } - - public void zipTo(File directoryToZip, File zipFile) { - Zip zip = new Zip(); - zip.setBasedir(directoryToZip); - zip.setDestFile(zipFile); - zip.setProject(new Project()); - - Zip.WhenEmpty whenEmpty = new Zip.WhenEmpty(); - whenEmpty.setValue("create"); - zip.setWhenempty(whenEmpty); - zip.execute(); - } + Path mavenScript = explodedZipDir.resolve( "maven-0.9/bin/mvn" ); + Files.createDirectories( mavenScript.getParent() ); + Files.write( mavenScript, Arrays.asList( "something" ) ); + zipTo( explodedZipDir, zipDestination ); + } + + @Test + @Disabled("not working") + 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 + { + Files.createFile( zipDestination ); + + Files.createDirectories( mavenHomeDir ); + Path someFile = mavenHomeDir.resolve( "some-file" ); + Files.createFile( 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 ); + File garbage = mavenHomeDir.resolve( "garbage" ).toFile(); + Files.createFile( garbage.toPath() ); + + 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 ); + Files.createDirectories( mavenHomeDir ); + File garbage = mavenHomeDir.resolve( "garbage" ).toFile(); + Files.createFile( garbage.toPath() ); + + 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); + } + + public void zipTo( Path directoryToZip, Path zipFile ) + { + Zip zip = new Zip(); + zip.setBasedir( directoryToZip.toFile() ); + zip.setDestFile( zipFile.toFile() ); + zip.setProject( new Project() ); + + Zip.WhenEmpty whenEmpty = new Zip.WhenEmpty(); + whenEmpty.setValue( "create" ); + zip.setWhenempty( whenEmpty ); + zip.execute(); + } } 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 2532b0b..a2334c1 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 @@ -19,109 +19,97 @@ 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.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.File; import java.net.URI; -import java.util.regex.Pattern; +import java.nio.file.Path; +import java.nio.file.Paths; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Hans Dockter */ -public class PathAssemblerTest { - public static final String TEST_MAVEN_USER_HOME = "someUserHome"; - - private PathAssembler pathAssembler = new PathAssembler(new File(TEST_MAVEN_USER_HOME)); - - final WrapperConfiguration configuration = new WrapperConfiguration(); - - @Before - public void setup() { - configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING); - configuration.setDistributionPath("somePath"); - configuration.setZipBase(PathAssembler.MAVEN_USER_HOME_STRING); - configuration.setZipPath("somePath"); - } - - @Test - public void distributionDirWithMavenUserHomeBase() throws Exception { - configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip")); - - File distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir(); - assertThat(distributionDir.getName(), matchesRegexp("[a-z0-9]+")); - assertThat(distributionDir.getParentFile(), 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")); - - File distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir(); - assertThat(distributionDir.getName(), matchesRegexp("[a-z0-9]+")); - assertThat(distributionDir.getParentFile(), 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()); +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(); + + @BeforeEach + public void setup() + { + configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING ); + configuration.setDistributionPath( "somePath" ); + configuration.setZipBase( PathAssembler.MAVEN_USER_HOME_STRING ); + configuration.setZipPath( "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, is( Paths.get( 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, equalTo( Paths.get( 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" ); + + RuntimeException e = + assertThrows( RuntimeException.class, () -> pathAssembler.getDistribution( configuration ) ); + 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(), equalTo( Paths.get( 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(), equalTo( Paths.get( currentDirPath(), "/somePath/maven-1.0" ) ) ); + } + + private String currentDirPath() + { + return System.getProperty( "user.dir" ); } - } - - @Test - public void distZipWithMavenUserHomeBase() throws Exception { - configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip")); - - File dist = pathAssembler.getDistribution(configuration).getZipFile(); - assertThat(dist.getName(), equalTo("maven-1.0.zip")); - assertThat(dist.getParentFile().getName(), matchesRegexp("[a-z0-9]+")); - assertThat(dist.getParentFile().getParentFile(), 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")); - - File dist = pathAssembler.getDistribution(configuration).getZipFile(); - assertThat(dist.getName(), equalTo("maven-1.0.zip")); - assertThat(dist.getParentFile().getName(), matchesRegexp("[a-z0-9]+")); - assertThat(dist.getParentFile().getParentFile(), equalTo(file(currentDirPath() + "/somePath/maven-1.0"))); - } - - private File file(String path) { - return new File(path); - } - - private String currentDirPath() { - return System.getProperty("user.dir"); - } - - public static <T extends CharSequence> Matcher<T> matchesRegexp(final String pattern) { - return new BaseMatcher<T>() { - public boolean matches(Object o) { - return Pattern.compile(pattern).matcher((CharSequence) o).matches(); - } - - 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 deleted file mode 100644 index b5112ea..0000000 --- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.apache.maven.wrapper; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Test; - -public class SystemPropertiesHandlerTest { - - private File tmpDir = new File("target/test-files/SystemPropertiesHandlerTest"); - - @Before - public void setupTempDir() { - tmpDir.mkdirs(); - } - - @Test - public void testParsePropertiesFile() throws Exception { - File propFile = new File(tmpDir, "props"); - Properties props = new Properties(); - props.put("a", "b"); - props.put("systemProp.c", "d"); - props.put("systemProp.", "e"); - - FileOutputStream fos = null; - try { - fos = new FileOutputStream(propFile); - props.store(fos, ""); - } finally { - IOUtils.closeQuietly(fos); - } - - Map<String, String> expected = new HashMap<String, String>(); - expected.put("c", "d"); - - assertThat(SystemPropertiesHandler.getSystemProperties(propFile), equalTo(expected)); - } - - @Test - public void ifNoPropertyFileExistShouldReturnEmptyMap() { - Map<String, String> expected = new HashMap<String, String>(); - assertThat(SystemPropertiesHandler.getSystemProperties(new File(tmpDir, "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 d6ed891..23bcf21 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 @@ -19,167 +19,184 @@ package org.apache.maven.wrapper; * under the License. */ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.File; -import java.io.FileOutputStream; +import java.io.IOException; import java.io.OutputStream; import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Properties; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; -public class WrapperExecutorTest { - private final Installer install; - - private final BootstrapMainStarter start; - - private File propertiesFile; - - private Properties properties = new Properties(); - - private File testDir = new File("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis()); - - private File mockInstallDir = new File(testDir, "mock-dir"); - - public WrapperExecutorTest() throws Exception { - install = mock(Installer.class); - when(install.createDist(Mockito.any(WrapperConfiguration.class))).thenReturn(mockInstallDir); - start = mock(BootstrapMainStarter.class); - - testDir.mkdirs(); - propertiesFile = new File(testDir, "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, System.out); - - 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()); - Assert.assertEquals("testZipBase", wrapper.getConfiguration().getZipBase()); - Assert.assertEquals("testZipPath", wrapper.getConfiguration().getZipPath()); - } - - @Test - public void loadWrapperMetadataFromDirectory() throws Exception { - WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(testDir, System.out); - - 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()); - Assert.assertEquals("testZipBase", wrapper.getConfiguration().getZipBase()); - Assert.assertEquals("testZipPath", wrapper.getConfiguration().getZipPath()); - } - - @Test - public void useDefaultMetadataNoProeprtiesFile() throws Exception { - WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(new File(testDir, "unknown"), System.out); - - 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, System.out); - - 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, System.out); - - 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, System.out); - 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()); +public class WrapperExecutorTest +{ + @TempDir + public Path testDir; + + private Installer install; + + private BootstrapMainStarter start; + + private Path propertiesFile; + + private Properties properties = new Properties(); + + private Path mockInstallDir; + + @BeforeEach + public void setUp() + throws Exception + { + mockInstallDir = testDir.resolve( "mock-dir" ); + + install = mock( Installer.class ); + when( install.createDist( Mockito.any( WrapperConfiguration.class ) ) ).thenReturn( mockInstallDir ); + start = mock( BootstrapMainStarter.class ); + + propertiesFile = testDir.resolve( "maven" ).resolve( "wrapper" ).resolve( "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 ); + + assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); + assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); + assertEquals( "testDistBase", wrapper.getConfiguration().getDistributionBase() ); + assertEquals( "testDistPath", wrapper.getConfiguration().getDistributionPath() ); + assertEquals( "testZipBase", wrapper.getConfiguration().getZipBase() ); + assertEquals( "testZipPath", wrapper.getConfiguration().getZipPath() ); + } - @Test - public void failWhenPropertiesFileDoesNotExist() { - propertiesFile = new File(testDir, "unknown.properties"); + @Test + public void loadWrapperMetadataFromDirectory() + throws Exception + { + WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir ); + + assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); + assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); + assertEquals( "testDistBase", wrapper.getConfiguration().getDistributionBase() ); + assertEquals( "testDistPath", wrapper.getConfiguration().getDistributionPath() ); + assertEquals( "testZipBase", wrapper.getConfiguration().getZipBase() ); + assertEquals( "testZipPath", wrapper.getConfiguration().getZipPath() ); + } - try { - WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out); - Assert.fail("Expected RuntimeException"); - } catch (RuntimeException e) { - Assert.assertEquals("Wrapper properties file '" + propertiesFile + "' does not exist.", e.getMessage()); + @Test + public void useDefaultMetadataNoProeprtiesFile() + throws Exception + { + WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir.resolve( "unknown" ) ); + + assertNull( wrapper.getDistribution() ); + assertNull( wrapper.getConfiguration().getDistribution() ); + assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase() ); + assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath() ); + assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase() ); + assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getZipPath() ); } - } - @Test - public void testRelativeDistUrl() throws Exception { + @Test + public void propertiesFileOnlyContainsDistURL() + throws Exception + { - properties = new Properties(); - properties.put("distributionUrl", "some/relative/url/to/bin.zip"); - writePropertiesFile(properties, propertiesFile, "header"); + properties = new Properties(); + properties.put( "distributionUrl", "http://server/test/maven.zip" ); + writePropertiesFile( properties, propertiesFile, "header" ); - WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out); - Assert.assertNotEquals("some/relative/url/to/bin.zip", wrapper.getDistribution().getSchemeSpecificPart()); - Assert.assertTrue(wrapper.getDistribution().getSchemeSpecificPart().endsWith("some/relative/url/to/bin.zip")); - } + WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); - private void writePropertiesFile(Properties properties, File propertiesFile, String message) throws Exception { + assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); + assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); + assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase() ); + assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath() ); + assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase() ); + 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" ); + + RuntimeException e = assertThrows( + RuntimeException.class, + () -> WrapperExecutor.forWrapperPropertiesFile( propertiesFile ), + "Expected RuntimeException" ); + assertEquals( "No value with key 'distributionUrl' specified in wrapper properties file '" + + propertiesFile + "'.", e.getMessage() ); + } + + @Test + public void failWhenPropertiesFileDoesNotExist() + { + propertiesFile = testDir.resolve( "unknown.properties" ); + + RuntimeException e = assertThrows( + RuntimeException.class, + () -> WrapperExecutor.forWrapperPropertiesFile( propertiesFile ), + "Expected RuntimeException" ); + 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 ); + assertNotEquals( "some/relative/url/to/bin.zip", wrapper.getDistribution().getSchemeSpecificPart() ); + assertTrue( wrapper.getDistribution().getSchemeSpecificPart().endsWith( "some/relative/url/to/bin.zip" ) ); + } - propertiesFile.getParentFile().mkdirs(); + private void writePropertiesFile( Properties properties, Path propertiesFile, String message ) + throws IOException + { + Files.createDirectories( propertiesFile.getParent() ); - OutputStream outStream = null; - try { - outStream = new FileOutputStream(propertiesFile); - properties.store(outStream, message); - } finally { - IOUtils.closeQuietly(outStream); + try ( OutputStream outStream = Files.newOutputStream( propertiesFile ) ) + { + properties.store( outStream, message ); + } } - } } diff --git a/pom.xml b/pom.xml index 654cc2c..82431b5 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,7 @@ under the License. <properties> <maven.site.path>wrapper-archives/wrapper-LATEST</maven.site.path> <mavenVersion>3.1.0</mavenVersion> - <javaVersion>7</javaVersion> + <javaVersion>7</javaVersion> <!-- MWRAPPER-34 !! --> <project.build.outputTimestamp>2021-11-26T10:03:59Z</project.build.outputTimestamp> </properties>