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
.project
.settings
.settings
/target/

View File

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

View File

@ -30,108 +30,85 @@ import java.net.URLConnection;
/**
* @author Hans Dockter
*/
public class DefaultDownloader
implements Downloader
{
private static final int PROGRESS_CHUNK = 20000;
public class DefaultDownloader implements Downloader {
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 )
{
this.applicationName = applicationName;
this.applicationVersion = applicationVersion;
configureProxyAuthentication();
public DefaultDownloader(String applicationName, String applicationVersion) {
this.applicationName = applicationName;
this.applicationVersion = applicationVersion;
configureProxyAuthentication();
}
private void configureProxyAuthentication() {
if (System.getProperty("http.proxyUser") != null) {
Authenticator.setDefault(new SystemPropertiesProxyAuthenticator());
}
}
private void configureProxyAuthentication()
{
if ( System.getProperty( "http.proxyUser" ) != null )
{
Authenticator.setDefault( new SystemPropertiesProxyAuthenticator() );
public void download(URI address, File destination) throws Exception {
if (destination.exists()) {
return;
}
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 )
throws Exception
{
if ( destination.exists() )
{
return;
}
destination.getParentFile().mkdirs();
private String calculateUserAgent() {
String appVersion = applicationVersion;
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();
}
}
}
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() );
}
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
*/
public interface Downloader
{
void download( URI address, File destination )
throws Exception;
public interface Downloader {
void download(URI address, File destination) throws Exception;
}

View File

@ -36,198 +36,155 @@ import java.util.zip.ZipFile;
/**
* @author Hans Dockter
*/
public class Installer
{
public static final String DEFAULT_DISTRIBUTION_PATH = "wrapper/dists";
public class Installer {
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 )
{
this.download = download;
this.pathAssembler = pathAssembler;
public Installer(Downloader download, PathAssembler pathAssembler) {
this.download = download;
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 )
throws Exception
{
URI distributionUrl = configuration.getDistribution();
boolean alwaysDownload = configuration.isAlwaysDownload();
boolean alwaysUnpack = configuration.isAlwaysUnpack();
File distDir = localDistribution.getDistributionDir();
List<File> dirs = listDirs(distDir);
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();
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;
private List<File> listDirs(File distDir) {
List<File> dirs = new ArrayList<File>();
if (distDir.exists()) {
for (File file : distDir.listFiles()) {
if (file.isDirectory()) {
dirs.add(file);
}
}
}
return dirs;
}
File distDir = localDistribution.getDistributionDir();
List<File> dirs = listDirs( distDir );
private void setExecutablePermissions(File mavenHome) {
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() )
{
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 ) );
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;
}
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 )
{
List<File> dirs = new ArrayList<File>();
if ( distDir.exists() )
{
for ( File file : distDir.listFiles() )
{
if ( file.isDirectory() )
{
dirs.add( file );
}
}
}
return dirs;
// 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);
}
private void setExecutablePermissions( File mavenHome )
{
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();
}
in.close();
out.close();
}
}

View File

@ -29,124 +29,91 @@ import org.apache.maven.wrapper.cli.SystemPropertiesCommandLineConverter;
/**
* @author Hans Dockter
*/
public class MavenWrapperMain
{
public static final String DEFAULT_MAVEN_USER_HOME = System.getProperty( "user.home" ) + "/.m2";
public class MavenWrapperMain {
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 )
throws Exception
{
File wrapperJar = wrapperJar();
File propertiesFile = wrapperProperties( wrapperJar );
File rootDir = rootDir( wrapperJar );
public static void main(String[] args) throws Exception {
File wrapperJar = wrapperJar();
File propertiesFile = wrapperProperties(wrapperJar);
File rootDir = rootDir(wrapperJar);
Properties systemProperties = System.getProperties();
systemProperties.putAll( parseSystemPropertiesFromArgs( args ) );
Properties systemProperties = System.getProperties();
systemProperties.putAll(parseSystemPropertiesFromArgs(args));
addSystemProperties( rootDir );
addSystemProperties(rootDir);
WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile( propertiesFile, System.out );
wrapperExecutor.execute( args, new Installer( new DefaultDownloader( "mvnw", wrapperVersion() ),
new PathAssembler( mavenUserHome() ) ), new BootstrapMainStarter() );
WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
wrapperExecutor.execute(args, new Installer(new DefaultDownloader("mvnw", wrapperVersion()), 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);
}
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 ) );
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());
}
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" ) ) );
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 rootDir( File wrapperJar )
{
return wrapperJar.getParentFile().getParentFile().getParentFile();
}
private static File wrapperProperties( File wrapperJar )
{
return new File( wrapperJar.getParent(), wrapperJar.getName().replaceFirst( "\\.jar$", ".properties" ) );
}
private static File wrapperJar()
{
URI location;
try
{
location = MavenWrapperMain.class.getProtectionDomain().getCodeSource().getLocation().toURI();
}
catch ( URISyntaxException e )
{
throw new RuntimeException( e );
}
if ( !location.getScheme().equals( "file" ) )
{
throw new RuntimeException(
String.format( "Cannot determine classpath for wrapper Jar from codebase '%s'.",
location ) );
}
return new File( location.getPath() );
}
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 );
}
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
*/
public class PathAssembler
{
public static final String MAVEN_USER_HOME_STRING = "MAVEN_USER_HOME";
public class PathAssembler {
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 )
{
this.mavenUserHome = mavenUserHome;
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;
}
/**
* 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 )
{
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 );
public File getDistributionDir() {
return distDir;
}
private String rootDirName( String distName, WrapperConfiguration configuration )
{
String urlHash = getMd5Hash( configuration.getDistribution().toString() );
return String.format( "%s/%s", distName, urlHash );
}
private String getMd5Hash( String string )
{
try
{
MessageDigest messageDigest = MessageDigest.getInstance( "MD5" );
byte[] bytes = string.getBytes();
messageDigest.update( bytes );
return new BigInteger( 1, messageDigest.digest() ).toString( 32 );
}
catch ( Exception e )
{
throw new RuntimeException( "Could not hash input string.", e );
}
}
private String removeExtension( String name )
{
int p = name.lastIndexOf( "." );
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;
}
/**
* 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
*/
public class SystemPropertiesHandler
{
public class SystemPropertiesHandler {
public static Map<String, String> getSystemProperties( File propertiesFile )
{
Map<String, String> propertyMap = new HashMap<String, String>();
if ( !propertiesFile.isFile() )
{
return propertyMap;
}
Properties properties = new Properties();
try
{
FileInputStream inStream = new FileInputStream( propertiesFile );
try
{
properties.load( inStream );
}
finally
{
inStream.close();
}
}
catch ( IOException e )
{
throw new RuntimeException( "Error when loading properties file=" + propertiesFile, e );
}
Pattern pattern = Pattern.compile( "systemProp\\.(.*)" );
for ( Object argument : properties.keySet() )
{
Matcher matcher = pattern.matcher( argument.toString() );
if ( matcher.find() )
{
String key = matcher.group( 1 );
if ( key.length() > 0 )
{
propertyMap.put( key, properties.get( argument ).toString() );
}
}
}
return propertyMap;
public static Map<String, String> getSystemProperties(File propertiesFile) {
Map<String, String> propertyMap = new HashMap<String, String>();
if (!propertiesFile.isFile()) {
return propertyMap;
}
Properties properties = new Properties();
try {
FileInputStream inStream = new FileInputStream(propertiesFile);
try {
properties.load(inStream);
} finally {
inStream.close();
}
} catch (IOException e) {
throw new RuntimeException("Error when loading properties file=" + propertiesFile, e);
}
Pattern pattern = Pattern.compile("systemProp\\.(.*)");
for (Object argument : properties.keySet()) {
Matcher matcher = pattern.matcher(argument.toString());
if (matcher.find()) {
String key = matcher.group(1);
if (key.length() > 0) {
propertyMap.put(key, properties.get(argument).toString());
}
}
}
return propertyMap;
}
}

View File

@ -17,93 +17,78 @@ package org.apache.maven.wrapper;
import java.net.URI;
public class WrapperConfiguration
{
public static final String ALWAYS_UNPACK_ENV = "MAVEN_WRAPPER_ALWAYS_UNPACK";
public class WrapperConfiguration {
public static final String ALWAYS_UNPACK_ENV = "MAVEN_WRAPPER_ALWAYS_UNPACK";
public static final String ALWAYS_DOWNLOAD_ENV = "MAVEN_WRAPPER_ALWAYS_DOWNLOAD";
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()
{
return alwaysDownload;
}
public boolean isAlwaysDownload() {
return alwaysDownload;
}
public void setAlwaysDownload( boolean alwaysDownload )
{
this.alwaysDownload = alwaysDownload;
}
public void setAlwaysDownload(boolean alwaysDownload) {
this.alwaysDownload = alwaysDownload;
}
public boolean isAlwaysUnpack()
{
return alwaysUnpack;
}
public boolean isAlwaysUnpack() {
return alwaysUnpack;
}
public void setAlwaysUnpack( boolean alwaysUnpack )
{
this.alwaysUnpack = alwaysUnpack;
}
public void setAlwaysUnpack(boolean alwaysUnpack) {
this.alwaysUnpack = alwaysUnpack;
}
public URI getDistribution()
{
return distribution;
}
public URI getDistribution() {
return distribution;
}
public void setDistribution( URI distribution )
{
this.distribution = distribution;
}
public void setDistribution(URI distribution) {
this.distribution = distribution;
}
public String getDistributionBase()
{
return distributionBase;
}
public String getDistributionBase() {
return distributionBase;
}
public void setDistributionBase( String distributionBase )
{
this.distributionBase = distributionBase;
}
public void setDistributionBase(String distributionBase) {
this.distributionBase = distributionBase;
}
public String getDistributionPath()
{
return distributionPath;
}
public String getDistributionPath() {
return distributionPath;
}
public void setDistributionPath( String distributionPath )
{
this.distributionPath = distributionPath;
}
public void setDistributionPath(String distributionPath) {
this.distributionPath = distributionPath;
}
public String getZipBase()
{
return zipBase;
}
public String getZipBase() {
return zipBase;
}
public void setZipBase( String zipBase )
{
this.zipBase = zipBase;
}
public void setZipBase(String zipBase) {
this.zipBase = zipBase;
}
public String getZipPath()
{
return zipPath;
}
public String getZipPath() {
return zipPath;
}
public void setZipPath( String zipPath )
{
this.zipPath = zipPath;
}
public void setZipPath(String zipPath) {
this.zipPath = zipPath;
}
}

View File

@ -26,152 +26,118 @@ import java.util.Properties;
/**
* @author Hans Dockter
*/
public class WrapperExecutor
{
public static final String DISTRIBUTION_URL_PROPERTY = "distributionUrl";
public class WrapperExecutor {
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 )
{
return new WrapperExecutor( new File( projectDir, "maven/wrapper/maven-wrapper.properties" ), new Properties(),
warningOutput );
public static WrapperExecutor forProjectDirectory(File projectDir, Appendable 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 )
{
if ( !propertiesFile.exists() )
{
throw new RuntimeException( String.format( "Wrapper properties file '%s' does not exist.", propertiesFile ) );
}
return new WrapperExecutor( propertiesFile, new Properties(), warningOutput );
}
reportMissingProperty(DISTRIBUTION_URL_PROPERTY);
return null; // previous line will fail
}
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 static void loadProperties(File propertiesFile, Properties properties) throws IOException {
InputStream inStream = new FileInputStream(propertiesFile);
try {
properties.load(inStream);
} finally {
inStream.close();
}
}
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;
}
/**
* 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;
}
private URI readDistroUrl()
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
if (defaultValue != null) {
return defaultValue;
}
return reportMissingProperty(propertyName);
}
private static void loadProperties( File propertiesFile, Properties properties )
throws IOException
{
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 ) );
}
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;
public abstract class AbstractCommandLineConverter<T>
implements CommandLineConverter<T>
{
public T convert( Iterable<String> args )
throws CommandLineArgumentException
{
CommandLineParser parser = new CommandLineParser();
configure( parser );
return convert( parser.parse( args ) );
}
public abstract class AbstractCommandLineConverter<T> implements CommandLineConverter<T> {
public T convert(Iterable<String> args) throws CommandLineArgumentException {
CommandLineParser parser = new CommandLineParser();
configure(parser);
return convert(parser.parse(args));
}
public T convert( ParsedCommandLine args )
throws CommandLineArgumentException
{
return convert( args, newInstance() );
}
public T convert(ParsedCommandLine args) throws CommandLineArgumentException {
return convert(args, newInstance());
}
public T convert( Iterable<String> args, T target )
throws CommandLineArgumentException
{
CommandLineParser parser = new CommandLineParser();
configure( parser );
return convert( parser.parse( args ), target );
}
public T convert(Iterable<String> args, T target) throws CommandLineArgumentException {
CommandLineParser parser = new CommandLineParser();
configure(parser);
return convert(parser.parse(args), target);
}
protected abstract T newInstance();
protected abstract T newInstance();
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,25 +15,20 @@
*/
package org.apache.maven.wrapper.cli;
public class SystemPropertiesCommandLineConverter
extends AbstractPropertiesCommandLineConverter
{
public class SystemPropertiesCommandLineConverter extends AbstractPropertiesCommandLineConverter {
@Override
protected String getPropertyOption()
{
return "D";
}
@Override
protected String getPropertyOption() {
return "D";
}
@Override
protected String getPropertyOptionDetailed()
{
return "system-prop";
}
@Override
protected String getPropertyOptionDetailed() {
return "system-prop";
}
@Override
protected String getPropertyOptionDescription()
{
return "Set system property of the JVM (e.g. -Dmyprop=myvalue).";
}
@Override
protected String getPropertyOptionDescription() {
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.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
public void setUp()
throws Exception
{
download = new DefaultDownloader( "mvnw", "aVersion" );
testDir = new File( "target/test-files/DownloadTest" );
rootDir = new File( testDir, "root" );
downloadFile = new File( rootDir, "file" );
remoteFile = new File( testDir, "remoteFile" );
FileUtils.write( remoteFile, "sometext" );
sourceRoot = remoteFile.toURI();
}
@Before
public void setUp() throws Exception {
download = new DefaultDownloader("mvnw", "aVersion");
testDir = new File("target/test-files/DownloadTest");
rootDir = new File(testDir, "root");
downloadFile = new File(rootDir, "file");
remoteFile = new File(testDir, "remoteFile");
FileUtils.write(remoteFile, "sometext");
sourceRoot = remoteFile.toURI();
}
@Test
public void testDownload()
throws Exception
{
assert !downloadFile.exists();
download.download( sourceRoot, downloadFile );
assert downloadFile.exists();
assertEquals( "sometext", FileUtils.readFileToString( downloadFile ) );
}
@Test
public void testDownload() throws Exception {
assert !downloadFile.exists();
download.download(sourceRoot, downloadFile);
assert downloadFile.exists();
assertEquals("sometext", FileUtils.readFileToString(downloadFile));
}
}

View File

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

View File

@ -33,113 +33,91 @@ import org.junit.Test;
/**
* @author Hans Dockter
*/
public class PathAssemblerTest
{
public static final String TEST_MAVEN_USER_HOME = "someUserHome";
public class PathAssemblerTest {
public static final String TEST_MAVEN_USER_HOME = "someUserHome";
private PathAssembler pathAssembler = new PathAssembler( new File( TEST_MAVEN_USER_HOME ) );
private PathAssembler pathAssembler = new PathAssembler(new File(TEST_MAVEN_USER_HOME));
final WrapperConfiguration configuration = new WrapperConfiguration();
final WrapperConfiguration configuration = new WrapperConfiguration();
@Before
public void setup()
{
configuration.setDistributionBase( PathAssembler.MAVEN_USER_HOME_STRING );
configuration.setDistributionPath( "somePath" );
configuration.setZipBase( PathAssembler.MAVEN_USER_HOME_STRING );
configuration.setZipPath( "somePath" );
@Before
public void setup() {
configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
configuration.setDistributionPath("somePath");
configuration.setZipBase(PathAssembler.MAVEN_USER_HOME_STRING);
configuration.setZipPath("somePath");
}
@Test
public void distributionDirWithMavenUserHomeBase() throws Exception {
configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip"));
File distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir();
assertThat(distributionDir.getName(), matchesRegexp("[a-z0-9]+"));
assertThat(distributionDir.getParentFile(), equalTo(file(TEST_MAVEN_USER_HOME + "/somePath/maven-0.9-bin")));
}
@Test
public void distributionDirWithProjectBase() throws Exception {
configuration.setDistributionBase(PathAssembler.PROJECT_STRING);
configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip"));
File distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir();
assertThat(distributionDir.getName(), matchesRegexp("[a-z0-9]+"));
assertThat(distributionDir.getParentFile(), equalTo(file(currentDirPath() + "/somePath/maven-0.9-bin")));
}
@Test
public void distributionDirWithUnknownBase() throws Exception {
configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
configuration.setDistributionBase("unknownBase");
try {
pathAssembler.getDistribution(configuration);
fail();
} catch (RuntimeException e) {
assertEquals("Base: unknownBase is unknown", e.getMessage());
}
}
@Test
public void distributionDirWithMavenUserHomeBase()
throws Exception
{
configuration.setDistribution( new URI( "http://server/dist/maven-0.9-bin.zip" ) );
@Test
public void distZipWithMavenUserHomeBase() throws Exception {
configuration.setDistribution(new URI("http://server/dist/maven-1.0.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" ) ) );
}
File dist = pathAssembler.getDistribution(configuration).getZipFile();
assertThat(dist.getName(), equalTo("maven-1.0.zip"));
assertThat(dist.getParentFile().getName(), matchesRegexp("[a-z0-9]+"));
assertThat(dist.getParentFile().getParentFile(), equalTo(file(TEST_MAVEN_USER_HOME + "/somePath/maven-1.0")));
}
@Test
public void distributionDirWithProjectBase()
throws Exception
{
configuration.setDistributionBase( PathAssembler.PROJECT_STRING );
configuration.setDistribution( new URI( "http://server/dist/maven-0.9-bin.zip" ) );
@Test
public void distZipWithProjectBase() throws Exception {
configuration.setZipBase(PathAssembler.PROJECT_STRING);
configuration.setDistribution(new URI("http://server/dist/maven-1.0.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" ) ) );
}
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")));
}
@Test
public void distributionDirWithUnknownBase()
throws Exception
{
configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
configuration.setDistributionBase( "unknownBase" );
private File file(String path) {
return new File(path);
}
try
{
pathAssembler.getDistribution( configuration );
fail();
}
catch ( RuntimeException e )
{
assertEquals( "Base: unknownBase is unknown", e.getMessage() );
}
}
private String currentDirPath() {
return System.getProperty("user.dir");
}
@Test
public void distZipWithMavenUserHomeBase()
throws Exception
{
configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
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();
}
File dist = pathAssembler.getDistribution( configuration ).getZipFile();
assertThat( dist.getName(), equalTo( "maven-1.0.zip" ) );
assertThat( dist.getParentFile().getName(), matchesRegexp( "[a-z0-9]+" ) );
assertThat( dist.getParentFile().getParentFile(),
equalTo( file( TEST_MAVEN_USER_HOME + "/somePath/maven-1.0" ) ) );
}
@Test
public void distZipWithProjectBase()
throws Exception
{
configuration.setZipBase( PathAssembler.PROJECT_STRING );
configuration.setDistribution( new URI( "http://server/dist/maven-1.0.zip" ) );
File dist = pathAssembler.getDistribution( configuration ).getZipFile();
assertThat( dist.getName(), equalTo( "maven-1.0.zip" ) );
assertThat( dist.getParentFile().getName(), matchesRegexp( "[a-z0-9]+" ) );
assertThat( dist.getParentFile().getParentFile(), equalTo( file( currentDirPath() + "/somePath/maven-1.0" ) ) );
}
private File file( String path )
{
return new File( path );
}
private String currentDirPath()
{
return System.getProperty( "user.dir" );
}
public static <T extends CharSequence> Matcher<T> matchesRegexp( final String pattern )
{
return new BaseMatcher<T>()
{
public boolean matches( Object o )
{
return Pattern.compile( pattern ).matcher( (CharSequence) o ).matches();
}
public void describeTo( Description description )
{
description.appendText( "a CharSequence that matches regexp " ).appendValue( pattern );
}
};
}
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.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
public void setupTempDir()
{
tmpDir.mkdirs();
@Before
public void setupTempDir() {
tmpDir.mkdirs();
}
@Test
public void testParsePropertiesFile() throws Exception {
File propFile = new File(tmpDir, "props");
Properties props = new Properties();
props.put("a", "b");
props.put("systemProp.c", "d");
props.put("systemProp.", "e");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(propFile);
props.store(fos, "");
} finally {
IOUtils.closeQuietly(fos);
}
@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" );
Map<String, String> expected = new HashMap<String, String>();
expected.put("c", "d");
FileOutputStream fos = null;
try
{
fos = new FileOutputStream( propFile );
props.store( fos, "" );
}
finally
{
IOUtils.closeQuietly( fos );
}
assertThat(SystemPropertiesHandler.getSystemProperties(propFile), equalTo(expected));
}
Map<String, String> expected = new HashMap<String, String>();
expected.put( "c", "d" );
assertThat( SystemPropertiesHandler.getSystemProperties( propFile ), equalTo( expected ) );
}
@Test
public void ifNoPropertyFileExistShouldReturnEmptyMap()
{
Map<String, String> expected = new HashMap<String, String>();
assertThat( SystemPropertiesHandler.getSystemProperties( new File( tmpDir, "unknown" ) ), equalTo( expected ) );
}
@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.mockito.Mockito;
public class WrapperExecutorTest
{
private final Installer install;
public class WrapperExecutorTest {
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()
throws Exception
{
install = mock( Installer.class );
when( install.createDist( Mockito.any( WrapperConfiguration.class ) ) ).thenReturn( mockInstallDir );
start = mock( BootstrapMainStarter.class );
public WrapperExecutorTest() throws Exception {
install = mock(Installer.class);
when(install.createDist(Mockito.any(WrapperConfiguration.class))).thenReturn(mockInstallDir);
start = mock(BootstrapMainStarter.class);
testDir.mkdirs();
propertiesFile = new File( testDir, "maven/wrapper/maven-wrapper.properties" );
testDir.mkdirs();
propertiesFile = new File(testDir, "maven/wrapper/maven-wrapper.properties");
properties.put( "distributionUrl", "http://server/test/maven.zip" );
properties.put( "distributionBase", "testDistBase" );
properties.put( "distributionPath", "testDistPath" );
properties.put( "zipStoreBase", "testZipBase" );
properties.put( "zipStorePath", "testZipPath" );
properties.put("distributionUrl", "http://server/test/maven.zip");
properties.put("distributionBase", "testDistBase");
properties.put("distributionPath", "testDistPath");
properties.put("zipStoreBase", "testZipBase");
properties.put("zipStorePath", "testZipPath");
writePropertiesFile( properties, propertiesFile, "header" );
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() );
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 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 loadWrapperMetadataFromDirectory()
throws Exception
{
WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory( testDir, System.out );
@Test
public void testRelativeDistUrl() throws Exception {
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 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 );
}
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);
}
}
}