Formatting

This commit is contained in:
Jason van Zyl 2015-03-24 00:28:45 -04:00 committed by rfscholte
parent 2f07f99b51
commit ff3e1148b2
25 changed files with 1604 additions and 2097 deletions

View File

@ -1,3 +1,4 @@
.classpath .classpath
.project .project
.settings .settings
/target/

View File

@ -23,35 +23,30 @@ import java.net.URLClassLoader;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class BootstrapMainStarter public class BootstrapMainStarter {
{ public void start(String[] args, File mavenHome) throws Exception {
public void start( String[] args, File mavenHome ) File mavenJar = findLauncherJar(mavenHome);
throws Exception URLClassLoader contextClassLoader = new URLClassLoader(new URL[] {
{ mavenJar.toURI().toURL()
File mavenJar = findLauncherJar( mavenHome ); }, ClassLoader.getSystemClassLoader().getParent());
URLClassLoader contextClassLoader = Thread.currentThread().setContextClassLoader(contextClassLoader);
new URLClassLoader( new URL[] { mavenJar.toURI().toURL() }, ClassLoader.getSystemClassLoader().getParent() ); Class<?> mainClass = contextClassLoader.loadClass("org.codehaus.plexus.classworlds.launcher.Launcher");
Thread.currentThread().setContextClassLoader( contextClassLoader );
Class<?> mainClass = contextClassLoader.loadClass( "org.codehaus.plexus.classworlds.launcher.Launcher" );
System.setProperty( "maven.home", mavenHome.getAbsolutePath() ); System.setProperty("maven.home", mavenHome.getAbsolutePath());
System.setProperty( "classworlds.conf", new File( mavenHome, "/bin/m2.conf" ).getAbsolutePath() ); System.setProperty("classworlds.conf", new File(mavenHome, "/bin/m2.conf").getAbsolutePath());
Method mainMethod = mainClass.getMethod( "main", String[].class ); Method mainMethod = mainClass.getMethod("main", String[].class);
mainMethod.invoke( null, new Object[] { args } ); mainMethod.invoke(null, new Object[] {
} args
});
private File findLauncherJar( File mavenHome ) }
{
for ( File file : new File( mavenHome, "boot" ).listFiles() ) private File findLauncherJar(File mavenHome) {
{ for (File file : new File(mavenHome, "boot").listFiles()) {
if ( file.getName().matches( "plexus-classworlds-.*\\.jar" ) ) if (file.getName().matches("plexus-classworlds-.*\\.jar")) {
{ return file;
return file; }
}
}
throw new RuntimeException(
String.format( "Could not locate the Maven launcher JAR in Maven distribution '%s'.",
mavenHome ) );
} }
throw new RuntimeException(String.format("Could not locate the Maven launcher JAR in Maven distribution '%s'.", mavenHome));
}
} }

View File

@ -30,108 +30,85 @@ import java.net.URLConnection;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class DefaultDownloader public class DefaultDownloader implements Downloader {
implements Downloader private static final int PROGRESS_CHUNK = 20000;
{
private static final int PROGRESS_CHUNK = 20000;
private static final int BUFFER_SIZE = 10000; private static final int BUFFER_SIZE = 10000;
private final String applicationName; private final String applicationName;
private final String applicationVersion; private final String applicationVersion;
public DefaultDownloader( String applicationName, String applicationVersion ) public DefaultDownloader(String applicationName, String applicationVersion) {
{ this.applicationName = applicationName;
this.applicationName = applicationName; this.applicationVersion = applicationVersion;
this.applicationVersion = applicationVersion; configureProxyAuthentication();
configureProxyAuthentication(); }
private void configureProxyAuthentication() {
if (System.getProperty("http.proxyUser") != null) {
Authenticator.setDefault(new SystemPropertiesProxyAuthenticator());
} }
}
private void configureProxyAuthentication() public void download(URI address, File destination) throws Exception {
{ if (destination.exists()) {
if ( System.getProperty( "http.proxyUser" ) != null ) return;
{ }
Authenticator.setDefault( new SystemPropertiesProxyAuthenticator() ); destination.getParentFile().mkdirs();
downloadInternal(address, destination);
}
private void downloadInternal(URI address, File destination) throws Exception {
OutputStream out = null;
URLConnection conn;
InputStream in = null;
try {
URL url = address.toURL();
out = new BufferedOutputStream(new FileOutputStream(destination));
conn = url.openConnection();
final String userAgentValue = calculateUserAgent();
conn.setRequestProperty("User-Agent", userAgentValue);
in = conn.getInputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int numRead;
long progressCounter = 0;
while ((numRead = in.read(buffer)) != -1) {
progressCounter += numRead;
if (progressCounter / PROGRESS_CHUNK > 0) {
System.out.print(".");
progressCounter = progressCounter - PROGRESS_CHUNK;
} }
out.write(buffer, 0, numRead);
}
} finally {
System.out.println("");
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} }
}
public void download( URI address, File destination ) private String calculateUserAgent() {
throws Exception String appVersion = applicationVersion;
{
if ( destination.exists() )
{
return;
}
destination.getParentFile().mkdirs();
downloadInternal( address, destination ); String javaVendor = System.getProperty("java.vendor");
} String javaVersion = System.getProperty("java.version");
String javaVendorVersion = System.getProperty("java.vm.version");
private void downloadInternal( URI address, File destination ) String osName = System.getProperty("os.name");
throws Exception String osVersion = System.getProperty("os.version");
{ String osArch = System.getProperty("os.arch");
OutputStream out = null; return String.format("%s/%s (%s;%s;%s) (%s;%s;%s)", applicationName, appVersion, osName, osVersion, osArch, javaVendor, javaVersion, javaVendorVersion);
URLConnection conn; }
InputStream in = null;
try private static class SystemPropertiesProxyAuthenticator extends Authenticator {
{ @Override
URL url = address.toURL(); protected PasswordAuthentication getPasswordAuthentication() {
out = new BufferedOutputStream( new FileOutputStream( destination ) ); return new PasswordAuthentication(System.getProperty("http.proxyUser"), System.getProperty("http.proxyPassword", "").toCharArray());
conn = url.openConnection();
final String userAgentValue = calculateUserAgent();
conn.setRequestProperty( "User-Agent", userAgentValue );
in = conn.getInputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int numRead;
long progressCounter = 0;
while ( ( numRead = in.read( buffer ) ) != -1 )
{
progressCounter += numRead;
if ( progressCounter / PROGRESS_CHUNK > 0 )
{
System.out.print( "." );
progressCounter = progressCounter - PROGRESS_CHUNK;
}
out.write( buffer, 0, numRead );
}
}
finally
{
System.out.println( "" );
if ( in != null )
{
in.close();
}
if ( out != null )
{
out.close();
}
}
}
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 );
}
private static class SystemPropertiesProxyAuthenticator
extends Authenticator
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( System.getProperty( "http.proxyUser" ),
System.getProperty( "http.proxyPassword", "" ).toCharArray() );
}
} }
}
} }

View File

@ -21,8 +21,6 @@ import java.net.URI;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public interface Downloader public interface Downloader {
{ void download(URI address, File destination) throws Exception;
void download( URI address, File destination )
throws Exception;
} }

View File

@ -36,198 +36,155 @@ import java.util.zip.ZipFile;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class Installer public class Installer {
{ public static final String DEFAULT_DISTRIBUTION_PATH = "wrapper/dists";
public static final String DEFAULT_DISTRIBUTION_PATH = "wrapper/dists";
private final Downloader download; private final Downloader download;
private final PathAssembler pathAssembler; private final PathAssembler pathAssembler;
public Installer( Downloader download, PathAssembler pathAssembler ) public Installer(Downloader download, PathAssembler pathAssembler) {
{ this.download = download;
this.download = download; this.pathAssembler = pathAssembler;
this.pathAssembler = pathAssembler; }
public File createDist(WrapperConfiguration configuration) throws Exception {
URI distributionUrl = configuration.getDistribution();
boolean alwaysDownload = configuration.isAlwaysDownload();
boolean alwaysUnpack = configuration.isAlwaysUnpack();
PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution(configuration);
File localZipFile = localDistribution.getZipFile();
boolean downloaded = false;
if (alwaysDownload || !localZipFile.exists()) {
File tmpZipFile = new File(localZipFile.getParentFile(), localZipFile.getName() + ".part");
tmpZipFile.delete();
System.out.println("Downloading " + distributionUrl);
download.download(distributionUrl, tmpZipFile);
tmpZipFile.renameTo(localZipFile);
downloaded = true;
} }
public File createDist( WrapperConfiguration configuration ) File distDir = localDistribution.getDistributionDir();
throws Exception List<File> dirs = listDirs(distDir);
{
URI distributionUrl = configuration.getDistribution();
boolean alwaysDownload = configuration.isAlwaysDownload();
boolean alwaysUnpack = configuration.isAlwaysUnpack();
PathAssembler.LocalDistribution localDistribution = pathAssembler.getDistribution( configuration ); if (downloaded || alwaysUnpack || dirs.isEmpty()) {
for (File dir : dirs) {
System.out.println("Deleting directory " + dir.getAbsolutePath());
deleteDir(dir);
}
System.out.println("Unzipping " + localZipFile.getAbsolutePath() + " to " + distDir.getAbsolutePath());
unzip(localZipFile, distDir);
dirs = listDirs(distDir);
if (dirs.isEmpty()) {
throw new RuntimeException(String.format("Maven distribution '%s' does not contain any directories. Expected to find exactly 1 directory.", distributionUrl));
}
setExecutablePermissions(dirs.get(0));
}
if (dirs.size() != 1) {
throw new RuntimeException(String.format("Maven distribution '%s' contains too many directories. Expected to find exactly 1 directory.", distributionUrl));
}
return dirs.get(0);
}
File localZipFile = localDistribution.getZipFile(); private List<File> listDirs(File distDir) {
boolean downloaded = false; List<File> dirs = new ArrayList<File>();
if ( alwaysDownload || !localZipFile.exists() ) if (distDir.exists()) {
{ for (File file : distDir.listFiles()) {
File tmpZipFile = new File( localZipFile.getParentFile(), localZipFile.getName() + ".part" ); if (file.isDirectory()) {
tmpZipFile.delete(); dirs.add(file);
System.out.println( "Downloading " + distributionUrl );
download.download( distributionUrl, tmpZipFile );
tmpZipFile.renameTo( localZipFile );
downloaded = true;
} }
}
}
return dirs;
}
File distDir = localDistribution.getDistributionDir(); private void setExecutablePermissions(File mavenHome) {
List<File> dirs = listDirs( distDir ); if (isWindows()) {
return;
}
File mavenCommand = new File(mavenHome, "bin/mvn");
String errorMessage = null;
try {
ProcessBuilder pb = new ProcessBuilder("chmod", "755", mavenCommand.getCanonicalPath());
Process p = pb.start();
if (p.waitFor() == 0) {
System.out.println("Set executable permissions for: " + mavenCommand.getAbsolutePath());
} else {
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
Formatter stdout = new Formatter();
String line;
while ((line = is.readLine()) != null) {
stdout.format("%s%n", line);
}
errorMessage = stdout.toString();
}
} catch (IOException e) {
errorMessage = e.getMessage();
} catch (InterruptedException e) {
errorMessage = e.getMessage();
}
if (errorMessage != null) {
System.out.println("Could not set executable permissions for: " + mavenCommand.getAbsolutePath());
System.out.println("Please do this manually if you want to use maven.");
}
}
if ( downloaded || alwaysUnpack || dirs.isEmpty() ) private boolean isWindows() {
{ String osName = System.getProperty("os.name").toLowerCase(Locale.US);
for ( File dir : dirs ) if (osName.indexOf("windows") > -1) {
{ return true;
System.out.println( "Deleting directory " + dir.getAbsolutePath() ); }
deleteDir( dir ); return false;
} }
System.out.println( "Unzipping " + localZipFile.getAbsolutePath() + " to " + distDir.getAbsolutePath() );
unzip( localZipFile, distDir ); private boolean deleteDir(File dir) {
dirs = listDirs( distDir ); if (dir.isDirectory()) {
if ( dirs.isEmpty() ) String[] children = dir.list();
{ for (int i = 0; i < children.length; i++) {
throw new RuntimeException( boolean success = deleteDir(new File(dir, children[i]));
String.format( "Maven distribution '%s' does not contain any directories. Expected to find exactly 1 directory.", if (!success) {
distributionUrl ) ); return false;
}
setExecutablePermissions( dirs.get( 0 ) );
} }
if ( dirs.size() != 1 ) }
{
throw new RuntimeException(
String.format( "Maven distribution '%s' contains too many directories. Expected to find exactly 1 directory.",
distributionUrl ) );
}
return dirs.get( 0 );
} }
private List<File> listDirs( File distDir ) // The directory is now empty so delete it
{ return dir.delete();
List<File> dirs = new ArrayList<File>(); }
if ( distDir.exists() )
{ public void unzip(File zip, File dest) throws IOException {
for ( File file : distDir.listFiles() ) Enumeration entries;
{ ZipFile zipFile;
if ( file.isDirectory() )
{ zipFile = new ZipFile(zip);
dirs.add( file );
} entries = zipFile.entries();
}
} while (entries.hasMoreElements()) {
return dirs; ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) {
(new File(dest, entry.getName())).mkdirs();
continue;
}
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);
} }
private void setExecutablePermissions( File mavenHome ) in.close();
{ out.close();
if ( isWindows() ) }
{
return;
}
File mavenCommand = new File( mavenHome, "bin/mvn" );
String errorMessage = null;
try
{
ProcessBuilder pb = new ProcessBuilder( "chmod", "755", mavenCommand.getCanonicalPath() );
Process p = pb.start();
if ( p.waitFor() == 0 )
{
System.out.println( "Set executable permissions for: " + mavenCommand.getAbsolutePath() );
}
else
{
BufferedReader is = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
Formatter stdout = new Formatter();
String line;
while ( ( line = is.readLine() ) != null )
{
stdout.format( "%s%n", line );
}
errorMessage = stdout.toString();
}
}
catch ( IOException e )
{
errorMessage = e.getMessage();
}
catch ( InterruptedException e )
{
errorMessage = e.getMessage();
}
if ( errorMessage != null )
{
System.out.println( "Could not set executable permissions for: " + mavenCommand.getAbsolutePath() );
System.out.println( "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();
}
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;
}
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();
}
} }

View File

@ -29,124 +29,91 @@ import org.apache.maven.wrapper.cli.SystemPropertiesCommandLineConverter;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class MavenWrapperMain public class MavenWrapperMain {
{ public static final String DEFAULT_MAVEN_USER_HOME = System.getProperty("user.home") + "/.m2";
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"; 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 MAVEN_USER_HOME_ENV_KEY = "MAVEN_USER_HOME";
public static void main( String[] args ) public static void main(String[] args) throws Exception {
throws Exception File wrapperJar = wrapperJar();
{ File propertiesFile = wrapperProperties(wrapperJar);
File wrapperJar = wrapperJar(); File rootDir = rootDir(wrapperJar);
File propertiesFile = wrapperProperties( wrapperJar );
File rootDir = rootDir( wrapperJar );
Properties systemProperties = System.getProperties(); Properties systemProperties = System.getProperties();
systemProperties.putAll( parseSystemPropertiesFromArgs( args ) ); systemProperties.putAll(parseSystemPropertiesFromArgs(args));
addSystemProperties( rootDir ); addSystemProperties(rootDir);
WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out ); WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
wrapperExecutor.execute( args, new Installer( new DefaultDownloader( "mvnw", wrapperVersion() ), wrapperExecutor.execute(args, new Installer(new DefaultDownloader("mvnw", wrapperVersion()), new PathAssembler(mavenUserHome())), new BootstrapMainStarter());
new PathAssembler( mavenUserHome() ) ), new BootstrapMainStarter() ); }
private static Map<String, String> parseSystemPropertiesFromArgs(String[] args) {
SystemPropertiesCommandLineConverter converter = new SystemPropertiesCommandLineConverter();
CommandLineParser commandLineParser = new CommandLineParser();
converter.configure(commandLineParser);
commandLineParser.allowUnknownOptions();
return converter.convert(commandLineParser.parse(args));
}
private static void addSystemProperties(File rootDir) {
System.getProperties().putAll(SystemPropertiesHandler.getSystemProperties(new File(mavenUserHome(), "maven.properties")));
System.getProperties().putAll(SystemPropertiesHandler.getSystemProperties(new File(rootDir, "maven.properties")));
}
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")) {
private static Map<String, String> parseSystemPropertiesFromArgs( String[] args ) throw new RuntimeException(String.format("Cannot determine classpath for wrapper Jar from codebase '%s'.", location));
{
SystemPropertiesCommandLineConverter converter = new SystemPropertiesCommandLineConverter();
CommandLineParser commandLineParser = new CommandLineParser();
converter.configure( commandLineParser );
commandLineParser.allowUnknownOptions();
return converter.convert( commandLineParser.parse( args ) );
} }
return new File(location.getPath());
}
private static void addSystemProperties( File rootDir ) static String wrapperVersion() {
{ try {
System.getProperties().putAll( SystemPropertiesHandler.getSystemProperties( new File( mavenUserHome(), InputStream resourceAsStream = MavenWrapperMain.class.getResourceAsStream("/META-INF/maven/org.apache.maven/maven-wapper/pom.properties");
"maven.properties" ) ) ); if (resourceAsStream == null) {
System.getProperties().putAll( SystemPropertiesHandler.getSystemProperties( new File( rootDir, throw new RuntimeException("No maven properties found.");
"maven.properties" ) ) ); }
Properties mavenProperties = new Properties();
try {
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();
}
} catch (Exception e) {
throw new RuntimeException("Could not determine wrapper version.", e);
} }
}
private static File rootDir( File wrapperJar ) private static File mavenUserHome() {
{ String mavenUserHome = System.getProperty(MAVEN_USER_HOME_PROPERTY_KEY);
return wrapperJar.getParentFile().getParentFile().getParentFile(); if (mavenUserHome != null) {
} return new File(mavenUserHome);
} else if ((mavenUserHome = System.getenv(MAVEN_USER_HOME_ENV_KEY)) != null) {
private static File wrapperProperties( File wrapperJar ) return new File(mavenUserHome);
{ } else {
return new File( wrapperJar.getParent(), wrapperJar.getName().replaceFirst( "\\.jar$", ".properties" ) ); return new File(DEFAULT_MAVEN_USER_HOME);
}
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() );
}
static String wrapperVersion()
{
try
{
InputStream resourceAsStream =
MavenWrapperMain.class.getResourceAsStream( "/META-INF/maven/org.apache.maven/maven-wapper/pom.properties" );
if ( resourceAsStream == null )
{
throw new RuntimeException( "No maven properties found." );
}
Properties mavenProperties = new Properties();
try
{
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();
}
}
catch ( Exception e )
{
throw new RuntimeException( "Could not determine wrapper version.", e );
}
}
private static File mavenUserHome()
{
String mavenUserHome = System.getProperty( MAVEN_USER_HOME_PROPERTY_KEY );
if ( mavenUserHome != null )
{
return new File( mavenUserHome );
}
else if ( ( mavenUserHome = System.getenv( MAVEN_USER_HOME_ENV_KEY ) ) != null )
{
return new File( mavenUserHome );
}
else
{
return new File( DEFAULT_MAVEN_USER_HOME );
}
} }
}
} }

View File

@ -23,124 +23,97 @@ import java.security.MessageDigest;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class PathAssembler public class PathAssembler {
{ public static final String MAVEN_USER_HOME_STRING = "MAVEN_USER_HOME";
public static final String MAVEN_USER_HOME_STRING = "MAVEN_USER_HOME";
public static final String PROJECT_STRING = "PROJECT"; public static final String PROJECT_STRING = "PROJECT";
private File mavenUserHome; private File mavenUserHome;
public PathAssembler() public PathAssembler() {
{ }
public PathAssembler(File mavenUserHome) {
this.mavenUserHome = mavenUserHome;
}
/**
* Determines the local locations for the distribution to use given the supplied configuration.
*/
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);
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);
} }
}
public PathAssembler( File mavenUserHome ) private String removeExtension(String name) {
{ int p = name.lastIndexOf(".");
this.mavenUserHome = mavenUserHome; if (p < 0) {
return name;
}
return name.substring(0, p);
}
private String getDistName(URI distUrl) {
String path = distUrl.getPath();
int p = path.lastIndexOf("/");
if (p < 0) {
return path;
}
return path.substring(p + 1);
}
private File getBaseDir(String base) {
if (base.equals(MAVEN_USER_HOME_STRING)) {
return mavenUserHome;
} else if (base.equals(PROJECT_STRING)) {
return new File(System.getProperty("user.dir"));
} else {
throw new RuntimeException("Base: " + base + " is unknown");
}
}
public class LocalDistribution {
private final File distZip;
private final File distDir;
public LocalDistribution(File distDir, File distZip) {
this.distDir = distDir;
this.distZip = distZip;
} }
/** /**
* Determines the local locations for the distribution to use given the supplied configuration. * Returns the location to install the distribution into.
*/ */
public LocalDistribution getDistribution( WrapperConfiguration configuration ) public File getDistributionDir() {
{ return distDir;
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 );
return new LocalDistribution( distDir, distZip );
} }
private String rootDirName( String distName, WrapperConfiguration configuration ) /**
{ * Returns the location to install the distribution ZIP file to.
String urlHash = getMd5Hash( configuration.getDistribution().toString() ); */
return String.format( "%s/%s", distName, urlHash ); public File getZipFile() {
} return distZip;
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( "." );
if ( p < 0 )
{
return name;
}
return name.substring( 0, p );
}
private String getDistName( URI distUrl )
{
String path = distUrl.getPath();
int p = path.lastIndexOf( "/" );
if ( p < 0 )
{
return path;
}
return path.substring( p + 1 );
}
private File getBaseDir( String base )
{
if ( base.equals( MAVEN_USER_HOME_STRING ) )
{
return mavenUserHome;
}
else if ( base.equals( PROJECT_STRING ) )
{
return new File( System.getProperty( "user.dir" ) );
}
else
{
throw new RuntimeException( "Base: " + base + " is unknown" );
}
}
public class LocalDistribution
{
private final File distZip;
private final File distDir;
public LocalDistribution( File distDir, File distZip )
{
this.distDir = distDir;
this.distZip = distZip;
}
/**
* Returns the location to install the distribution into.
*/
public File getDistributionDir()
{
return distDir;
}
/**
* Returns the location to install the distribution ZIP file to.
*/
public File getZipFile()
{
return distZip;
}
} }
}
} }

View File

@ -27,47 +27,35 @@ import java.util.regex.Pattern;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class SystemPropertiesHandler public class SystemPropertiesHandler {
{
public static Map<String, String> getSystemProperties( File propertiesFile ) public static Map<String, String> getSystemProperties(File propertiesFile) {
{ Map<String, String> propertyMap = new HashMap<String, String>();
Map<String, String> propertyMap = new HashMap<String, String>(); if (!propertiesFile.isFile()) {
if ( !propertiesFile.isFile() ) return propertyMap;
{
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;
} }
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;
}
} }

View File

@ -17,93 +17,78 @@ package org.apache.maven.wrapper;
import java.net.URI; import java.net.URI;
public class WrapperConfiguration public class WrapperConfiguration {
{ public static final String ALWAYS_UNPACK_ENV = "MAVEN_WRAPPER_ALWAYS_UNPACK";
public static final String ALWAYS_UNPACK_ENV = "MAVEN_WRAPPER_ALWAYS_UNPACK";
public static final String ALWAYS_DOWNLOAD_ENV = "MAVEN_WRAPPER_ALWAYS_DOWNLOAD"; public static final String ALWAYS_DOWNLOAD_ENV = "MAVEN_WRAPPER_ALWAYS_DOWNLOAD";
private boolean alwaysUnpack = Boolean.parseBoolean( System.getenv( ALWAYS_UNPACK_ENV ) ); private boolean alwaysUnpack = Boolean.parseBoolean(System.getenv(ALWAYS_UNPACK_ENV));
private boolean alwaysDownload = Boolean.parseBoolean( System.getenv( ALWAYS_DOWNLOAD_ENV ) ); private boolean alwaysDownload = Boolean.parseBoolean(System.getenv(ALWAYS_DOWNLOAD_ENV));
private URI distribution; private URI distribution;
private String distributionBase = PathAssembler.MAVEN_USER_HOME_STRING; private String distributionBase = PathAssembler.MAVEN_USER_HOME_STRING;
private String distributionPath = Installer.DEFAULT_DISTRIBUTION_PATH; private String distributionPath = Installer.DEFAULT_DISTRIBUTION_PATH;
private String zipBase = PathAssembler.MAVEN_USER_HOME_STRING; private String zipBase = PathAssembler.MAVEN_USER_HOME_STRING;
private String zipPath = Installer.DEFAULT_DISTRIBUTION_PATH; private String zipPath = Installer.DEFAULT_DISTRIBUTION_PATH;
public boolean isAlwaysDownload() public boolean isAlwaysDownload() {
{ return alwaysDownload;
return alwaysDownload; }
}
public void setAlwaysDownload( boolean alwaysDownload ) public void setAlwaysDownload(boolean alwaysDownload) {
{ this.alwaysDownload = alwaysDownload;
this.alwaysDownload = alwaysDownload; }
}
public boolean isAlwaysUnpack() public boolean isAlwaysUnpack() {
{ return alwaysUnpack;
return alwaysUnpack; }
}
public void setAlwaysUnpack( boolean alwaysUnpack ) public void setAlwaysUnpack(boolean alwaysUnpack) {
{ this.alwaysUnpack = alwaysUnpack;
this.alwaysUnpack = alwaysUnpack; }
}
public URI getDistribution() public URI getDistribution() {
{ return distribution;
return distribution; }
}
public void setDistribution( URI distribution ) public void setDistribution(URI distribution) {
{ this.distribution = distribution;
this.distribution = distribution; }
}
public String getDistributionBase() public String getDistributionBase() {
{ return distributionBase;
return distributionBase; }
}
public void setDistributionBase( String distributionBase ) public void setDistributionBase(String distributionBase) {
{ this.distributionBase = distributionBase;
this.distributionBase = distributionBase; }
}
public String getDistributionPath() public String getDistributionPath() {
{ return distributionPath;
return distributionPath; }
}
public void setDistributionPath( String distributionPath ) public void setDistributionPath(String distributionPath) {
{ this.distributionPath = distributionPath;
this.distributionPath = distributionPath; }
}
public String getZipBase() public String getZipBase() {
{ return zipBase;
return zipBase; }
}
public void setZipBase( String zipBase ) public void setZipBase(String zipBase) {
{ this.zipBase = zipBase;
this.zipBase = zipBase; }
}
public String getZipPath() public String getZipPath() {
{ return zipPath;
return zipPath; }
}
public void setZipPath( String zipPath ) public void setZipPath(String zipPath) {
{ this.zipPath = zipPath;
this.zipPath = zipPath; }
}
} }

View File

@ -26,152 +26,118 @@ import java.util.Properties;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class WrapperExecutor public class WrapperExecutor {
{ public static final String DISTRIBUTION_URL_PROPERTY = "distributionUrl";
public static final String DISTRIBUTION_URL_PROPERTY = "distributionUrl";
public static final String DISTRIBUTION_BASE_PROPERTY = "distributionBase"; public static final String DISTRIBUTION_BASE_PROPERTY = "distributionBase";
public static final String ZIP_STORE_BASE_PROPERTY = "zipStoreBase"; public static final String ZIP_STORE_BASE_PROPERTY = "zipStoreBase";
public static final String DISTRIBUTION_PATH_PROPERTY = "distributionPath"; public static final String DISTRIBUTION_PATH_PROPERTY = "distributionPath";
public static final String ZIP_STORE_PATH_PROPERTY = "zipStorePath"; public static final String ZIP_STORE_PATH_PROPERTY = "zipStorePath";
private final Properties properties; private final Properties properties;
private final File propertiesFile; private final File propertiesFile;
private final Appendable warningOutput; private final Appendable warningOutput;
private final WrapperConfiguration config = new WrapperConfiguration(); private final WrapperConfiguration config = new WrapperConfiguration();
public static WrapperExecutor forProjectDirectory( File projectDir, Appendable warningOutput ) public static WrapperExecutor forProjectDirectory(File projectDir, Appendable warningOutput) {
{ return new WrapperExecutor(new File(projectDir, "maven/wrapper/maven-wrapper.properties"), new Properties(), warningOutput);
return new WrapperExecutor( new File( projectDir, "maven/wrapper/maven-wrapper.properties" ), new Properties(), }
warningOutput );
public static WrapperExecutor forWrapperPropertiesFile(File propertiesFile, Appendable warningOutput) {
if (!propertiesFile.exists()) {
throw new RuntimeException(String.format("Wrapper properties file '%s' does not exist.", propertiesFile));
}
return new WrapperExecutor(propertiesFile, new Properties(), warningOutput);
}
WrapperExecutor(File propertiesFile, Properties properties, Appendable warningOutput) {
this.properties = properties;
this.propertiesFile = propertiesFile;
this.warningOutput = warningOutput;
if (propertiesFile.exists()) {
try {
loadProperties(propertiesFile, properties);
config.setDistribution(prepareDistributionUri());
config.setDistributionBase(getProperty(DISTRIBUTION_BASE_PROPERTY, config.getDistributionBase()));
config.setDistributionPath(getProperty(DISTRIBUTION_PATH_PROPERTY, config.getDistributionPath()));
config.setZipBase(getProperty(ZIP_STORE_BASE_PROPERTY, config.getZipBase()));
config.setZipPath(getProperty(ZIP_STORE_PATH_PROPERTY, config.getZipPath()));
} catch (Exception e) {
throw new RuntimeException(String.format("Could not load wrapper properties from '%s'.", propertiesFile), e);
}
}
}
private URI prepareDistributionUri() throws URISyntaxException {
URI source = readDistroUrl();
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();
} else {
return source;
}
}
private URI readDistroUrl() throws URISyntaxException {
if (properties.getProperty(DISTRIBUTION_URL_PROPERTY) != null) {
return new URI(getProperty(DISTRIBUTION_URL_PROPERTY));
} }
public static WrapperExecutor forWrapperPropertiesFile( File propertiesFile, Appendable warningOutput ) reportMissingProperty(DISTRIBUTION_URL_PROPERTY);
{ return null; // previous line will fail
if ( !propertiesFile.exists() ) }
{
throw new RuntimeException( String.format( "Wrapper properties file '%s' does not exist.", propertiesFile ) );
}
return new WrapperExecutor( propertiesFile, new Properties(), warningOutput );
}
WrapperExecutor( File propertiesFile, Properties properties, Appendable warningOutput ) private static void loadProperties(File propertiesFile, Properties properties) throws IOException {
{ InputStream inStream = new FileInputStream(propertiesFile);
this.properties = properties; try {
this.propertiesFile = propertiesFile; properties.load(inStream);
this.warningOutput = warningOutput; } finally {
if ( propertiesFile.exists() ) inStream.close();
{
try
{
loadProperties( propertiesFile, properties );
config.setDistribution( prepareDistributionUri() );
config.setDistributionBase( getProperty( DISTRIBUTION_BASE_PROPERTY, config.getDistributionBase() ) );
config.setDistributionPath( getProperty( DISTRIBUTION_PATH_PROPERTY, config.getDistributionPath() ) );
config.setZipBase( getProperty( ZIP_STORE_BASE_PROPERTY, config.getZipBase() ) );
config.setZipPath( getProperty( ZIP_STORE_PATH_PROPERTY, config.getZipPath() ) );
}
catch ( Exception e )
{
throw new RuntimeException( String.format( "Could not load wrapper properties from '%s'.",
propertiesFile ), e );
}
}
} }
}
private URI prepareDistributionUri() /**
throws URISyntaxException * Returns the distribution which this wrapper will use. Returns null if no wrapper meta-data was found in the
{ * specified project directory.
URI source = readDistroUrl(); */
if ( source.getScheme() == null ) public URI getDistribution() {
{ return config.getDistribution();
// 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();
} /**
else * Returns the configuration for this wrapper.
{ */
return source; public WrapperConfiguration getConfiguration() {
} return config;
}
public void execute(String[] args, Installer install, BootstrapMainStarter bootstrapMainStarter) throws Exception {
File mavenHome = install.createDist(config);
bootstrapMainStarter.start(args, mavenHome);
}
private String getProperty(String propertyName) {
return getProperty(propertyName, null);
}
private String getProperty(String propertyName, String defaultValue) {
String value = properties.getProperty(propertyName);
if (value != null) {
return value;
} }
if (defaultValue != null) {
private URI readDistroUrl() return defaultValue;
throws URISyntaxException
{
if ( properties.getProperty( DISTRIBUTION_URL_PROPERTY ) != null )
{
return new URI( getProperty( DISTRIBUTION_URL_PROPERTY ) );
}
reportMissingProperty( DISTRIBUTION_URL_PROPERTY );
return null; // previous line will fail
} }
return reportMissingProperty(propertyName);
}
private static void loadProperties( File propertiesFile, Properties properties ) private String reportMissingProperty(String propertyName) {
throws IOException throw new RuntimeException(String.format("No value with key '%s' specified in wrapper properties file '%s'.", propertyName, propertiesFile));
{ }
InputStream inStream = new FileInputStream( propertiesFile );
try
{
properties.load( inStream );
}
finally
{
inStream.close();
}
}
/**
* Returns the distribution which this wrapper will use. Returns null if no wrapper meta-data was found in the
* specified project directory.
*/
public URI getDistribution()
{
return config.getDistribution();
}
/**
* Returns the configuration for this wrapper.
*/
public WrapperConfiguration getConfiguration()
{
return config;
}
public void execute( String[] args, Installer install, BootstrapMainStarter bootstrapMainStarter )
throws Exception
{
File mavenHome = install.createDist( config );
bootstrapMainStarter.start( args, mavenHome );
}
private String getProperty( String propertyName )
{
return getProperty( propertyName, null );
}
private String getProperty( String propertyName, String defaultValue )
{
String value = properties.getProperty( propertyName );
if ( value != null )
{
return value;
}
if ( defaultValue != null )
{
return defaultValue;
}
return reportMissingProperty( propertyName );
}
private String reportMissingProperty( String propertyName )
{
throw new RuntimeException( String.format( "No value with key '%s' specified in wrapper properties file '%s'.",
propertyName, propertiesFile ) );
}
} }

View File

@ -15,30 +15,22 @@
*/ */
package org.apache.maven.wrapper.cli; package org.apache.maven.wrapper.cli;
public abstract class AbstractCommandLineConverter<T> public abstract class AbstractCommandLineConverter<T> implements CommandLineConverter<T> {
implements CommandLineConverter<T> public T convert(Iterable<String> args) throws CommandLineArgumentException {
{ CommandLineParser parser = new CommandLineParser();
public T convert( Iterable<String> args ) configure(parser);
throws CommandLineArgumentException return convert(parser.parse(args));
{ }
CommandLineParser parser = new CommandLineParser();
configure( parser );
return convert( parser.parse( args ) );
}
public T convert( ParsedCommandLine args ) public T convert(ParsedCommandLine args) throws CommandLineArgumentException {
throws CommandLineArgumentException return convert(args, newInstance());
{ }
return convert( args, newInstance() );
}
public T convert( Iterable<String> args, T target ) public T convert(Iterable<String> args, T target) throws CommandLineArgumentException {
throws CommandLineArgumentException CommandLineParser parser = new CommandLineParser();
{ configure(parser);
CommandLineParser parser = new CommandLineParser(); return convert(parser.parse(args), target);
configure( parser ); }
return convert( parser.parse( args ), target );
}
protected abstract T newInstance(); protected abstract T newInstance();
} }

View File

@ -19,42 +19,32 @@ package org.apache.maven.wrapper.cli;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public abstract class AbstractPropertiesCommandLineConverter public abstract class AbstractPropertiesCommandLineConverter extends AbstractCommandLineConverter<Map<String, String>> {
extends AbstractCommandLineConverter<Map<String, String>> protected abstract String getPropertyOption();
{
protected abstract String getPropertyOption();
protected abstract String getPropertyOptionDetailed(); protected abstract String getPropertyOptionDetailed();
protected abstract String getPropertyOptionDescription(); protected abstract String getPropertyOptionDescription();
public void configure( CommandLineParser parser ) public void configure(CommandLineParser parser) {
{ CommandLineOption option = parser.option(getPropertyOption(), getPropertyOptionDetailed());
CommandLineOption option = parser.option( getPropertyOption(), getPropertyOptionDetailed() ); option = option.hasArguments();
option = option.hasArguments(); option.hasDescription(getPropertyOptionDescription());
option.hasDescription( getPropertyOptionDescription() ); }
}
protected Map<String, String> newInstance() {
protected Map<String, String> newInstance() return new HashMap<String, String>();
{ }
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()) {
public Map<String, String> convert( ParsedCommandLine options, Map<String, String> properties ) int pos = keyValueExpression.indexOf("=");
throws CommandLineArgumentException if (pos < 0) {
{ properties.put(keyValueExpression, "");
for ( String keyValueExpression : options.option( getPropertyOption() ).getValues() ) } else {
{ properties.put(keyValueExpression.substring(0, pos), keyValueExpression.substring(pos + 1));
int pos = keyValueExpression.indexOf( "=" ); }
if ( pos < 0 )
{
properties.put( keyValueExpression, "" );
}
else
{
properties.put( keyValueExpression.substring( 0, pos ), keyValueExpression.substring( pos + 1 ) );
}
}
return properties;
} }
return properties;
}
} }

View File

@ -20,16 +20,12 @@ package org.apache.maven.wrapper.cli;
* *
* @author Hans Dockter * @author Hans Dockter
*/ */
public class CommandLineArgumentException public class CommandLineArgumentException extends RuntimeException {
extends RuntimeException public CommandLineArgumentException(String message) {
{ super(message);
public CommandLineArgumentException( String message ) }
{
super( message );
}
public CommandLineArgumentException( String message, Throwable cause ) public CommandLineArgumentException(String message, Throwable cause) {
{ super(message, cause);
super( message, cause ); }
}
} }

View File

@ -18,19 +18,14 @@ package org.apache.maven.wrapper.cli;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public interface CommandLineConverter<T> public interface CommandLineConverter<T> {
{ T convert(Iterable<String> args) throws CommandLineArgumentException;
T convert( Iterable<String> args )
throws CommandLineArgumentException;
T convert( Iterable<String> args, T target ) T convert(Iterable<String> args, T target) throws CommandLineArgumentException;
throws CommandLineArgumentException;
T convert( ParsedCommandLine args ) T convert(ParsedCommandLine args) throws CommandLineArgumentException;
throws CommandLineArgumentException;
T convert( ParsedCommandLine args, T target ) T convert(ParsedCommandLine args, T target) throws CommandLineArgumentException;
throws CommandLineArgumentException;
void configure( CommandLineParser parser ); void configure(CommandLineParser parser);
} }

View File

@ -19,114 +19,94 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
public class CommandLineOption public class CommandLineOption {
{ private final Set<String> options = new HashSet<String>();
private final Set<String> options = new HashSet<String>();
private Class<?> argumentType = Void.TYPE; private Class<?> argumentType = Void.TYPE;
private String description; private String description;
private String subcommand; private String subcommand;
private String deprecationWarning; private String deprecationWarning;
private boolean incubating; private boolean incubating;
public CommandLineOption( Iterable<String> options ) public CommandLineOption(Iterable<String> options) {
{ for (String option : options) {
for ( String option : options ) this.options.add(option);
{
this.options.add( option );
}
} }
}
public Set<String> getOptions() public Set<String> getOptions() {
{ return options;
return options; }
}
public CommandLineOption hasArgument() public CommandLineOption hasArgument() {
{ argumentType = String.class;
argumentType = String.class; return this;
return this; }
}
public CommandLineOption hasArguments() public CommandLineOption hasArguments() {
{ argumentType = List.class;
argumentType = List.class; return this;
return this; }
}
public String getSubcommand() public String getSubcommand() {
{ return subcommand;
return subcommand; }
}
public CommandLineOption mapsToSubcommand( String command ) public CommandLineOption mapsToSubcommand(String command) {
{ this.subcommand = command;
this.subcommand = command; return this;
return this; }
}
public String getDescription() public String getDescription() {
{ StringBuilder result = new StringBuilder();
StringBuilder result = new StringBuilder(); if (description != null) {
if ( description != null ) result.append(description);
{
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();
} }
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 ) public CommandLineOption hasDescription(String description) {
{ this.description = description;
this.description = description; return this;
return this; }
}
public boolean getAllowsArguments() public boolean getAllowsArguments() {
{ return argumentType != Void.TYPE;
return argumentType != Void.TYPE; }
}
public boolean getAllowsMultipleArguments() public boolean getAllowsMultipleArguments() {
{ return argumentType == List.class;
return argumentType == List.class; }
}
public CommandLineOption deprecated( String deprecationWarning ) public CommandLineOption deprecated(String deprecationWarning) {
{ this.deprecationWarning = deprecationWarning;
this.deprecationWarning = deprecationWarning; return this;
return this; }
}
public CommandLineOption incubating() public CommandLineOption incubating() {
{ incubating = true;
incubating = true; return this;
return this; }
}
public String getDeprecationWarning() public String getDeprecationWarning() {
{ return deprecationWarning;
return deprecationWarning; }
}
} }

View File

@ -23,111 +23,93 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
public class ParsedCommandLine public class ParsedCommandLine {
{ private final Map<String, ParsedCommandLineOption> optionsByString = new HashMap<String, ParsedCommandLineOption>();
private final Map<String, ParsedCommandLineOption> optionsByString = new HashMap<String, ParsedCommandLineOption>();
private final Set<String> presentOptions = new HashSet<String>(); private final Set<String> presentOptions = new HashSet<String>();
private final List<String> extraArguments = new ArrayList<String>(); private final List<String> extraArguments = new ArrayList<String>();
ParsedCommandLine( Iterable<CommandLineOption> options ) ParsedCommandLine(Iterable<CommandLineOption> options) {
{ for (CommandLineOption option : options) {
for ( CommandLineOption option : options ) ParsedCommandLineOption parsedOption = new ParsedCommandLineOption();
{ for (String optionStr : option.getOptions()) {
ParsedCommandLineOption parsedOption = new ParsedCommandLineOption(); optionsByString.put(optionStr, parsedOption);
for ( String optionStr : option.getOptions() ) }
{
optionsByString.put( optionStr, parsedOption );
}
}
} }
}
@Override @Override
public String toString() public String toString() {
{ return String.format("options: %s, extraArguments: %s", quoteAndJoin(presentOptions), quoteAndJoin(extraArguments));
return String.format( "options: %s, extraArguments: %s", quoteAndJoin( presentOptions ), }
quoteAndJoin( extraArguments ) );
}
private String quoteAndJoin( Iterable<String> strings ) private String quoteAndJoin(Iterable<String> strings) {
{ StringBuilder output = new StringBuilder();
StringBuilder output = new StringBuilder(); boolean isFirst = true;
boolean isFirst = true; for (String string : strings) {
for ( String string : strings ) if (!isFirst) {
{ output.append(", ");
if ( !isFirst ) }
{ output.append("'");
output.append( ", " ); output.append(string);
} output.append("'");
output.append( "'" ); isFirst = false;
output.append( string );
output.append( "'" );
isFirst = false;
}
return output.toString();
} }
return output.toString();
}
/** /**
* Returns true if the given option is present in this command-line. * Returns true if the given option is present in this command-line.
* *
* @param option The option, without the '-' or '--' prefix. * @param option The option, without the '-' or '--' prefix.
* @return true if the option is present. * @return true if the option is present.
*/ */
public boolean hasOption( String option ) public boolean hasOption(String option) {
{ option(option);
option( option ); return presentOptions.contains(option);
return presentOptions.contains( option ); }
}
/** /**
* See also {@link #hasOption}. * See also {@link #hasOption}.
* *
* @param logLevelOptions the options to check * @param logLevelOptions the options to check
* @return true if any of the passed options is present * @return true if any of the passed options is present
*/ */
public boolean hasAnyOption( Collection<String> logLevelOptions ) public boolean hasAnyOption(Collection<String> logLevelOptions) {
{ for (String option : logLevelOptions) {
for ( String option : logLevelOptions ) if (hasOption(option)) {
{ return true;
if ( hasOption( option ) ) }
{
return true;
}
}
return false;
} }
return false;
}
/** /**
* Returns the value of the given option. * Returns the value of the given option.
* *
* @param option The option, without the '-' or '--' prefix. * @param option The option, without the '-' or '--' prefix.
* @return The option. never returns null. * @return The option. never returns null.
*/ */
public ParsedCommandLineOption option( String option ) public ParsedCommandLineOption option(String option) {
{ ParsedCommandLineOption parsedOption = optionsByString.get(option);
ParsedCommandLineOption parsedOption = optionsByString.get( option ); if (parsedOption == null) {
if ( parsedOption == null ) throw new IllegalArgumentException(String.format("Option '%s' not defined.", option));
{
throw new IllegalArgumentException( String.format( "Option '%s' not defined.", option ) );
}
return parsedOption;
} }
return parsedOption;
}
public List<String> getExtraArguments() public List<String> getExtraArguments() {
{ return extraArguments;
return extraArguments; }
}
void addExtraValue( String value ) void addExtraValue(String value) {
{ extraArguments.add(value);
extraArguments.add( value ); }
}
ParsedCommandLineOption addOption( String optionStr, CommandLineOption option ) ParsedCommandLineOption addOption(String optionStr, CommandLineOption option) {
{ ParsedCommandLineOption parsedOption = optionsByString.get(optionStr);
ParsedCommandLineOption parsedOption = optionsByString.get( optionStr ); presentOptions.addAll(option.getOptions());
presentOptions.addAll( option.getOptions() ); return parsedOption;
return parsedOption; }
}
} }

View File

@ -18,35 +18,28 @@ package org.apache.maven.wrapper.cli;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ParsedCommandLineOption public class ParsedCommandLineOption {
{ private final List<String> values = new ArrayList<String>();
private final List<String> values = new ArrayList<String>();
public String getValue() public String getValue() {
{ if (!hasValue()) {
if ( !hasValue() ) throw new IllegalStateException("Option does not have any value.");
{
throw new IllegalStateException( "Option does not have any value." );
}
if ( values.size() > 1 )
{
throw new IllegalStateException( "Option has multiple values." );
}
return values.get( 0 );
} }
if (values.size() > 1) {
throw new IllegalStateException("Option has multiple values.");
}
return values.get(0);
}
public List<String> getValues() public List<String> getValues() {
{ return values;
return values; }
}
public void addArgument( String argument ) public void addArgument(String argument) {
{ values.add(argument);
values.add( argument ); }
}
public boolean hasValue() public boolean hasValue() {
{ return !values.isEmpty();
return !values.isEmpty(); }
}
} }

View File

@ -16,25 +16,20 @@
package org.apache.maven.wrapper.cli; package org.apache.maven.wrapper.cli;
public class ProjectPropertiesCommandLineConverter public class ProjectPropertiesCommandLineConverter extends AbstractPropertiesCommandLineConverter {
extends AbstractPropertiesCommandLineConverter
{
@Override @Override
protected String getPropertyOption() protected String getPropertyOption() {
{ return "P";
return "P"; }
}
@Override @Override
protected String getPropertyOptionDetailed() protected String getPropertyOptionDetailed() {
{ return "project-prop";
return "project-prop"; }
}
@Override @Override
protected String getPropertyOptionDescription() protected String getPropertyOptionDescription() {
{ return "Set project property for the build script (e.g. -Pmyprop=myvalue).";
return "Set project property for the build script (e.g. -Pmyprop=myvalue)."; }
}
} }

View File

@ -15,25 +15,20 @@
*/ */
package org.apache.maven.wrapper.cli; package org.apache.maven.wrapper.cli;
public class SystemPropertiesCommandLineConverter public class SystemPropertiesCommandLineConverter extends AbstractPropertiesCommandLineConverter {
extends AbstractPropertiesCommandLineConverter
{
@Override @Override
protected String getPropertyOption() protected String getPropertyOption() {
{ return "D";
return "D"; }
}
@Override @Override
protected String getPropertyOptionDetailed() protected String getPropertyOptionDetailed() {
{ return "system-prop";
return "system-prop"; }
}
@Override @Override
protected String getPropertyOptionDescription() protected String getPropertyOptionDescription() {
{ return "Set system property of the JVM (e.g. -Dmyprop=myvalue).";
return "Set system property of the JVM (e.g. -Dmyprop=myvalue)."; }
}
} }

View File

@ -9,41 +9,36 @@ import org.apache.commons.io.FileUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class DownloaderTest public class DownloaderTest {
{
private DefaultDownloader download; private DefaultDownloader download;
private File testDir; private File testDir;
private File downloadFile; private File downloadFile;
private File rootDir; private File rootDir;
private URI sourceRoot; private URI sourceRoot;
private File remoteFile; private File remoteFile;
@Before @Before
public void setUp() public void setUp() throws Exception {
throws Exception download = new DefaultDownloader("mvnw", "aVersion");
{ testDir = new File("target/test-files/DownloadTest");
download = new DefaultDownloader( "mvnw", "aVersion" ); rootDir = new File(testDir, "root");
testDir = new File( "target/test-files/DownloadTest" ); downloadFile = new File(rootDir, "file");
rootDir = new File( testDir, "root" ); remoteFile = new File(testDir, "remoteFile");
downloadFile = new File( rootDir, "file" ); FileUtils.write(remoteFile, "sometext");
remoteFile = new File( testDir, "remoteFile" ); sourceRoot = remoteFile.toURI();
FileUtils.write( remoteFile, "sometext" ); }
sourceRoot = remoteFile.toURI();
}
@Test @Test
public void testDownload() public void testDownload() throws Exception {
throws Exception assert !downloadFile.exists();
{ download.download(sourceRoot, downloadFile);
assert !downloadFile.exists(); assert downloadFile.exists();
download.download( sourceRoot, downloadFile ); assertEquals("sometext", FileUtils.readFileToString(downloadFile));
assert downloadFile.exists(); }
assertEquals( "sometext", FileUtils.readFileToString( downloadFile ) );
}
} }

View File

@ -16,181 +16,167 @@ import org.junit.Test;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class InstallerTest public class InstallerTest {
{ private File testDir = new File("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis());
private File testDir = new File( "target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis() );
private Installer install; private Installer install;
private Downloader downloadMock; private Downloader downloadMock;
private PathAssembler pathAssemblerMock; private PathAssembler pathAssemblerMock;
private boolean downloadCalled; private boolean downloadCalled;
private File zip; private File zip;
private File distributionDir; private File distributionDir;
private File zipStore; private File zipStore;
private File mavenHomeDir; private File mavenHomeDir;
private File zipDestination; private File zipDestination;
private WrapperConfiguration configuration = new WrapperConfiguration(); private WrapperConfiguration configuration = new WrapperConfiguration();
private Downloader download; private Downloader download;
private PathAssembler pathAssembler; private PathAssembler pathAssembler;
private PathAssembler.LocalDistribution localDistribution; private PathAssembler.LocalDistribution localDistribution;
@Before @Before
public void setup() public void setup() throws Exception {
throws Exception
{
testDir.mkdirs(); testDir.mkdirs();
downloadCalled = false; downloadCalled = false;
configuration.setZipBase( PathAssembler.PROJECT_STRING ); configuration.setZipBase(PathAssembler.PROJECT_STRING);
configuration.setZipPath( "someZipPath" ); configuration.setZipPath("someZipPath");
configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING ); configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
configuration.setDistributionPath( "someDistPath" ); configuration.setDistributionPath("someDistPath");
configuration.setDistribution( new URI( "http://server/maven-0.9.zip" ) ); configuration.setDistribution(new URI("http://server/maven-0.9.zip"));
configuration.setAlwaysDownload( false ); configuration.setAlwaysDownload(false);
configuration.setAlwaysUnpack( false ); configuration.setAlwaysUnpack(false);
distributionDir = new File( testDir, "someDistPath" ); distributionDir = new File(testDir, "someDistPath");
mavenHomeDir = new File( distributionDir, "maven-0.9" ); mavenHomeDir = new File(distributionDir, "maven-0.9");
zipStore = new File( testDir, "zips" ); zipStore = new File(testDir, "zips");
zipDestination = new File( zipStore, "maven-0.9.zip" ); zipDestination = new File(zipStore, "maven-0.9.zip");
download = mock( Downloader.class ); download = mock(Downloader.class);
pathAssembler = mock( PathAssembler.class ); pathAssembler = mock(PathAssembler.class);
localDistribution = mock( PathAssembler.LocalDistribution.class ); localDistribution = mock(PathAssembler.LocalDistribution.class);
when( localDistribution.getZipFile() ).thenReturn( zipDestination ); when(localDistribution.getZipFile()).thenReturn(zipDestination);
when( localDistribution.getDistributionDir() ).thenReturn( distributionDir ); when(localDistribution.getDistributionDir()).thenReturn(distributionDir);
when( pathAssembler.getDistribution( configuration ) ).thenReturn( localDistribution ); when(pathAssembler.getDistribution(configuration)).thenReturn(localDistribution);
install = new Installer( download, pathAssembler ); install = new Installer(download, pathAssembler);
} }
private void createTestZip( File zipDestination ) private void createTestZip(File zipDestination) throws Exception {
throws Exception File explodedZipDir = new File(testDir, "explodedZip");
{ explodedZipDir.mkdirs();
File explodedZipDir = new File( testDir, "explodedZip" ); zipDestination.getParentFile().mkdirs();
explodedZipDir.mkdirs(); File mavenScript = new File(explodedZipDir, "maven-0.9/bin/mvn");
zipDestination.getParentFile().mkdirs(); mavenScript.getParentFile().mkdirs();
File mavenScript = new File( explodedZipDir, "maven-0.9/bin/mvn" ); FileUtils.write(mavenScript, "something");
mavenScript.getParentFile().mkdirs();
FileUtils.write( mavenScript, "something" );
zipTo( explodedZipDir, zipDestination ); zipTo(explodedZipDir, zipDestination);
} }
public void testCreateDist() public void testCreateDist() throws Exception {
throws Exception File homeDir = install.createDist(configuration);
{
File homeDir = install.createDist( configuration );
Assert.assertEquals( mavenHomeDir, homeDir ); Assert.assertEquals(mavenHomeDir, homeDir);
Assert.assertTrue( homeDir.isDirectory() ); Assert.assertTrue(homeDir.isDirectory());
Assert.assertTrue( new File( homeDir, "bin/mvn" ).exists() ); Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
Assert.assertTrue( zipDestination.exists() ); Assert.assertTrue(zipDestination.exists());
Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) ); Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() ); Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
Assert.assertEquals( zipDestination, localDistribution.getZipFile() ); Assert.assertEquals(zipDestination, localDistribution.getZipFile());
// download.download(new URI("http://some/test"), distributionDir); // download.download(new URI("http://some/test"), distributionDir);
// verify(download).download(new URI("http://some/test"), distributionDir); // verify(download).download(new URI("http://some/test"), distributionDir);
} }
@Test @Test
public void testCreateDistWithExistingDistribution() public void testCreateDistWithExistingDistribution() throws Exception {
throws Exception
{
FileUtils.touch( zipDestination ); FileUtils.touch(zipDestination);
mavenHomeDir.mkdirs(); mavenHomeDir.mkdirs();
File someFile = new File( mavenHomeDir, "some-file" ); File someFile = new File(mavenHomeDir, "some-file");
FileUtils.touch( someFile ); FileUtils.touch(someFile);
File homeDir = install.createDist( configuration ); File homeDir = install.createDist(configuration);
Assert.assertEquals( mavenHomeDir, homeDir ); Assert.assertEquals(mavenHomeDir, homeDir);
Assert.assertTrue( mavenHomeDir.isDirectory() ); Assert.assertTrue(mavenHomeDir.isDirectory());
Assert.assertTrue( new File( homeDir, "some-file" ).exists() ); Assert.assertTrue(new File(homeDir, "some-file").exists());
Assert.assertTrue( zipDestination.exists() ); Assert.assertTrue(zipDestination.exists());
Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) ); Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() ); Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
Assert.assertEquals( zipDestination, localDistribution.getZipFile() ); Assert.assertEquals(zipDestination, localDistribution.getZipFile());
} }
@Test @Test
public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue() public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue() throws Exception {
throws Exception
{
createTestZip( zipDestination ); createTestZip(zipDestination);
mavenHomeDir.mkdirs(); mavenHomeDir.mkdirs();
File garbage = new File( mavenHomeDir, "garbage" ); File garbage = new File(mavenHomeDir, "garbage");
FileUtils.touch( garbage ); FileUtils.touch(garbage);
configuration.setAlwaysUnpack( true ); configuration.setAlwaysUnpack(true);
File homeDir = install.createDist( configuration ); File homeDir = install.createDist(configuration);
Assert.assertEquals( mavenHomeDir, homeDir ); Assert.assertEquals(mavenHomeDir, homeDir);
Assert.assertTrue( mavenHomeDir.isDirectory() ); Assert.assertTrue(mavenHomeDir.isDirectory());
Assert.assertFalse( new File( homeDir, "garbage" ).exists() ); Assert.assertFalse(new File(homeDir, "garbage").exists());
Assert.assertTrue( zipDestination.exists() ); Assert.assertTrue(zipDestination.exists());
Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) ); Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() ); Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
Assert.assertEquals( zipDestination, localDistribution.getZipFile() ); Assert.assertEquals(zipDestination, localDistribution.getZipFile());
} }
@Test @Test
public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue() public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue() throws Exception {
throws Exception
{
createTestZip( zipDestination ); createTestZip(zipDestination);
File garbage = new File( mavenHomeDir, "garbage" ); File garbage = new File(mavenHomeDir, "garbage");
FileUtils.touch( garbage ); FileUtils.touch(garbage);
configuration.setAlwaysUnpack( true ); configuration.setAlwaysUnpack(true);
File homeDir = install.createDist( configuration ); File homeDir = install.createDist(configuration);
Assert.assertEquals( mavenHomeDir, homeDir ); Assert.assertEquals(mavenHomeDir, homeDir);
Assert.assertTrue( mavenHomeDir.isDirectory() ); Assert.assertTrue(mavenHomeDir.isDirectory());
Assert.assertTrue( new File( homeDir, "bin/mvn" ).exists() ); Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
Assert.assertFalse( new File( homeDir, "garbage" ).exists() ); Assert.assertFalse(new File(homeDir, "garbage").exists());
Assert.assertTrue( zipDestination.exists() ); Assert.assertTrue(zipDestination.exists());
Assert.assertEquals( localDistribution, pathAssembler.getDistribution( configuration ) ); Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration));
Assert.assertEquals( distributionDir, localDistribution.getDistributionDir() ); Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
Assert.assertEquals( zipDestination, localDistribution.getZipFile() ); Assert.assertEquals(zipDestination, localDistribution.getZipFile());
// download.download(new URI("http://some/test"), distributionDir); // download.download(new URI("http://some/test"), distributionDir);
// verify(download).download(new URI("http://some/test"), distributionDir); // verify(download).download(new URI("http://some/test"), distributionDir);
} }
public void zipTo( File directoryToZip, File zipFile ) public void zipTo(File directoryToZip, File zipFile) {
{ Zip zip = new Zip();
Zip zip = new Zip(); zip.setBasedir(directoryToZip);
zip.setBasedir( directoryToZip ); zip.setDestFile(zipFile);
zip.setDestFile( zipFile ); zip.setProject(new Project());
zip.setProject( new Project() );
Zip.WhenEmpty whenEmpty = new Zip.WhenEmpty(); Zip.WhenEmpty whenEmpty = new Zip.WhenEmpty();
whenEmpty.setValue( "create" ); whenEmpty.setValue("create");
zip.setWhenempty( whenEmpty ); zip.setWhenempty(whenEmpty);
zip.execute(); zip.execute();
} }
} }

View File

@ -33,113 +33,91 @@ import org.junit.Test;
/** /**
* @author Hans Dockter * @author Hans Dockter
*/ */
public class PathAssemblerTest public class PathAssemblerTest {
{ public static final String TEST_MAVEN_USER_HOME = "someUserHome";
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(new File(TEST_MAVEN_USER_HOME));
final WrapperConfiguration configuration = new WrapperConfiguration(); final WrapperConfiguration configuration = new WrapperConfiguration();
@Before @Before
public void setup() public void setup() {
{ configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING ); configuration.setDistributionPath("somePath");
configuration.setDistributionPath( "somePath" ); configuration.setZipBase(PathAssembler.MAVEN_USER_HOME_STRING);
configuration.setZipBase( PathAssembler.MAVEN_USER_HOME_STRING ); configuration.setZipPath("somePath");
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());
} }
}
@Test @Test
public void distributionDirWithMavenUserHomeBase() public void distZipWithMavenUserHomeBase() throws Exception {
throws Exception configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
{
configuration.setDistribution( new URI( "http://server/dist/maven-0.9-bin.zip" ) );
File distributionDir = pathAssembler.getDistribution( configuration ).getDistributionDir(); File dist = pathAssembler.getDistribution(configuration).getZipFile();
assertThat( distributionDir.getName(), matchesRegexp( "[a-z0-9]+" ) ); assertThat(dist.getName(), equalTo("maven-1.0.zip"));
assertThat( distributionDir.getParentFile(), equalTo( file( TEST_MAVEN_USER_HOME + "/somePath/maven-0.9-bin" ) ) ); assertThat(dist.getParentFile().getName(), matchesRegexp("[a-z0-9]+"));
} assertThat(dist.getParentFile().getParentFile(), equalTo(file(TEST_MAVEN_USER_HOME + "/somePath/maven-1.0")));
}
@Test @Test
public void distributionDirWithProjectBase() public void distZipWithProjectBase() throws Exception {
throws Exception configuration.setZipBase(PathAssembler.PROJECT_STRING);
{ configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
configuration.setDistributionBase( PathAssembler.PROJECT_STRING );
configuration.setDistribution( new URI( "http://server/dist/maven-0.9-bin.zip" ) );
File distributionDir = pathAssembler.getDistribution( configuration ).getDistributionDir(); File dist = pathAssembler.getDistribution(configuration).getZipFile();
assertThat( distributionDir.getName(), matchesRegexp( "[a-z0-9]+" ) ); assertThat(dist.getName(), equalTo("maven-1.0.zip"));
assertThat( distributionDir.getParentFile(), equalTo( file( currentDirPath() + "/somePath/maven-0.9-bin" ) ) ); assertThat(dist.getParentFile().getName(), matchesRegexp("[a-z0-9]+"));
} assertThat(dist.getParentFile().getParentFile(), equalTo(file(currentDirPath() + "/somePath/maven-1.0")));
}
@Test private File file(String path) {
public void distributionDirWithUnknownBase() return new File(path);
throws Exception }
{
configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
configuration.setDistributionBase( "unknownBase" );
try private String currentDirPath() {
{ return System.getProperty("user.dir");
pathAssembler.getDistribution( configuration ); }
fail();
}
catch ( RuntimeException e )
{
assertEquals( "Base: unknownBase is unknown", e.getMessage() );
}
}
@Test public static <T extends CharSequence> Matcher<T> matchesRegexp(final String pattern) {
public void distZipWithMavenUserHomeBase() return new BaseMatcher<T>() {
throws Exception public boolean matches(Object o) {
{ return Pattern.compile(pattern).matcher((CharSequence) o).matches();
configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) ); }
File dist = pathAssembler.getDistribution( configuration ).getZipFile(); public void describeTo(Description description) {
assertThat( dist.getName(), equalTo( "maven-1.0.zip" ) ); description.appendText("a CharSequence that matches regexp ").appendValue(pattern);
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 );
}
};
}
} }

View File

@ -13,48 +13,40 @@ import org.apache.commons.io.IOUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
public class SystemPropertiesHandlerTest public class SystemPropertiesHandlerTest {
{
private File tmpDir = new File( "target/test-files/SystemPropertiesHandlerTest" ); private File tmpDir = new File("target/test-files/SystemPropertiesHandlerTest");
@Before @Before
public void setupTempDir() public void setupTempDir() {
{ tmpDir.mkdirs();
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);
} }
@Test Map<String, String> expected = new HashMap<String, String>();
public void testParsePropertiesFile() expected.put("c", "d");
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; assertThat(SystemPropertiesHandler.getSystemProperties(propFile), equalTo(expected));
try }
{
fos = new FileOutputStream( propFile );
props.store( fos, "" );
}
finally
{
IOUtils.closeQuietly( fos );
}
Map<String, String> expected = new HashMap<String, String>(); @Test
expected.put( "c", "d" ); public void ifNoPropertyFileExistShouldReturnEmptyMap() {
Map<String, String> expected = new HashMap<String, String>();
assertThat( SystemPropertiesHandler.getSystemProperties( propFile ), equalTo( expected ) ); assertThat(SystemPropertiesHandler.getSystemProperties(new File(tmpDir, "unknown")), equalTo(expected));
} }
@Test
public void ifNoPropertyFileExistShouldReturnEmptyMap()
{
Map<String, String> expected = new HashMap<String, String>();
assertThat( SystemPropertiesHandler.getSystemProperties( new File( tmpDir, "unknown" ) ), equalTo( expected ) );
}
} }

View File

@ -15,178 +15,152 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
public class WrapperExecutorTest public class WrapperExecutorTest {
{ private final Installer install;
private final Installer install;
private final BootstrapMainStarter start; private final BootstrapMainStarter start;
private File propertiesFile; private File propertiesFile;
private Properties properties = new Properties(); private Properties properties = new Properties();
private File testDir = new File( "target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis() ); private File testDir = new File("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis());
private File mockInstallDir = new File( testDir, "mock-dir" ); private File mockInstallDir = new File(testDir, "mock-dir");
public WrapperExecutorTest() public WrapperExecutorTest() throws Exception {
throws Exception install = mock(Installer.class);
{ when(install.createDist(Mockito.any(WrapperConfiguration.class))).thenReturn(mockInstallDir);
install = mock( Installer.class ); start = mock(BootstrapMainStarter.class);
when( install.createDist( Mockito.any( WrapperConfiguration.class ) ) ).thenReturn( mockInstallDir );
start = mock( BootstrapMainStarter.class );
testDir.mkdirs(); testDir.mkdirs();
propertiesFile = new File( testDir, "maven/wrapper/maven-wrapper.properties" ); propertiesFile = new File(testDir, "maven/wrapper/maven-wrapper.properties");
properties.put( "distributionUrl", "http://server/test/maven.zip" ); properties.put("distributionUrl", "http://server/test/maven.zip");
properties.put( "distributionBase", "testDistBase" ); properties.put("distributionBase", "testDistBase");
properties.put( "distributionPath", "testDistPath" ); properties.put("distributionPath", "testDistPath");
properties.put( "zipStoreBase", "testZipBase" ); properties.put("zipStoreBase", "testZipBase");
properties.put( "zipStorePath", "testZipPath" ); properties.put("zipStorePath", "testZipPath");
writePropertiesFile( properties, propertiesFile, "header" ); 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());
} }
@Test }
public void loadWrapperMetadataFromFile()
throws Exception
{
WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out );
Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); @Test
Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); public void failWhenPropertiesFileDoesNotExist() {
Assert.assertEquals( "testDistBase", wrapper.getConfiguration().getDistributionBase() ); propertiesFile = new File(testDir, "unknown.properties");
Assert.assertEquals( "testDistPath", wrapper.getConfiguration().getDistributionPath() );
Assert.assertEquals( "testZipBase", wrapper.getConfiguration().getZipBase() ); try {
Assert.assertEquals( "testZipPath", wrapper.getConfiguration().getZipPath() ); WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
Assert.fail("Expected RuntimeException");
} catch (RuntimeException e) {
Assert.assertEquals("Wrapper properties file '" + propertiesFile + "' does not exist.", e.getMessage());
} }
}
@Test @Test
public void loadWrapperMetadataFromDirectory() public void testRelativeDistUrl() throws Exception {
throws Exception
{
WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir, System.out );
Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getDistribution() ); properties = new Properties();
Assert.assertEquals( new URI( "http://server/test/maven.zip" ), wrapper.getConfiguration().getDistribution() ); properties.put("distributionUrl", "some/relative/url/to/bin.zip");
Assert.assertEquals( "testDistBase", wrapper.getConfiguration().getDistributionBase() ); writePropertiesFile(properties, propertiesFile, "header");
Assert.assertEquals( "testDistPath", wrapper.getConfiguration().getDistributionPath() );
Assert.assertEquals( "testZipBase", wrapper.getConfiguration().getZipBase() ); WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
Assert.assertEquals( "testZipPath", wrapper.getConfiguration().getZipPath() ); Assert.assertNotEquals("some/relative/url/to/bin.zip", wrapper.getDistribution().getSchemeSpecificPart());
} Assert.assertTrue(wrapper.getDistribution().getSchemeSpecificPart().endsWith("some/relative/url/to/bin.zip"));
}
@Test
public void useDefaultMetadataNoProeprtiesFile() private void writePropertiesFile(Properties properties, File propertiesFile, String message) throws Exception {
throws Exception
{ propertiesFile.getParentFile().mkdirs();
WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( new File( testDir, "unknown" ), System.out );
OutputStream outStream = null;
Assert.assertNull( wrapper.getDistribution() ); try {
Assert.assertNull( wrapper.getConfiguration().getDistribution() ); outStream = new FileOutputStream(propertiesFile);
Assert.assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getDistributionBase() ); properties.store(outStream, message);
Assert.assertEquals( Installer.DEFAULT_DISTRIBUTION_PATH, wrapper.getConfiguration().getDistributionPath() ); } finally {
Assert.assertEquals( PathAssembler.MAVEN_USER_HOME_STRING, wrapper.getConfiguration().getZipBase() ); IOUtils.closeQuietly(outStream);
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() );
}
}
@Test
public void failWhenPropertiesFileDoesNotExist()
{
propertiesFile = new File( testDir, "unknown.properties" );
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 testRelativeDistUrl()
throws Exception
{
properties = new Properties();
properties.put( "distributionUrl", "some/relative/url/to/bin.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" ) );
}
private void writePropertiesFile( Properties properties, File propertiesFile, String message )
throws Exception
{
propertiesFile.getParentFile().mkdirs();
OutputStream outStream = null;
try
{
outStream = new FileOutputStream( propertiesFile );
properties.store( outStream, message );
}
finally
{
IOUtils.closeQuietly( outStream );
}
} }
}
} }