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
/target/

View File

@ -23,14 +23,12 @@ import java.net.URLClassLoader;
/**
* @author Hans Dockter
*/
public class BootstrapMainStarter
{
public void start( String[] args, File mavenHome )
throws Exception
{
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() );
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");
@ -38,20 +36,17 @@ public class BootstrapMainStarter
System.setProperty("classworlds.conf", new File(mavenHome, "/bin/m2.conf").getAbsolutePath());
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() )
{
if ( file.getName().matches( "plexus-classworlds-.*\\.jar" ) )
{
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 ) );
throw new RuntimeException(String.format("Could not locate the Maven launcher JAR in Maven distribution '%s'.", mavenHome));
}
}

View File

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

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,23 +36,19 @@ import java.util.zip.ZipFile;
/**
* @author Hans Dockter
*/
public class Installer
{
public class Installer {
public static final String DEFAULT_DISTRIBUTION_PATH = "wrapper/dists";
private final Downloader download;
private final PathAssembler pathAssembler;
public Installer( Downloader download, PathAssembler pathAssembler )
{
public Installer(Downloader download, PathAssembler pathAssembler) {
this.download = download;
this.pathAssembler = pathAssembler;
}
public File createDist( WrapperConfiguration configuration )
throws Exception
{
public File createDist(WrapperConfiguration configuration) throws Exception {
URI distributionUrl = configuration.getDistribution();
boolean alwaysDownload = configuration.isAlwaysDownload();
boolean alwaysUnpack = configuration.isAlwaysUnpack();
@ -61,8 +57,7 @@ public class Installer
File localZipFile = localDistribution.getZipFile();
boolean downloaded = false;
if ( alwaysDownload || !localZipFile.exists() )
{
if (alwaysDownload || !localZipFile.exists()) {
File tmpZipFile = new File(localZipFile.getParentFile(), localZipFile.getName() + ".part");
tmpZipFile.delete();
System.out.println("Downloading " + distributionUrl);
@ -74,42 +69,30 @@ public class Installer
File distDir = localDistribution.getDistributionDir();
List<File> dirs = listDirs(distDir);
if ( downloaded || alwaysUnpack || dirs.isEmpty() )
{
for ( File dir : dirs )
{
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 ) );
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 ) );
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 )
{
private List<File> listDirs(File distDir) {
List<File> dirs = new ArrayList<File>();
if ( distDir.exists() )
{
for ( File file : distDir.listFiles() )
{
if ( file.isDirectory() )
{
if (distDir.exists()) {
for (File file : distDir.listFiles()) {
if (file.isDirectory()) {
dirs.add(file);
}
}
@ -117,69 +100,51 @@ public class Installer
return dirs;
}
private void setExecutablePermissions( File mavenHome )
{
if ( isWindows() )
{
private void setExecutablePermissions(File mavenHome) {
if (isWindows()) {
return;
}
File mavenCommand = new File(mavenHome, "bin/mvn");
String errorMessage = null;
try
{
try {
ProcessBuilder pb = new ProcessBuilder("chmod", "755", mavenCommand.getCanonicalPath());
Process p = pb.start();
if ( p.waitFor() == 0 )
{
if (p.waitFor() == 0) {
System.out.println("Set executable permissions for: " + mavenCommand.getAbsolutePath());
}
else
{
} else {
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
Formatter stdout = new Formatter();
String line;
while ( ( line = is.readLine() ) != null )
{
while ((line = is.readLine()) != null) {
stdout.format("%s%n", line);
}
errorMessage = stdout.toString();
}
}
catch ( IOException e )
{
} catch (IOException e) {
errorMessage = e.getMessage();
} catch (InterruptedException e) {
errorMessage = e.getMessage();
}
catch ( InterruptedException e )
{
errorMessage = e.getMessage();
}
if ( errorMessage != null )
{
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()
{
private boolean isWindows() {
String osName = System.getProperty("os.name").toLowerCase(Locale.US);
if ( osName.indexOf( "windows" ) > -1 )
{
if (osName.indexOf("windows") > -1) {
return true;
}
return false;
}
private boolean deleteDir( File dir )
{
if ( dir.isDirectory() )
{
private boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for ( int i = 0; i < children.length; i++ )
{
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if ( !success )
{
if (!success) {
return false;
}
}
@ -189,9 +154,7 @@ public class Installer
return dir.delete();
}
public void unzip( File zip, File dest )
throws IOException
{
public void unzip(File zip, File dest) throws IOException {
Enumeration entries;
ZipFile zipFile;
@ -199,30 +162,24 @@ public class Installer
entries = zipFile.entries();
while ( entries.hasMoreElements() )
{
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if ( entry.isDirectory() )
{
if (entry.isDirectory()) {
(new File(dest, entry.getName())).mkdirs();
continue;
}
copyInputStream( zipFile.getInputStream( entry ),
new BufferedOutputStream( new FileOutputStream( new File( dest, entry.getName() ) ) ) );
copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(new File(dest, entry.getName()))));
}
zipFile.close();
}
public void copyInputStream( InputStream in, OutputStream out )
throws IOException
{
public void copyInputStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len;
while ( ( len = in.read( buffer ) ) >= 0 )
{
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}

View File

@ -29,17 +29,14 @@ import org.apache.maven.wrapper.cli.SystemPropertiesCommandLineConverter;
/**
* @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 MAVEN_USER_HOME_PROPERTY_KEY = "maven.user.home";
public static final String MAVEN_USER_HOME_ENV_KEY = "MAVEN_USER_HOME";
public static void main( String[] args )
throws Exception
{
public static void main(String[] args) throws Exception {
File wrapperJar = wrapperJar();
File propertiesFile = wrapperProperties(wrapperJar);
File rootDir = rootDir(wrapperJar);
@ -50,12 +47,10 @@ public class MavenWrapperMain
addSystemProperties(rootDir);
WrapperExecutor wrapperExecutor = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
wrapperExecutor.execute( args, new Installer( new DefaultDownloader( "mvnw", wrapperVersion() ),
new PathAssembler( mavenUserHome() ) ), new BootstrapMainStarter() );
wrapperExecutor.execute(args, new Installer(new DefaultDownloader("mvnw", wrapperVersion()), new PathAssembler(mavenUserHome())), new BootstrapMainStarter());
}
private static Map<String, String> parseSystemPropertiesFromArgs( String[] args )
{
private static Map<String, String> parseSystemPropertiesFromArgs(String[] args) {
SystemPropertiesCommandLineConverter converter = new SystemPropertiesCommandLineConverter();
CommandLineParser commandLineParser = new CommandLineParser();
converter.configure(commandLineParser);
@ -63,89 +58,61 @@ public class MavenWrapperMain
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 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 )
{
private static File rootDir(File wrapperJar) {
return wrapperJar.getParentFile().getParentFile().getParentFile();
}
private static File wrapperProperties( File wrapperJar )
{
private static File wrapperProperties(File wrapperJar) {
return new File(wrapperJar.getParent(), wrapperJar.getName().replaceFirst("\\.jar$", ".properties"));
}
private static File wrapperJar()
{
private static File wrapperJar() {
URI location;
try
{
try {
location = MavenWrapperMain.class.getProtectionDomain().getCodeSource().getLocation().toURI();
}
catch ( URISyntaxException e )
{
} 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 ) );
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 )
{
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
{
try {
mavenProperties.load(resourceAsStream);
String version = mavenProperties.getProperty("version");
if ( version == null )
{
if (version == null) {
throw new RuntimeException("No version number specified in build receipt resource.");
}
return version;
}
finally
{
} finally {
resourceAsStream.close();
}
}
catch ( Exception e )
{
} catch (Exception e) {
throw new RuntimeException("Could not determine wrapper version.", e);
}
}
private static File mavenUserHome()
{
private static File mavenUserHome() {
String mavenUserHome = System.getProperty(MAVEN_USER_HOME_PROPERTY_KEY);
if ( mavenUserHome != null )
{
if (mavenUserHome != null) {
return new File(mavenUserHome);
}
else if ( ( mavenUserHome = System.getenv( MAVEN_USER_HOME_ENV_KEY ) ) != null )
{
} else if ((mavenUserHome = System.getenv(MAVEN_USER_HOME_ENV_KEY)) != null) {
return new File(mavenUserHome);
}
else
{
} else {
return new File(DEFAULT_MAVEN_USER_HOME);
}
}

View File

@ -23,106 +23,81 @@ import java.security.MessageDigest;
/**
* @author Hans Dockter
*/
public class PathAssembler
{
public class PathAssembler {
public static final String MAVEN_USER_HOME_STRING = "MAVEN_USER_HOME";
public static final String PROJECT_STRING = "PROJECT";
private File mavenUserHome;
public PathAssembler()
{
public PathAssembler() {
}
public PathAssembler( File mavenUserHome )
{
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 )
{
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 );
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 )
{
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
{
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 )
{
} catch (Exception e) {
throw new RuntimeException("Could not hash input string.", e);
}
}
private String removeExtension( String name )
{
private String removeExtension(String name) {
int p = name.lastIndexOf(".");
if ( p < 0 )
{
if (p < 0) {
return name;
}
return name.substring(0, p);
}
private String getDistName( URI distUrl )
{
private String getDistName(URI distUrl) {
String path = distUrl.getPath();
int p = path.lastIndexOf("/");
if ( p < 0 )
{
if (p < 0) {
return path;
}
return path.substring(p + 1);
}
private File getBaseDir( String base )
{
if ( base.equals( MAVEN_USER_HOME_STRING ) )
{
private File getBaseDir(String base) {
if (base.equals(MAVEN_USER_HOME_STRING)) {
return mavenUserHome;
}
else if ( base.equals( PROJECT_STRING ) )
{
} else if (base.equals(PROJECT_STRING)) {
return new File(System.getProperty("user.dir"));
}
else
{
} else {
throw new RuntimeException("Base: " + base + " is unknown");
}
}
public class LocalDistribution
{
public class LocalDistribution {
private final File distZip;
private final File distDir;
public LocalDistribution( File distDir, File distZip )
{
public LocalDistribution(File distDir, File distZip) {
this.distDir = distDir;
this.distZip = distZip;
}
@ -130,16 +105,14 @@ public class PathAssembler
/**
* Returns the location to install the distribution into.
*/
public File getDistributionDir()
{
public File getDistributionDir() {
return distDir;
}
/**
* Returns the location to install the distribution ZIP file to.
*/
public File getZipFile()
{
public File getZipFile() {
return distZip;
}
}

View File

@ -27,43 +27,31 @@ import java.util.regex.Pattern;
/**
* @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>();
if ( !propertiesFile.isFile() )
{
if (!propertiesFile.isFile()) {
return propertyMap;
}
Properties properties = new Properties();
try
{
try {
FileInputStream inStream = new FileInputStream(propertiesFile);
try
{
try {
properties.load(inStream);
}
finally
{
} finally {
inStream.close();
}
}
catch ( IOException e )
{
} catch (IOException e) {
throw new RuntimeException("Error when loading properties file=" + propertiesFile, e);
}
Pattern pattern = Pattern.compile("systemProp\\.(.*)");
for ( Object argument : properties.keySet() )
{
for (Object argument : properties.keySet()) {
Matcher matcher = pattern.matcher(argument.toString());
if ( matcher.find() )
{
if (matcher.find()) {
String key = matcher.group(1);
if ( key.length() > 0 )
{
if (key.length() > 0) {
propertyMap.put(key, properties.get(argument).toString());
}
}

View File

@ -17,8 +17,7 @@ package org.apache.maven.wrapper;
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_DOWNLOAD_ENV = "MAVEN_WRAPPER_ALWAYS_DOWNLOAD";
@ -37,73 +36,59 @@ public class WrapperConfiguration
private String zipPath = Installer.DEFAULT_DISTRIBUTION_PATH;
public boolean isAlwaysDownload()
{
public boolean isAlwaysDownload() {
return alwaysDownload;
}
public void setAlwaysDownload( boolean alwaysDownload )
{
public void setAlwaysDownload(boolean alwaysDownload) {
this.alwaysDownload = alwaysDownload;
}
public boolean isAlwaysUnpack()
{
public boolean isAlwaysUnpack() {
return alwaysUnpack;
}
public void setAlwaysUnpack( boolean alwaysUnpack )
{
public void setAlwaysUnpack(boolean alwaysUnpack) {
this.alwaysUnpack = alwaysUnpack;
}
public URI getDistribution()
{
public URI getDistribution() {
return distribution;
}
public void setDistribution( URI distribution )
{
public void setDistribution(URI distribution) {
this.distribution = distribution;
}
public String getDistributionBase()
{
public String getDistributionBase() {
return distributionBase;
}
public void setDistributionBase( String distributionBase )
{
public void setDistributionBase(String distributionBase) {
this.distributionBase = distributionBase;
}
public String getDistributionPath()
{
public String getDistributionPath() {
return distributionPath;
}
public void setDistributionPath( String distributionPath )
{
public void setDistributionPath(String distributionPath) {
this.distributionPath = distributionPath;
}
public String getZipBase()
{
public String getZipBase() {
return zipBase;
}
public void setZipBase( String zipBase )
{
public void setZipBase(String zipBase) {
this.zipBase = zipBase;
}
public String getZipPath()
{
public String getZipPath() {
return zipPath;
}
public void setZipPath( String zipPath )
{
public void setZipPath(String zipPath) {
this.zipPath = zipPath;
}
}

View File

@ -26,8 +26,7 @@ import java.util.Properties;
/**
* @author Hans Dockter
*/
public class WrapperExecutor
{
public class WrapperExecutor {
public static final String DISTRIBUTION_URL_PROPERTY = "distributionUrl";
public static final String DISTRIBUTION_BASE_PROPERTY = "distributionBase";
@ -46,65 +45,47 @@ public class WrapperExecutor
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() )
{
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 )
{
WrapperExecutor(File propertiesFile, Properties properties, Appendable warningOutput) {
this.properties = properties;
this.propertiesFile = propertiesFile;
this.warningOutput = warningOutput;
if ( propertiesFile.exists() )
{
try
{
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 );
} catch (Exception e) {
throw new RuntimeException(String.format("Could not load wrapper properties from '%s'.", propertiesFile), e);
}
}
}
private URI prepareDistributionUri()
throws URISyntaxException
{
private URI prepareDistributionUri() throws URISyntaxException {
URI source = readDistroUrl();
if ( source.getScheme() == null )
{
if (source.getScheme() == null) {
// no scheme means someone passed a relative url. In our context only file relative urls make sense.
return new File(propertiesFile.getParentFile(), source.getSchemeSpecificPart()).toURI();
}
else
{
} else {
return source;
}
}
private URI readDistroUrl()
throws URISyntaxException
{
if ( properties.getProperty( DISTRIBUTION_URL_PROPERTY ) != null )
{
private URI readDistroUrl() throws URISyntaxException {
if (properties.getProperty(DISTRIBUTION_URL_PROPERTY) != null) {
return new URI(getProperty(DISTRIBUTION_URL_PROPERTY));
}
@ -112,16 +93,11 @@ public class WrapperExecutor
return null; // previous line will fail
}
private static void loadProperties( File propertiesFile, Properties properties )
throws IOException
{
private static void loadProperties(File propertiesFile, Properties properties) throws IOException {
InputStream inStream = new FileInputStream(propertiesFile);
try
{
try {
properties.load(inStream);
}
finally
{
} finally {
inStream.close();
}
}
@ -130,48 +106,38 @@ public class WrapperExecutor
* 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()
{
public URI getDistribution() {
return config.getDistribution();
}
/**
* Returns the configuration for this wrapper.
*/
public WrapperConfiguration getConfiguration()
{
public WrapperConfiguration getConfiguration() {
return config;
}
public void execute( String[] args, Installer install, BootstrapMainStarter bootstrapMainStarter )
throws Exception
{
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 )
{
private String getProperty(String propertyName) {
return getProperty(propertyName, null);
}
private String getProperty( String propertyName, String defaultValue )
{
private String getProperty(String propertyName, String defaultValue) {
String value = properties.getProperty(propertyName);
if ( value != null )
{
if (value != null) {
return value;
}
if ( defaultValue != null )
{
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,26 +15,18 @@
*/
package org.apache.maven.wrapper.cli;
public abstract class AbstractCommandLineConverter<T>
implements CommandLineConverter<T>
{
public T convert( Iterable<String> args )
throws CommandLineArgumentException
{
public abstract class AbstractCommandLineConverter<T> implements CommandLineConverter<T> {
public T convert(Iterable<String> args) throws CommandLineArgumentException {
CommandLineParser parser = new CommandLineParser();
configure(parser);
return convert(parser.parse(args));
}
public T convert( ParsedCommandLine args )
throws CommandLineArgumentException
{
public T convert(ParsedCommandLine args) throws CommandLineArgumentException {
return convert(args, newInstance());
}
public T convert( Iterable<String> args, T target )
throws CommandLineArgumentException
{
public T convert(Iterable<String> args, T target) throws CommandLineArgumentException {
CommandLineParser parser = new CommandLineParser();
configure(parser);
return convert(parser.parse(args), target);

View File

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

View File

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

View File

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

View File

@ -55,8 +55,7 @@ import java.util.TreeSet;
* time. Use {@link ParsedCommandLine#getExtraArguments()} to obtain the non-option command-line arguments.</li>
* </ul>
*/
public class CommandLineParser
{
public class CommandLineParser {
private Map<String, CommandLineOption> optionsByString = new HashMap<String, CommandLineOption>();
private boolean allowMixedOptions;
@ -65,13 +64,11 @@ public class CommandLineParser
private final PrintWriter deprecationPrinter;
public CommandLineParser()
{
public CommandLineParser() {
this(new OutputStreamWriter(System.out));
}
public CommandLineParser( Writer deprecationPrinter )
{
public CommandLineParser(Writer deprecationPrinter) {
this.deprecationPrinter = new PrintWriter(deprecationPrinter);
}
@ -82,9 +79,7 @@ public class CommandLineParser
* @return The parsed command line.
* @throws org.apache.maven.wrapper.cli.CommandLineArgumentException On parse failure.
*/
public ParsedCommandLine parse( String... commandLine )
throws CommandLineArgumentException
{
public ParsedCommandLine parse(String... commandLine) throws CommandLineArgumentException {
return parse(Arrays.asList(commandLine));
}
@ -95,77 +90,50 @@ public class CommandLineParser
* @return The parsed command line.
* @throws org.apache.maven.wrapper.cli.CommandLineArgumentException On parse failure.
*/
public ParsedCommandLine parse( Iterable<String> commandLine )
throws CommandLineArgumentException
{
ParsedCommandLine parsedCommandLine =
new ParsedCommandLine( new HashSet<CommandLineOption>( optionsByString.values() ) );
public ParsedCommandLine parse(Iterable<String> commandLine) throws CommandLineArgumentException {
ParsedCommandLine parsedCommandLine = new ParsedCommandLine(new HashSet<CommandLineOption>(optionsByString.values()));
ParserState parseState = new BeforeFirstSubCommand(parsedCommandLine);
for ( String arg : commandLine )
{
if ( parseState.maybeStartOption( arg ) )
{
if ( arg.equals( "--" ) )
{
for (String arg : commandLine) {
if (parseState.maybeStartOption(arg)) {
if (arg.equals("--")) {
parseState = new AfterOptions(parsedCommandLine);
}
else if ( arg.matches( "--[^=]+" ) )
{
} else if (arg.matches("--[^=]+")) {
OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2));
parseState = parsedOption.onStartNextArg();
}
else if ( arg.matches( "--[^=]+=.*" ) )
{
} else if (arg.matches("--[^=]+=.*")) {
int endArg = arg.indexOf('=');
OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2, endArg));
parseState = parsedOption.onArgument(arg.substring(endArg + 1));
}
else if ( arg.matches( "-[^=]=.*" ) )
{
} else if (arg.matches("-[^=]=.*")) {
OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(1, 2));
parseState = parsedOption.onArgument(arg.substring(3));
}
else
{
} else {
assert arg.matches("-[^-].*");
String option = arg.substring(1);
if ( optionsByString.containsKey( option ) )
{
if (optionsByString.containsKey(option)) {
OptionParserState parsedOption = parseState.onStartOption(arg, option);
parseState = parsedOption.onStartNextArg();
}
else
{
} else {
String option1 = arg.substring(1, 2);
OptionParserState parsedOption;
if ( optionsByString.containsKey( option1 ) )
{
if (optionsByString.containsKey(option1)) {
parsedOption = parseState.onStartOption("-" + option1, option1);
if ( parsedOption.getHasArgument() )
{
if (parsedOption.getHasArgument()) {
parseState = parsedOption.onArgument(arg.substring(2));
}
else
{
} else {
parseState = parsedOption.onComplete();
for ( int i = 2; i < arg.length(); i++ )
{
for (int i = 2; i < arg.length(); i++) {
String optionStr = arg.substring(i, i + 1);
parsedOption = parseState.onStartOption("-" + optionStr, optionStr);
parseState = parsedOption.onComplete();
}
}
}
else
{
if ( allowUnknownOptions )
{
} else {
if (allowUnknownOptions) {
// if we are allowing unknowns, just pass through the whole arg
parsedOption = parseState.onStartOption(arg, option);
parseState = parsedOption.onComplete();
}
else
{
} else {
// We are going to throw a CommandLineArgumentException below, but want the message
// to reflect that we didn't recognise the first char (i.e. the option specifier)
parsedOption = parseState.onStartOption("-" + option1, option1);
@ -174,9 +142,7 @@ public class CommandLineParser
}
}
}
}
else
{
} else {
parseState = parseState.onNonOption(arg);
}
}
@ -185,14 +151,12 @@ public class CommandLineParser
return parsedCommandLine;
}
public CommandLineParser allowMixedSubcommandsAndOptions()
{
public CommandLineParser allowMixedSubcommandsAndOptions() {
allowMixedOptions = true;
return this;
}
public CommandLineParser allowUnknownOptions()
{
public CommandLineParser allowUnknownOptions() {
allowUnknownOptions = true;
return this;
}
@ -202,71 +166,55 @@ public class CommandLineParser
*
* @param out The output stream to write to.
*/
public void printUsage( Appendable out )
{
public void printUsage(Appendable out) {
Formatter formatter = new Formatter(out);
Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>(new OptionComparator());
orderedOptions.addAll(optionsByString.values());
Map<String, String> lines = new LinkedHashMap<String, String>();
for ( CommandLineOption option : orderedOptions )
{
for (CommandLineOption option : orderedOptions) {
Set<String> orderedOptionStrings = new TreeSet<String>(new OptionStringComparator());
orderedOptionStrings.addAll(option.getOptions());
List<String> prefixedStrings = new ArrayList<String>();
for ( String optionString : orderedOptionStrings )
{
if ( optionString.length() == 1 )
{
for (String optionString : orderedOptionStrings) {
if (optionString.length() == 1) {
prefixedStrings.add("-" + optionString);
}
else
{
} else {
prefixedStrings.add("--" + optionString);
}
}
String key = join(prefixedStrings, ", ");
String value = option.getDescription();
if ( value == null || value.length() == 0 )
{
if (value == null || value.length() == 0) {
value = "";
}
lines.put(key, value);
}
int max = 0;
for ( String optionStr : lines.keySet() )
{
for (String optionStr : lines.keySet()) {
max = Math.max(max, optionStr.length());
}
for ( Map.Entry<String, String> entry : lines.entrySet() )
{
if ( entry.getValue().length() == 0 )
{
for (Map.Entry<String, String> entry : lines.entrySet()) {
if (entry.getValue().length() == 0) {
formatter.format("%s%n", entry.getKey());
}
else
{
} else {
formatter.format("%-" + max + "s %s%n", entry.getKey(), entry.getValue());
}
}
formatter.flush();
}
private static String join( Collection<?> things, String separator )
{
private static String join(Collection<?> things, String separator) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
if ( separator == null )
{
if (separator == null) {
separator = "";
}
for ( Object thing : things )
{
if ( !first )
{
for (Object thing : things) {
if (!first) {
buffer.append(separator);
}
buffer.append(thing.toString());
@ -281,59 +229,46 @@ public class CommandLineParser
* @param options The options values.
* @return The option, which can be further configured.
*/
public CommandLineOption option( String... options )
{
for ( String option : options )
{
if ( optionsByString.containsKey( option ) )
{
public CommandLineOption option(String... options) {
for (String option : options) {
if (optionsByString.containsKey(option)) {
throw new IllegalArgumentException(String.format("Option '%s' is already defined.", option));
}
if ( option.startsWith( "-" ) )
{
throw new IllegalArgumentException(
String.format( "Cannot add option '%s' as an option cannot start with '-'.",
option ) );
if (option.startsWith("-")) {
throw new IllegalArgumentException(String.format("Cannot add option '%s' as an option cannot start with '-'.", option));
}
}
CommandLineOption option = new CommandLineOption(Arrays.asList(options));
for ( String optionStr : option.getOptions() )
{
for (String optionStr : option.getOptions()) {
this.optionsByString.put(optionStr, option);
}
return option;
}
private static class OptionString
{
private static class OptionString {
private final String arg;
private final String option;
private OptionString( String arg, String option )
{
private OptionString(String arg, String option) {
this.arg = arg;
this.option = option;
}
public String getDisplayName()
{
public String getDisplayName() {
return arg.startsWith("--") ? "--" + option : "-" + option;
}
@Override
public String toString()
{
public String toString() {
return getDisplayName();
}
}
private static abstract class ParserState
{
private static abstract class ParserState {
public abstract boolean maybeStartOption(String arg);
boolean isOption( String arg )
{
boolean isOption(String arg) {
return arg.matches("-.+");
}
@ -341,151 +276,117 @@ public class CommandLineParser
public abstract ParserState onNonOption(String arg);
public void onCommandLineEnd()
{
public void onCommandLineEnd() {
}
}
private abstract class OptionAwareParserState
extends ParserState
{
private abstract class OptionAwareParserState extends ParserState {
protected final ParsedCommandLine commandLine;
protected OptionAwareParserState( ParsedCommandLine commandLine )
{
protected OptionAwareParserState(ParsedCommandLine commandLine) {
this.commandLine = commandLine;
}
@Override
public boolean maybeStartOption( String arg )
{
public boolean maybeStartOption(String arg) {
return isOption(arg);
}
@Override
public ParserState onNonOption( String arg )
{
public ParserState onNonOption(String arg) {
commandLine.addExtraValue(arg);
return allowMixedOptions ? new AfterFirstSubCommand(commandLine) : new AfterOptions(commandLine);
}
}
private class BeforeFirstSubCommand
extends OptionAwareParserState
{
private BeforeFirstSubCommand( ParsedCommandLine commandLine )
{
private class BeforeFirstSubCommand extends OptionAwareParserState {
private BeforeFirstSubCommand(ParsedCommandLine commandLine) {
super(commandLine);
}
@Override
public OptionParserState onStartOption( String arg, String option )
{
public OptionParserState onStartOption(String arg, String option) {
OptionString optionString = new OptionString(arg, option);
CommandLineOption commandLineOption = optionsByString.get(option);
if ( commandLineOption == null )
{
if ( allowUnknownOptions )
{
if (commandLineOption == null) {
if (allowUnknownOptions) {
return new UnknownOptionParserState(arg, commandLine, this);
}
else
{
throw new CommandLineArgumentException( String.format( "Unknown command-line option '%s'.",
optionString ) );
} else {
throw new CommandLineArgumentException(String.format("Unknown command-line option '%s'.", optionString));
}
}
return new KnownOptionParserState(optionString, commandLineOption, commandLine, this);
}
}
private class AfterFirstSubCommand
extends OptionAwareParserState
{
private AfterFirstSubCommand( ParsedCommandLine commandLine )
{
private class AfterFirstSubCommand extends OptionAwareParserState {
private AfterFirstSubCommand(ParsedCommandLine commandLine) {
super(commandLine);
}
@Override
public OptionParserState onStartOption( String arg, String option )
{
public OptionParserState onStartOption(String arg, String option) {
CommandLineOption commandLineOption = optionsByString.get(option);
if ( commandLineOption == null )
{
if (commandLineOption == null) {
return new UnknownOptionParserState(arg, commandLine, this);
}
return new KnownOptionParserState(new OptionString(arg, option), commandLineOption, commandLine, this);
}
}
private static class AfterOptions
extends ParserState
{
private static class AfterOptions extends ParserState {
private final ParsedCommandLine commandLine;
private AfterOptions( ParsedCommandLine commandLine )
{
private AfterOptions(ParsedCommandLine commandLine) {
this.commandLine = commandLine;
}
@Override
public boolean maybeStartOption( String arg )
{
public boolean maybeStartOption(String arg) {
return false;
}
@Override
public OptionParserState onStartOption( String arg, String option )
{
public OptionParserState onStartOption(String arg, String option) {
return new UnknownOptionParserState(arg, commandLine, this);
}
@Override
public ParserState onNonOption( String arg )
{
public ParserState onNonOption(String arg) {
commandLine.addExtraValue(arg);
return this;
}
}
private static class MissingOptionArgState
extends ParserState
{
private static class MissingOptionArgState extends ParserState {
private final OptionParserState option;
private MissingOptionArgState( OptionParserState option )
{
private MissingOptionArgState(OptionParserState option) {
this.option = option;
}
@Override
public boolean maybeStartOption( String arg )
{
public boolean maybeStartOption(String arg) {
return isOption(arg);
}
@Override
public OptionParserState onStartOption( String arg, String option )
{
public OptionParserState onStartOption(String arg, String option) {
return this.option.onComplete().onStartOption(arg, option);
}
@Override
public ParserState onNonOption( String arg )
{
public ParserState onNonOption(String arg) {
return option.onArgument(arg);
}
@Override
public void onCommandLineEnd()
{
public void onCommandLineEnd() {
option.onComplete();
}
}
private static abstract class OptionParserState
{
private static abstract class OptionParserState {
public abstract ParserState onStartNextArg();
public abstract ParserState onArgument(String argument);
@ -495,9 +396,7 @@ public class CommandLineParser
public abstract ParserState onComplete();
}
private class KnownOptionParserState
extends OptionParserState
{
private class KnownOptionParserState extends OptionParserState {
private final OptionString optionString;
private final CommandLineOption option;
@ -508,9 +407,7 @@ public class CommandLineParser
private final List<String> values = new ArrayList<String>();
private KnownOptionParserState( OptionString optionString, CommandLineOption option,
ParsedCommandLine commandLine, ParserState state )
{
private KnownOptionParserState(OptionString optionString, CommandLineOption option, ParsedCommandLine commandLine, ParserState state) {
this.optionString = optionString;
this.option = option;
this.commandLine = commandLine;
@ -518,68 +415,47 @@ public class CommandLineParser
}
@Override
public ParserState onArgument( String argument )
{
if ( !getHasArgument() )
{
throw new CommandLineArgumentException(
String.format( "Command-line option '%s' does not take an argument.",
optionString ) );
public ParserState onArgument(String argument) {
if (!getHasArgument()) {
throw new CommandLineArgumentException(String.format("Command-line option '%s' does not take an argument.", optionString));
}
if ( argument.length() == 0 )
{
throw new CommandLineArgumentException(
String.format( "An empty argument was provided for command-line option '%s'.",
optionString ) );
if (argument.length() == 0) {
throw new CommandLineArgumentException(String.format("An empty argument was provided for command-line option '%s'.", optionString));
}
values.add(argument);
return onComplete();
}
@Override
public ParserState onStartNextArg()
{
if ( option.getAllowsArguments() && values.isEmpty() )
{
public ParserState onStartNextArg() {
if (option.getAllowsArguments() && values.isEmpty()) {
return new MissingOptionArgState(this);
}
return onComplete();
}
@Override
public boolean getHasArgument()
{
public boolean getHasArgument() {
return option.getAllowsArguments();
}
@Override
public ParserState onComplete()
{
if ( getHasArgument() && values.isEmpty() )
{
throw new CommandLineArgumentException(
String.format( "No argument was provided for command-line option '%s'.",
optionString ) );
public ParserState onComplete() {
if (getHasArgument() && values.isEmpty()) {
throw new CommandLineArgumentException(String.format("No argument was provided for command-line option '%s'.", optionString));
}
ParsedCommandLineOption parsedOption = commandLine.addOption(optionString.option, option);
if ( values.size() + parsedOption.getValues().size() > 1 && !option.getAllowsMultipleArguments() )
{
throw new CommandLineArgumentException(
String.format( "Multiple arguments were provided for command-line option '%s'.",
optionString ) );
if (values.size() + parsedOption.getValues().size() > 1 && !option.getAllowsMultipleArguments()) {
throw new CommandLineArgumentException(String.format("Multiple arguments were provided for command-line option '%s'.", optionString));
}
for ( String value : values )
{
for (String value : values) {
parsedOption.addArgument(value);
}
if ( option.getDeprecationWarning() != null )
{
deprecationPrinter.println( "The " + optionString + " option is deprecated - "
+ option.getDeprecationWarning() );
if (option.getDeprecationWarning() != null) {
deprecationPrinter.println("The " + optionString + " option is deprecated - " + option.getDeprecationWarning());
}
if ( option.getSubcommand() != null )
{
if (option.getSubcommand() != null) {
return state.onNonOption(option.getSubcommand());
}
@ -587,86 +463,67 @@ public class CommandLineParser
}
}
private static class UnknownOptionParserState
extends OptionParserState
{
private static class UnknownOptionParserState extends OptionParserState {
private final ParserState state;
private final String arg;
private final ParsedCommandLine commandLine;
private UnknownOptionParserState( String arg, ParsedCommandLine commandLine, ParserState state )
{
private UnknownOptionParserState(String arg, ParsedCommandLine commandLine, ParserState state) {
this.arg = arg;
this.commandLine = commandLine;
this.state = state;
}
@Override
public boolean getHasArgument()
{
public boolean getHasArgument() {
return true;
}
@Override
public ParserState onStartNextArg()
{
public ParserState onStartNextArg() {
return onComplete();
}
@Override
public ParserState onArgument( String argument )
{
public ParserState onArgument(String argument) {
return onComplete();
}
@Override
public ParserState onComplete()
{
public ParserState onComplete() {
commandLine.addExtraValue(arg);
return state;
}
}
private static final class OptionComparator
implements Comparator<CommandLineOption>
{
public int compare( CommandLineOption option1, CommandLineOption option2 )
{
private static final class OptionComparator implements Comparator<CommandLineOption> {
public int compare(CommandLineOption option1, CommandLineOption option2) {
String min1 = Collections.min(option1.getOptions(), new OptionStringComparator());
String min2 = Collections.min(option2.getOptions(), new OptionStringComparator());
return new CaseInsensitiveStringComparator().compare(min1, min2);
}
}
private static final class CaseInsensitiveStringComparator
implements Comparator<String>
{
public int compare( String option1, String option2 )
{
private static final class CaseInsensitiveStringComparator implements Comparator<String> {
public int compare(String option1, String option2) {
int diff = option1.compareToIgnoreCase(option2);
if ( diff != 0 )
{
if (diff != 0) {
return diff;
}
return option1.compareTo(option2);
}
}
private static final class OptionStringComparator
implements Comparator<String>
{
public int compare( String option1, String option2 )
{
private static final class OptionStringComparator implements Comparator<String> {
public int compare(String option1, String option2) {
boolean short1 = option1.length() == 1;
boolean short2 = option2.length() == 1;
if ( short1 && !short2 )
{
if (short1 && !short2) {
return -1;
}
if ( !short1 && short2 )
{
if (!short1 && short2) {
return 1;
}
return new CaseInsensitiveStringComparator().compare(option1, option2);

View File

@ -23,41 +23,32 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
public class ParsedCommandLine
{
public class ParsedCommandLine {
private final Map<String, ParsedCommandLineOption> optionsByString = new HashMap<String, ParsedCommandLineOption>();
private final Set<String> presentOptions = new HashSet<String>();
private final List<String> extraArguments = new ArrayList<String>();
ParsedCommandLine( Iterable<CommandLineOption> options )
{
for ( CommandLineOption option : options )
{
ParsedCommandLine(Iterable<CommandLineOption> options) {
for (CommandLineOption option : options) {
ParsedCommandLineOption parsedOption = new ParsedCommandLineOption();
for ( String optionStr : option.getOptions() )
{
for (String optionStr : option.getOptions()) {
optionsByString.put(optionStr, parsedOption);
}
}
}
@Override
public String toString()
{
return String.format( "options: %s, extraArguments: %s", quoteAndJoin( presentOptions ),
quoteAndJoin( extraArguments ) );
public String toString() {
return String.format("options: %s, extraArguments: %s", quoteAndJoin(presentOptions), quoteAndJoin(extraArguments));
}
private String quoteAndJoin( Iterable<String> strings )
{
private String quoteAndJoin(Iterable<String> strings) {
StringBuilder output = new StringBuilder();
boolean isFirst = true;
for ( String string : strings )
{
if ( !isFirst )
{
for (String string : strings) {
if (!isFirst) {
output.append(", ");
}
output.append("'");
@ -74,8 +65,7 @@ public class ParsedCommandLine
* @param option The option, without the '-' or '--' prefix.
* @return true if the option is present.
*/
public boolean hasOption( String option )
{
public boolean hasOption(String option) {
option(option);
return presentOptions.contains(option);
}
@ -86,12 +76,9 @@ public class ParsedCommandLine
* @param logLevelOptions the options to check
* @return true if any of the passed options is present
*/
public boolean hasAnyOption( Collection<String> logLevelOptions )
{
for ( String option : logLevelOptions )
{
if ( hasOption( option ) )
{
public boolean hasAnyOption(Collection<String> logLevelOptions) {
for (String option : logLevelOptions) {
if (hasOption(option)) {
return true;
}
}
@ -104,28 +91,23 @@ public class ParsedCommandLine
* @param option The option, without the '-' or '--' prefix.
* @return The option. never returns null.
*/
public ParsedCommandLineOption option( String option )
{
public ParsedCommandLineOption option(String option) {
ParsedCommandLineOption parsedOption = optionsByString.get(option);
if ( parsedOption == null )
{
if (parsedOption == null) {
throw new IllegalArgumentException(String.format("Option '%s' not defined.", option));
}
return parsedOption;
}
public List<String> getExtraArguments()
{
public List<String> getExtraArguments() {
return extraArguments;
}
void addExtraValue( String value )
{
void addExtraValue(String value) {
extraArguments.add(value);
}
ParsedCommandLineOption addOption( String optionStr, CommandLineOption option )
{
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
{
public class ParsedCommandLineOption {
private final List<String> values = new ArrayList<String>();
public String getValue()
{
if ( !hasValue() )
{
public String getValue() {
if (!hasValue()) {
throw new IllegalStateException("Option does not have any value.");
}
if ( values.size() > 1 )
{
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;
}
public void addArgument( String argument )
{
public void addArgument(String argument) {
values.add(argument);
}
public boolean hasValue()
{
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()
{
protected String getPropertyOption() {
return "P";
}
@Override
protected String getPropertyOptionDetailed()
{
protected String getPropertyOptionDetailed() {
return "project-prop";
}
@Override
protected String getPropertyOptionDescription()
{
protected String getPropertyOptionDescription() {
return "Set project property for the build script (e.g. -Pmyprop=myvalue).";
}
}

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()
{
protected String getPropertyOption() {
return "D";
}
@Override
protected String getPropertyOptionDetailed()
{
protected String getPropertyOptionDetailed() {
return "system-prop";
}
@Override
protected String getPropertyOptionDescription()
{
protected String getPropertyOptionDescription() {
return "Set system property of the JVM (e.g. -Dmyprop=myvalue).";
}
}

View File

@ -9,8 +9,7 @@ import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
public class DownloaderTest
{
public class DownloaderTest {
private DefaultDownloader download;
@ -25,9 +24,7 @@ public class DownloaderTest
private File remoteFile;
@Before
public void setUp()
throws Exception
{
public void setUp() throws Exception {
download = new DefaultDownloader("mvnw", "aVersion");
testDir = new File("target/test-files/DownloadTest");
rootDir = new File(testDir, "root");
@ -38,9 +35,7 @@ public class DownloaderTest
}
@Test
public void testDownload()
throws Exception
{
public void testDownload() throws Exception {
assert !downloadFile.exists();
download.download(sourceRoot, downloadFile);
assert downloadFile.exists();

View File

@ -16,8 +16,7 @@ import org.junit.Test;
/**
* @author Hans Dockter
*/
public class InstallerTest
{
public class InstallerTest {
private File testDir = new File("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis());
private Installer install;
@ -47,9 +46,7 @@ public class InstallerTest
private PathAssembler.LocalDistribution localDistribution;
@Before
public void setup()
throws Exception
{
public void setup() throws Exception {
testDir.mkdirs();
@ -78,9 +75,7 @@ public class InstallerTest
}
private void createTestZip( File zipDestination )
throws Exception
{
private void createTestZip(File zipDestination) throws Exception {
File explodedZipDir = new File(testDir, "explodedZip");
explodedZipDir.mkdirs();
zipDestination.getParentFile().mkdirs();
@ -91,9 +86,7 @@ public class InstallerTest
zipTo(explodedZipDir, zipDestination);
}
public void testCreateDist()
throws Exception
{
public void testCreateDist() throws Exception {
File homeDir = install.createDist(configuration);
Assert.assertEquals(mavenHomeDir, homeDir);
@ -110,9 +103,7 @@ public class InstallerTest
}
@Test
public void testCreateDistWithExistingDistribution()
throws Exception
{
public void testCreateDistWithExistingDistribution() throws Exception {
FileUtils.touch(zipDestination);
mavenHomeDir.mkdirs();
@ -132,9 +123,7 @@ public class InstallerTest
}
@Test
public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue()
throws Exception
{
public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue() throws Exception {
createTestZip(zipDestination);
mavenHomeDir.mkdirs();
@ -155,9 +144,7 @@ public class InstallerTest
}
@Test
public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue()
throws Exception
{
public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue() throws Exception {
createTestZip(zipDestination);
File garbage = new File(mavenHomeDir, "garbage");
@ -180,8 +167,7 @@ public class InstallerTest
// 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.setBasedir(directoryToZip);
zip.setDestFile(zipFile);

View File

@ -33,8 +33,7 @@ import org.junit.Test;
/**
* @author Hans Dockter
*/
public class PathAssemblerTest
{
public class PathAssemblerTest {
public static final String TEST_MAVEN_USER_HOME = "someUserHome";
private PathAssembler pathAssembler = new PathAssembler(new File(TEST_MAVEN_USER_HOME));
@ -42,8 +41,7 @@ public class PathAssemblerTest
final WrapperConfiguration configuration = new WrapperConfiguration();
@Before
public void setup()
{
public void setup() {
configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
configuration.setDistributionPath("somePath");
configuration.setZipBase(PathAssembler.MAVEN_USER_HOME_STRING);
@ -51,9 +49,7 @@ public class PathAssemblerTest
}
@Test
public void distributionDirWithMavenUserHomeBase()
throws Exception
{
public void distributionDirWithMavenUserHomeBase() throws Exception {
configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip"));
File distributionDir = pathAssembler.getDistribution(configuration).getDistributionDir();
@ -62,9 +58,7 @@ public class PathAssemblerTest
}
@Test
public void distributionDirWithProjectBase()
throws Exception
{
public void distributionDirWithProjectBase() throws Exception {
configuration.setDistributionBase(PathAssembler.PROJECT_STRING);
configuration.setDistribution(new URI("http://server/dist/maven-0.9-bin.zip"));
@ -74,40 +68,30 @@ public class PathAssemblerTest
}
@Test
public void distributionDirWithUnknownBase()
throws Exception
{
public void distributionDirWithUnknownBase() throws Exception {
configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
configuration.setDistributionBase("unknownBase");
try
{
try {
pathAssembler.getDistribution(configuration);
fail();
}
catch ( RuntimeException e )
{
} catch (RuntimeException e) {
assertEquals("Base: unknownBase is unknown", e.getMessage());
}
}
@Test
public void distZipWithMavenUserHomeBase()
throws Exception
{
public void distZipWithMavenUserHomeBase() throws Exception {
configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
File dist = pathAssembler.getDistribution(configuration).getZipFile();
assertThat(dist.getName(), equalTo("maven-1.0.zip"));
assertThat(dist.getParentFile().getName(), matchesRegexp("[a-z0-9]+"));
assertThat( dist.getParentFile().getParentFile(),
equalTo( file( TEST_MAVEN_USER_HOME + "/somePath/maven-1.0" ) ) );
assertThat(dist.getParentFile().getParentFile(), equalTo(file(TEST_MAVEN_USER_HOME + "/somePath/maven-1.0")));
}
@Test
public void distZipWithProjectBase()
throws Exception
{
public void distZipWithProjectBase() throws Exception {
configuration.setZipBase(PathAssembler.PROJECT_STRING);
configuration.setDistribution(new URI("http://server/dist/maven-1.0.zip"));
@ -117,27 +101,21 @@ public class PathAssemblerTest
assertThat(dist.getParentFile().getParentFile(), equalTo(file(currentDirPath() + "/somePath/maven-1.0")));
}
private File file( String path )
{
private File file(String path) {
return new File(path);
}
private String currentDirPath()
{
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 )
{
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 )
{
public void describeTo(Description description) {
description.appendText("a CharSequence that matches regexp ").appendValue(pattern);
}
};

View File

@ -13,21 +13,17 @@ 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");
@Before
public void setupTempDir()
{
public void setupTempDir() {
tmpDir.mkdirs();
}
@Test
public void testParsePropertiesFile()
throws Exception
{
public void testParsePropertiesFile() throws Exception {
File propFile = new File(tmpDir, "props");
Properties props = new Properties();
props.put("a", "b");
@ -35,13 +31,10 @@ public class SystemPropertiesHandlerTest
props.put("systemProp.", "e");
FileOutputStream fos = null;
try
{
try {
fos = new FileOutputStream(propFile);
props.store(fos, "");
}
finally
{
} finally {
IOUtils.closeQuietly(fos);
}
@ -52,8 +45,7 @@ public class SystemPropertiesHandlerTest
}
@Test
public void ifNoPropertyFileExistShouldReturnEmptyMap()
{
public void ifNoPropertyFileExistShouldReturnEmptyMap() {
Map<String, String> expected = new HashMap<String, String>();
assertThat(SystemPropertiesHandler.getSystemProperties(new File(tmpDir, "unknown")), equalTo(expected));
}

View File

@ -15,8 +15,7 @@ import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class WrapperExecutorTest
{
public class WrapperExecutorTest {
private final Installer install;
private final BootstrapMainStarter start;
@ -29,9 +28,7 @@ public class WrapperExecutorTest
private File mockInstallDir = new File(testDir, "mock-dir");
public WrapperExecutorTest()
throws Exception
{
public WrapperExecutorTest() throws Exception {
install = mock(Installer.class);
when(install.createDist(Mockito.any(WrapperConfiguration.class))).thenReturn(mockInstallDir);
start = mock(BootstrapMainStarter.class);
@ -50,9 +47,7 @@ public class WrapperExecutorTest
}
@Test
public void loadWrapperMetadataFromFile()
throws Exception
{
public void loadWrapperMetadataFromFile() throws Exception {
WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
Assert.assertEquals(new URI("http://server/test/maven.zip"), wrapper.getDistribution());
@ -64,9 +59,7 @@ public class WrapperExecutorTest
}
@Test
public void loadWrapperMetadataFromDirectory()
throws Exception
{
public void loadWrapperMetadataFromDirectory() throws Exception {
WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(testDir, System.out);
Assert.assertEquals(new URI("http://server/test/maven.zip"), wrapper.getDistribution());
@ -78,9 +71,7 @@ public class WrapperExecutorTest
}
@Test
public void useDefaultMetadataNoProeprtiesFile()
throws Exception
{
public void useDefaultMetadataNoProeprtiesFile() throws Exception {
WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(new File(testDir, "unknown"), System.out);
Assert.assertNull(wrapper.getDistribution());
@ -92,9 +83,7 @@ public class WrapperExecutorTest
}
@Test
public void propertiesFileOnlyContainsDistURL()
throws Exception
{
public void propertiesFileOnlyContainsDistURL() throws Exception {
properties = new Properties();
properties.put("distributionUrl", "http://server/test/maven.zip");
@ -111,57 +100,47 @@ public class WrapperExecutorTest
}
@Test
public void executeInstallAndLaunch()
throws Exception
{
public void executeInstallAndLaunch() throws Exception {
WrapperExecutor wrapper = WrapperExecutor.forProjectDirectory(propertiesFile, System.out);
wrapper.execute( new String[] { "arg" }, install, start );
wrapper.execute(new String[] {
"arg"
}, install, start);
verify(install).createDist(Mockito.any(WrapperConfiguration.class));
verify( start ).start( new String[] { "arg" }, mockInstallDir );
verify(start).start(new String[] {
"arg"
}, mockInstallDir);
}
@Test()
public void failWhenDistNotSetInProperties()
throws Exception
{
public void failWhenDistNotSetInProperties() throws Exception {
properties = new Properties();
writePropertiesFile(properties, propertiesFile, "header");
try
{
try {
WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
Assert.fail("Expected RuntimeException");
}
catch ( RuntimeException e )
{
} 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() );
Assert.assertEquals("No value with key 'distributionUrl' specified in wrapper properties file '" + propertiesFile + "'.", e.getCause().getMessage());
}
}
@Test
public void failWhenPropertiesFileDoesNotExist()
{
public void failWhenPropertiesFileDoesNotExist() {
propertiesFile = new File(testDir, "unknown.properties");
try
{
try {
WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
Assert.fail("Expected RuntimeException");
}
catch ( RuntimeException e )
{
} catch (RuntimeException e) {
Assert.assertEquals("Wrapper properties file '" + propertiesFile + "' does not exist.", e.getMessage());
}
}
@Test
public void testRelativeDistUrl()
throws Exception
{
public void testRelativeDistUrl() throws Exception {
properties = new Properties();
properties.put("distributionUrl", "some/relative/url/to/bin.zip");
@ -172,20 +151,15 @@ public class WrapperExecutorTest
Assert.assertTrue(wrapper.getDistribution().getSchemeSpecificPart().endsWith("some/relative/url/to/bin.zip"));
}
private void writePropertiesFile( Properties properties, File propertiesFile, String message )
throws Exception
{
private void writePropertiesFile(Properties properties, File propertiesFile, String message) throws Exception {
propertiesFile.getParentFile().mkdirs();
OutputStream outStream = null;
try
{
try {
outStream = new FileOutputStream(propertiesFile);
properties.store(outStream, message);
}
finally
{
} finally {
IOUtils.closeQuietly(outStream);
}
}