From f813d54ae93af7e2376657b815996a5ce0b2b67e Mon Sep 17 00:00:00 2001 From: rfscholte Date: Sat, 2 May 2020 13:41:13 +0200 Subject: [PATCH] [MNG-5937] Optimize code for Java 8 --- maven-wrapper/pom.xml | 19 +- .../maven/wrapper/BootstrapMainStarter.java | 31 ++- .../maven/wrapper/DefaultDownloader.java | 43 ++-- .../org/apache/maven/wrapper/Downloader.java | 26 ++- .../org/apache/maven/wrapper/Installer.java | 193 ++++++++---------- .../maven/wrapper/MavenWrapperMain.java | 76 +++---- .../apache/maven/wrapper/PathAssembler.java | 64 ++---- .../wrapper/SystemPropertiesHandler.java | 77 ------- .../apache/maven/wrapper/WrapperExecutor.java | 42 ++-- .../apache/maven/wrapper/DownloaderTest.java | 38 ++-- .../apache/maven/wrapper/InstallerTest.java | 115 +++++------ .../maven/wrapper/PathAssemblerTest.java | 68 ++---- .../wrapper/SystemPropertiesHandlerTest.java | 79 ------- .../maven/wrapper/WrapperExecutorTest.java | 68 +++--- pom.xml | 2 +- 15 files changed, 338 insertions(+), 603 deletions(-) delete mode 100644 maven-wrapper/src/main/java/org/apache/maven/wrapper/SystemPropertiesHandler.java delete mode 100644 maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.java diff --git a/maven-wrapper/pom.xml b/maven-wrapper/pom.xml index 917db01570..c7c682bb78 100644 --- a/maven-wrapper/pom.xml +++ b/maven-wrapper/pom.xml @@ -38,30 +38,19 @@ under the License. junit junit - 4.12 + 4.13 test org.hamcrest - hamcrest-all - 1.3 + hamcrest + 2.2 test org.mockito mockito-core - test - - - commons-lang - commons-lang - 2.6 - test - - - commons-io - commons-io - 2.6 + 2.23.0 test 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 959a9b5d83..f4a5d73eb6 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 @@ -19,42 +19,41 @@ package org.apache.maven.wrapper; * under the License. */ -import java.io.File; +import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; /** * @author Hans Dockter */ 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 ); + 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 } ); } - private File findLauncherJar( File mavenHome ) + private Path findLauncherJar( Path mavenHome ) throws RuntimeException, IOException { - for ( File file : new File( mavenHome, "boot" ).listFiles() ) - { - if ( file.getName().matches( "plexus-classworlds-.*\\.jar" ) ) - { - return file; - } - } - throw new RuntimeException( - String.format( "Could not locate the Maven launcher JAR in Maven distribution '%s'.", mavenHome ) ); + return Files.list( mavenHome.resolve( "boot" ) ) + .filter( p -> p.getFileName().toString().matches( "plexus-classworlds-.*\\.jar" ) ) + .findFirst() + .orElseThrow( () -> new RuntimeException( + String.format( "Couldn't locate the Maven launcher JAR in Maven distribution '%s'.", + mavenHome ) ) ); } } diff --git a/maven-wrapper/src/main/java/org/apache/maven/wrapper/DefaultDownloader.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/DefaultDownloader.java index 5d0db68c0d..943189bfca 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,8 +23,6 @@ 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; @@ -34,6 +32,8 @@ 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; /** @@ -73,6 +73,7 @@ public class DefaultDownloader { Authenticator.setDefault( new Authenticator() { + @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( System.getProperty( "MVNW_USERNAME" ), @@ -82,33 +83,29 @@ public class DefaultDownloader } } - 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; @@ -126,14 +123,6 @@ public class DefaultDownloader finally { Logger.info( "" ); - if ( in != null ) - { - in.close(); - } - if ( out != null ) - { - out.close(); - } } } 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 eb1e69343d..42bda01b56 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,14 +19,34 @@ 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; /** * @author Hans Dockter */ 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 ffa7b44f00..f763de340c 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,20 +19,21 @@ 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.util.ArrayList; +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.Enumeration; import java.util.Formatter; import java.util.List; import java.util.Locale; +import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -54,8 +55,8 @@ public class Installer this.pathAssembler = pathAssembler; } - public File createDist( WrapperConfiguration configuration ) - throws Exception + public Path createDist( WrapperConfiguration configuration ) + throws IOException, URISyntaxException { URI distributionUrl; String mvnwRepoUrl = System.getenv( MavenWrapperMain.MVNW_REPOURL ); @@ -74,30 +75,51 @@ public class Installer PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution( configuration ); - 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 dirs = listDirs( distDir ); + Path distDir = localDistribution.getDistributionDir(); + List dirs = listDirs( distDir ); if ( downloaded || alwaysUnpack || dirs.isEmpty() ) { - for ( File dir : dirs ) + Files.walkFileTree( distDir.toAbsolutePath(), new SimpleFileVisitor() { - 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 ); if ( dirs.isEmpty() ) { @@ -109,68 +131,59 @@ public class Installer } if ( dirs.size() != 1 ) { - throw new RuntimeException( String.format( + throw new IllegalStateException( String.format( "Maven distribution '%s' contains too many directories. Expected to find exactly 1 directory.", distributionUrl ) ); } return dirs.get( 0 ); } - private List listDirs( File distDir ) + private List listDirs( Path distDir ) throws IOException { - List dirs = new ArrayList(); - if ( distDir.exists() ) - { - for ( File file : distDir.listFiles() ) - { - if ( file.isDirectory() ) - { - dirs.add( file ); - } - } - } - return dirs; + return Files.walk( distDir, 1 ) + .filter( p -> !distDir.equals( p ) ) + .filter( Files::isDirectory ) + .collect( Collectors.toList() ); } - 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( "Could not set executable permissions for: " + mavenCommand ); Logger.warn( "Please do this manually if you want to use maven." ); } } @@ -178,72 +191,36 @@ public class Installer private boolean isWindows() { String osName = System.getProperty( "os.name" ).toLowerCase( Locale.US ); - if ( osName.indexOf( "windows" ) > -1 ) - { - return true; - } - return false; + + return ( osName.indexOf( "windows" ) > -1 ); } - private boolean deleteDir( File dir ) + private void unzip( Path zip, Path dest ) + throws IOException { - if ( dir.isDirectory() ) + try ( ZipFile zipFile = new ZipFile( zip.toFile() ) ) { - String[] children = dir.list(); - for ( int i = 0; i < children.length; i++ ) + Enumeration entries = zipFile.entries(); + + while ( entries.hasMoreElements() ) { - boolean success = deleteDir( new File( dir, children[i] ) ); - if ( !success ) + ZipEntry entry = entries.nextElement(); + + if ( entry.isDirectory() ) { - return false; + continue; + } + + Path targetFile = dest.resolve( entry.getName() ); + + // prevent Zip Slip + if ( targetFile.startsWith( dest ) ) + { + Files.createDirectories( targetFile.getParent() ); + + Files.copy( zipFile.getInputStream( entry ), targetFile ); } } } - - // The directory is now empty so delete it - return dir.delete(); } - - public void unzip( File zip, File dest ) - throws IOException - { - Enumeration entries; - ZipFile zipFile; - - zipFile = new ZipFile( zip ); - - entries = zipFile.entries(); - - while ( entries.hasMoreElements() ) - { - ZipEntry entry = (ZipEntry) entries.nextElement(); - - if ( entry.isDirectory() ) - { - ( new File( dest, entry.getName() ) ).mkdirs(); - continue; - } - - new File( dest, entry.getName() ).getParentFile().mkdirs(); - copyInputStream( zipFile.getInputStream( entry ), - new BufferedOutputStream( new FileOutputStream( new File( dest, entry.getName() ) ) ) ); - } - zipFile.close(); - } - - public void copyInputStream( InputStream in, OutputStream out ) - throws IOException - { - byte[] buffer = new byte[1024]; - int len; - - while ( ( len = in.read( buffer ) ) >= 0 ) - { - out.write( buffer, 0, len ); - } - - in.close(); - out.close(); - } - } 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 fe49450f57..8dec0b75c0 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,10 +19,12 @@ 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.nio.file.Path; +import java.nio.file.Paths; import java.util.Properties; /** @@ -30,6 +32,8 @@ import java.util.Properties; */ public class MavenWrapperMain { + private static final String POM_PROPERTIES = "/META-INF/maven/org.apache.maven/maven-wrapper/pom.properties"; + public static final String DEFAULT_MAVEN_USER_HOME = System.getProperty( "user.home" ) + "/.m2"; public static final String MAVEN_USER_HOME_PROPERTY_KEY = "maven.user.home"; @@ -44,98 +48,76 @@ public class MavenWrapperMain public static final String MVNW_REPOURL = "MVNW_REPOURL"; - public static final String MVN_VERSION = "3.6.3"; - public static final String MVN_PATH = - "org/apache/maven/apache-maven/" + MVN_VERSION + "/apache-maven-" + MVN_VERSION + "-bin.zip"; + "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 ); + Path wrapperJar = wrapperJar(); + Path propertiesFile = wrapperProperties( wrapperJar ); String wrapperVersion = wrapperVersion(); Logger.info( "Apache Maven Wrapper " + wrapperVersion ); - 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 File wrapperProperties( File wrapperJar ) + private static Path wrapperProperties( Path wrapperJar ) throws URISyntaxException { - return new File( wrapperJar.getParent(), wrapperJar.getName().replaceFirst( "\\.jar$", ".properties" ) ); + return wrapperJar().resolveSibling( wrapperJar.getFileName().toString().replaceFirst( "\\.jar$", + ".properties" ) ); } - private static File wrapperJar() + private static Path wrapperJar() throws URISyntaxException { - 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() ); + URI location = MavenWrapperMain.class.getProtectionDomain().getCodeSource().getLocation().toURI(); + + return Paths.get( location ); } static String wrapperVersion() { - try + try ( InputStream resourceAsStream = MavenWrapperMain.class.getResourceAsStream( POM_PROPERTIES ) ) { - InputStream resourceAsStream = - MavenWrapperMain.class.getResourceAsStream( "/META-INF/maven/io.takari/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 ); + return Paths.get( mavenUserHome ); } mavenUserHome = System.getenv( MAVEN_USER_HOME_ENV_KEY ); - if ( mavenUserHome != null ) + if ( mavenUserHome != null ) { - return new File( mavenUserHome ); + return Paths.get( mavenUserHome ); } else { - return new File( DEFAULT_MAVEN_USER_HOME ); + 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 af44ddaf6e..fd999861a4 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,13 +32,13 @@ 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; } @@ -50,36 +49,17 @@ public class PathAssembler 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( "." ); @@ -101,19 +81,19 @@ 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" ); } } @@ -122,11 +102,11 @@ public class PathAssembler */ 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; @@ -135,7 +115,7 @@ public class PathAssembler /** * Returns the location to install the distribution into. */ - public File getDistributionDir() + public Path getDistributionDir() { return distDir; } @@ -143,7 +123,7 @@ public class PathAssembler /** * Returns 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 ac454786f9..0000000000 --- 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 getSystemProperties( File propertiesFile ) - { - Map propertyMap = new HashMap(); - 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/WrapperExecutor.java b/maven-wrapper/src/main/java/org/apache/maven/wrapper/WrapperExecutor.java index 0b7537c3f0..ee9ebecabd 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,12 +19,12 @@ 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; /** @@ -44,34 +44,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 { @@ -82,7 +79,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 ), @@ -98,7 +95,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 { @@ -118,18 +115,13 @@ 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(); - } } /** @@ -152,7 +144,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/test/java/org/apache/maven/wrapper/DownloaderTest.java b/maven-wrapper/src/test/java/org/apache/maven/wrapper/DownloaderTest.java index 314b54fbbf..68bc5c61f1 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 @@ -21,50 +21,52 @@ package org.apache.maven.wrapper; import static org.junit.Assert.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.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; public class DownloaderTest { + @Rule + public TemporaryFolder testDir = new TemporaryFolder(); private DefaultDownloader download; - private File testDir; + private Path downloadFile; - private File downloadFile; - - private File rootDir; + private Path rootDir; private URI sourceRoot; - private File remoteFile; + private Path remoteFile; @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(); + rootDir = testDir.newFolder( "root" ).toPath(); + downloadFile = rootDir.resolve( "file" ); + remoteFile = testDir.newFile( "remoteFile" ).toPath(); + Files.write( remoteFile, Arrays.asList( "sometext" ) ); + sourceRoot = remoteFile.toUri(); } @Test public void testDownload() throws Exception { - assert !downloadFile.exists(); + assert !Files.exists( downloadFile ); download.download( sourceRoot, downloadFile ); - assert downloadFile.exists(); - assertEquals( "sometext", FileUtils.readFileToString( 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 c469b14c7b..3ff712a429 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,38 +24,35 @@ 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.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; /** * @author Hans Dockter */ public class InstallerTest { - private File testDir = new File( "target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis() ); + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); 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 File distributionDir; - - private File zipStore; - - private File mavenHomeDir; - - private File zipDestination; + private Path zipDestination; private WrapperConfiguration configuration = new WrapperConfiguration(); @@ -69,10 +66,6 @@ public class InstallerTest public void setup() throws Exception { - - testDir.mkdirs(); - - downloadCalled = false; configuration.setZipBase( PathAssembler.PROJECT_STRING ); configuration.setZipPath( "someZipPath" ); configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING ); @@ -80,10 +73,10 @@ public class InstallerTest 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" ); + distributionDir = temporaryFolder.newFolder( "someDistPath" ).toPath(); + mavenHomeDir = distributionDir.resolve( "maven-0.9" ); + zipStore = temporaryFolder.newFolder( "zips" ).toPath(); + zipDestination = zipStore.resolve( "maven-0.9.zip" ); download = mock( Downloader.class ); pathAssembler = mock( PathAssembler.class ); @@ -94,18 +87,18 @@ public class InstallerTest when( pathAssembler.getDistribution( configuration ) ).thenReturn( localDistribution ); install = new Installer( download, pathAssembler ); - } - private void createTestZip( File zipDestination ) + private void createTestZip( Path 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" ); + Files.createDirectories( zipDestination.getParent() ); + + Path explodedZipDir = temporaryFolder.newFolder( "explodedZip" ).toPath(); + + Path mavenScript = explodedZipDir.resolve( "maven-0.9/bin/mvn" ); + Files.createDirectories( mavenScript.getParent() ); + Files.write( mavenScript, Arrays.asList( "something" ) ); zipTo( explodedZipDir, zipDestination ); } @@ -113,12 +106,12 @@ public class InstallerTest public void testCreateDist() throws Exception { - File homeDir = install.createDist( configuration ); + Path 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.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() ); @@ -132,18 +125,18 @@ public class InstallerTest public void testCreateDistWithExistingDistribution() throws Exception { + Files.createFile( zipDestination ); - FileUtils.touch( zipDestination ); - mavenHomeDir.mkdirs(); - File someFile = new File( mavenHomeDir, "some-file" ); - FileUtils.touch( someFile ); + Files.createDirectories( mavenHomeDir ); + Path someFile = mavenHomeDir.resolve( "some-file" ); + Files.createFile( someFile ); - File homeDir = install.createDist( configuration ); + Path 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.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() ); @@ -156,17 +149,18 @@ public class InstallerTest { createTestZip( zipDestination ); - mavenHomeDir.mkdirs(); - File garbage = new File( mavenHomeDir, "garbage" ); - FileUtils.touch( garbage ); + Files.createDirectories( mavenHomeDir ); + File garbage = mavenHomeDir.resolve( "garbage" ).toFile(); + Files.createFile( garbage.toPath() ); + configuration.setAlwaysUnpack( true ); - File homeDir = install.createDist( configuration ); + Path homeDir = install.createDist( configuration ); Assert.assertEquals( mavenHomeDir, homeDir ); - Assert.assertTrue( mavenHomeDir.isDirectory() ); - Assert.assertFalse( new File( homeDir, "garbage" ).exists() ); - Assert.assertTrue( zipDestination.exists() ); + 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() ); @@ -179,17 +173,19 @@ public class InstallerTest { createTestZip( zipDestination ); - File garbage = new File( mavenHomeDir, "garbage" ); - FileUtils.touch( garbage ); + Files.createDirectories( mavenHomeDir ); + File garbage = mavenHomeDir.resolve( "garbage" ).toFile(); + Files.createFile( garbage.toPath() ); + configuration.setAlwaysUnpack( true ); - File homeDir = install.createDist( configuration ); + Path 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.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() ); @@ -199,11 +195,11 @@ public class InstallerTest // verify(download).download(new URI("http://some/test"), distributionDir); } - public void zipTo( File directoryToZip, File zipFile ) + public void zipTo( Path directoryToZip, Path zipFile ) { Zip zip = new Zip(); - zip.setBasedir( directoryToZip ); - zip.setDestFile( zipFile ); + zip.setBasedir( directoryToZip.toFile() ); + zip.setDestFile( zipFile.toFile() ); zip.setProject( new Project() ); Zip.WhenEmpty whenEmpty = new Zip.WhenEmpty(); @@ -211,5 +207,4 @@ public class InstallerTest 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 cc2a92dd1b..9e22be0ea6 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,13 +19,16 @@ package org.apache.maven.wrapper; * under the License. */ +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import java.io.File; import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.regex.Pattern; import org.hamcrest.BaseMatcher; @@ -41,7 +44,7 @@ public class PathAssemblerTest { public static final String TEST_MAVEN_USER_HOME = "someUserHome"; - private PathAssembler pathAssembler = new PathAssembler( new File( TEST_MAVEN_USER_HOME ) ); + private PathAssembler pathAssembler = new PathAssembler( Paths.get( TEST_MAVEN_USER_HOME ) ); final WrapperConfiguration configuration = new WrapperConfiguration(); @@ -60,10 +63,8 @@ public class PathAssemblerTest { 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" ) ) ); + Path distributionDir = pathAssembler.getDistribution( configuration ).getDistributionDir(); + assertThat( distributionDir, is( Paths.get( TEST_MAVEN_USER_HOME, "/somePath/maven-0.9-bin" ) ) ); } @Test @@ -73,9 +74,8 @@ public class PathAssemblerTest 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" ) ) ); + Path distributionDir = pathAssembler.getDistribution( configuration ).getDistributionDir(); + assertThat( distributionDir, equalTo( Paths.get( currentDirPath(), "/somePath/maven-0.9-bin" ) ) ); } @Test @@ -85,15 +85,9 @@ public class PathAssemblerTest 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() ); - } + RuntimeException e = + assertThrows( RuntimeException.class, () -> pathAssembler.getDistribution( configuration ) ); + assertEquals( "Base: unknownBase is unknown", e.getMessage() ); } @Test @@ -102,11 +96,9 @@ public class PathAssemblerTest { 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" ) ) ); + 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 @@ -116,35 +108,13 @@ public class PathAssemblerTest 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 ); + 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" ); } - - public static Matcher matchesRegexp( final String pattern ) - { - return new BaseMatcher() - { - 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 f08fbdaac6..0000000000 --- a/maven-wrapper/src/test/java/org/apache/maven/wrapper/SystemPropertiesHandlerTest.java +++ /dev/null @@ -1,79 +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 expected = new HashMap(); - expected.put( "c", "d" ); - - assertThat( SystemPropertiesHandler.getSystemProperties( propFile ), equalTo( expected ) ); - } - - @Test - public void ifNoPropertyFileExistShouldReturnEmptyMap() - { - Map expected = new HashMap(); - 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 83cae1a094..2373fafc7f 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 @@ -23,40 +23,46 @@ 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.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; public class WrapperExecutorTest { - private final Installer install; + @Rule + public TemporaryFolder testDir = new TemporaryFolder(); - private final BootstrapMainStarter start; + private Installer install; - private File propertiesFile; + private BootstrapMainStarter start; + + private Path propertiesFile; private Properties properties = new Properties(); - private File testDir = new File( "target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis() ); + private Path mockInstallDir; - private File mockInstallDir = new File( testDir, "mock-dir" ); - - public WrapperExecutorTest() + @Before + public void setUp() throws Exception { + mockInstallDir = testDir.newFolder( "mock-dir" ).toPath(); + 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" ); + propertiesFile = testDir.newFolder( "maven", "wrapper" ).toPath().resolve( "maven-wrapper.properties" ); properties.put( "distributionUrl", "http://server/test/maven.zip" ); properties.put( "distributionBase", "testDistBase" ); @@ -65,14 +71,13 @@ public class WrapperExecutorTest properties.put( "zipStorePath", "testZipPath" ); writePropertiesFile( properties, propertiesFile, "header" ); - } @Test public void loadWrapperMetadataFromFile() throws Exception { - WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); + WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); @@ -86,7 +91,7 @@ public class WrapperExecutorTest public void loadWrapperMetadataFromDirectory() throws Exception { - WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir, System.out ); + WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir.getRoot().toPath() ); Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); @@ -100,7 +105,7 @@ public class WrapperExecutorTest public void useDefaultMetadataNoProeprtiesFile() throws Exception { - WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( new File( testDir, "unknown" ), System.out ); + WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir.getRoot().toPath().resolve( "unknown" ) ); Assert.assertNull( wrapper.getDistribution() ); Assert.assertNull( wrapper.getConfiguration().getDistribution() ); @@ -119,7 +124,7 @@ public class WrapperExecutorTest properties.put( "distributionUrl", "http://server/test/maven.zip" ); writePropertiesFile( properties, propertiesFile, "header" ); - WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); + WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); @@ -133,7 +138,7 @@ public class WrapperExecutorTest public void executeInstallAndLaunch() throws Exception { - WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( propertiesFile, System.out ); + WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( propertiesFile ); wrapper.execute( new String[] { "arg" }, install, start ); verify( install ).createDist( Mockito.any( WrapperConfiguration.class ) ); @@ -149,26 +154,24 @@ public class WrapperExecutorTest try { - WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); + WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); Assert.fail( "Expected RuntimeException" ); } catch ( RuntimeException e ) { - Assert.assertEquals( "Could not load wrapper properties from '" + propertiesFile + "'.", e.getMessage() ); Assert.assertEquals( "No value with key 'distributionUrl' specified in wrapper properties file '" - + propertiesFile + "'.", e.getCause().getMessage() ); + + propertiesFile + "'.", e.getMessage() ); } - } @Test public void failWhenPropertiesFileDoesNotExist() { - propertiesFile = new File( testDir, "unknown.properties" ); + propertiesFile = testDir.getRoot().toPath().resolve( "unknown.properties" ); try { - WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); + WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); Assert.fail( "Expected RuntimeException" ); } catch ( RuntimeException e ) @@ -186,26 +189,19 @@ public class WrapperExecutorTest properties.put( "distributionUrl", "some/relative/url/to/bin.zip" ); writePropertiesFile( properties, propertiesFile, "header" ); - WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); + WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile ); Assert.assertNotEquals( "some/relative/url/to/bin.zip", wrapper.getDistribution().getSchemeSpecificPart() ); Assert.assertTrue( wrapper.getDistribution().getSchemeSpecificPart().endsWith( "some/relative/url/to/bin.zip" ) ); } - private void writePropertiesFile( Properties properties, File propertiesFile, String message ) - throws Exception + private void writePropertiesFile( Properties properties, Path propertiesFile, String message ) + throws IOException { + Files.createDirectories( propertiesFile.getParent() ); - propertiesFile.getParentFile().mkdirs(); - - OutputStream outStream = null; - try + try ( OutputStream outStream = Files.newOutputStream( propertiesFile ) ) { - outStream = new FileOutputStream( propertiesFile ); properties.store( outStream, message ); } - finally - { - IOUtils.closeQuietly( outStream ); - } } } diff --git a/pom.xml b/pom.xml index ba7ee152c0..ee6f725e51 100644 --- a/pom.xml +++ b/pom.xml @@ -94,9 +94,9 @@ under the License. maven-slf4j-wrapper maven-embedder maven-compat + apache-maven maven-wrapper maven-wrapper/maven-wrapper.pom - apache-maven