/******************************************************************************* * Copyright (c) 2000,2002 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM - Initial API and implementation ******************************************************************************/ package org.eclipse.core.launcher; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Startup class for Eclipse. Creates a class loader using * supplied URL of platform installation, loads and calls * the Eclipse Boot Loader. The startup arguments are as follows: *
BootLoader
which can be used to start
* up and run the platform.
*
* @return the new boot loader
* @param path search path for the BootLoader
*/
public Class getBootLoader(URL[] path) throws Exception {
URLClassLoader loader = new URLClassLoader(path, null);
return loader.loadClass(BOOTLOADER);
}
/**
* Returns the URL
-based class path describing where the boot classes
* are located when running in development mode.
*
* @return the url-based class path
* @param base the base location
* @exception MalformedURLException if a problem occurs computing the class path
*/
protected URL[] getDevPath(URL base) throws MalformedURLException {
URL url;
String devBase = base.toExternalForm();
if (!inDevelopmentMode) {
url = new URL(devBase + BOOTJAR);
return new URL[] {url};
}
String[] locations = getArrayFromList(devClassPath);
ArrayList result = new ArrayList(locations.length);
for (int i = 0; i < locations.length; i++) {
String spec = devBase + locations[i];
char lastChar = spec.charAt(spec.length() - 1);
if ((spec.endsWith(".jar") || (lastChar == '/' || lastChar == '\\'))) //$NON-NLS-1$
url = new URL (spec);
else
url = new URL(spec + "/"); //$NON-NLS-1$
//make sure URL exists before adding to path
if (new java.io.File(url.getFile()).exists())
result.add(url);
}
url = new URL(devBase + BOOTJAR);
if (new java.io.File(url.getFile()).exists())
result.add(url);
return (URL[])result.toArray(new URL[result.size()]);
}
/**
* Returns the URL
-based class path describing where the boot classes are located.
*
* @return the url-based class path
* @param base the base location
* @exception MalformedURLException if a problem occurs computing the class path
*/
protected URL[] getBootPath(String base) throws MalformedURLException {
URL url = null;
// if the given location is not null, assume it is correct and use it.
if (base != null) {
url = new URL(base);
if (debug)
System.out.println("Boot URL: " + url.toExternalForm()); //$NON-NLS-1$
return new URL[] {url};
}
// search for boot in root location
URL[] result = null;
url = new URL(rootLocation);
String path = url.getFile();
path = searchForBoot(path);
// add on any dev path elements
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
result = getDevPath(url);
if (debug) {
System.out.println("Boot URL:"); //$NON-NLS-1$
for (int i = 0; i < result.length; i++)
System.out.println(" " + result[i].toExternalForm()); //$NON-NLS-1$
}
return result;
}
/**
* Searches for a boot directory starting in the "plugins" subdirectory
* of the given location. If one is found then this location is returned;
* otherwise an exception is thrown.
*
* @return the location where boot directory was found
* @param start the location to begin searching at
*/
protected String searchForBoot(String start) {
FileFilter filter = new FileFilter() {
public boolean accept(File candidate) {
return candidate.isDirectory() &&
(candidate.getName().equals(PI_BOOT)
|| candidate.getName().startsWith(PI_BOOT + "_")); //$NON-NLS-1$
}
};
File[] boots = new File(start, "plugins").listFiles(filter); //$NON-NLS-1$
if (boots == null)
throw new RuntimeException("Could not find bootstrap code. Check location of boot plug-in or specify -boot."); //$NON-NLS-1$
String result = null;
Object maxVersion = null;
for (int i = 0; i < boots.length; i++) {
String name = boots[i].getName();
int index = name.indexOf('_');
String version;
Object currentVersion;
if (index == -1)
version = ""; //$NON-NLS-1$ // Note: directory with version suffix is always > than directory without version suffix
else
version = name.substring(index + 1);
currentVersion = getVersionElements(version);
if (maxVersion == null) {
result = boots[i].getAbsolutePath();
maxVersion = currentVersion;
} else {
if (compareVersion((Object[])maxVersion, (Object[])currentVersion) < 0) {
result = boots[i].getAbsolutePath();
maxVersion = currentVersion;
}
}
}
if (result == null)
throw new RuntimeException("Could not find bootstrap code. Check location of boot plug-in or specify -boot."); //$NON-NLS-1$
return result.replace(File.separatorChar, '/') + "/"; //$NON-NLS-1$
}
/**
* Compares version strings.
* @return result of comparison, as integer;
* <0
if left < right;
* 0
if left == right;
* >0
if left > right;
*/
private int compareVersion(Object[] left, Object[] right) {
int result = ((Integer)left[0]).compareTo((Integer)right[0]); // compare major
if (result != 0)
return result;
result = ((Integer)left[1]).compareTo((Integer)right[1]); // compare minor
if (result != 0)
return result;
result = ((Integer)left[2]).compareTo((Integer)right[2]); // compare service
if (result != 0)
return result;
return ((String)left[3]).compareTo((String)right[3]); // compare qualifier
}
/**
* Do a quick parse of version identifier so its elements can be correctly compared.
* If we are unable to parse the full version, remaining elements are initialized
* with suitable defaults.
* @return an array of size 4; first three elements are of type Integer (representing
* major, minor and service) and the fourth element is of type String (representing
* qualifier). Note, that returning anything else will cause exceptions in the caller.
*/
private Object[] getVersionElements(String version) {
Object[] result = {new Integer(0), new Integer(0), new Integer(0), ""}; //$NON-NLS-1$
StringTokenizer t = new StringTokenizer(version, "."); //$NON-NLS-1$
String token;
int i = 0;
while(t.hasMoreTokens() && i<4) {
token = t.nextToken();
if (i<3) {
// major, minor or service ... numeric values
try {
result[i++] = new Integer(token);
} catch(Exception e) {
// invalid number format - use default numbers (0) for the rest
break;
}
} else {
// qualifier ... string value
result[i++] = token;
}
}
return result;
}
/**
* Runs the platform with the given arguments. The arguments must identify
* an application to run (e.g., -application com.example.application
).
* After running the application System.exit(N)
is executed.
* The value of N is derived from the value returned from running the application.
* If the application's return value is an Integer
, N is this value.
* In all other cases, N = 0.
*
* Clients wishing to run the platform without a following System.exit
* call should use run()
.
*
* @see #run
*
* @param args the command line arguments
*/
public static void main(String[] args) {
Object result = null;
arguments = args;
// Check to see if we are running with a compatible VM.
// If not, then return exit code "14" which will be recognized
// by the executable and an appropriate message will be displayed
// to the user.
if (!isCompatible())
System.exit(14);
// Check to see if there is already a platform running in
// this workspace. If there is, then return an exit code of "15" which
// will be recognized by the executable and an appropriate message
// will be displayed to the user.
if (isAlreadyRunning())
System.exit(15);
Main launcher = new Main();
try {
result = launcher.run(args);
} catch (Throwable e) {
// try and take down the splash screen.
launcher.takeDownSplash();
log("Exception launching the Eclipse Platform:"); //$NON-NLS-1$
log(e);
// Return "unlucky" 13 as the exit code. The executable will recognize
// this constant and display a message to the user telling them that
// there is information in their log file.
System.exit(13);
}
int exitCode = result instanceof Integer ? ((Integer) result).intValue() : 0;
System.exit(exitCode);
}
/**
* Runs this launcher with the arguments specified in the given string.
*
* @param argString the arguments string
* @exception Exception thrown if a problem occurs during launching
*/
public static void main(String argString) throws Exception {
Vector list = new Vector(5);
for (StringTokenizer tokens = new StringTokenizer(argString, " "); tokens.hasMoreElements();) //$NON-NLS-1$
list.addElement((String) tokens.nextElement());
main((String[]) list.toArray(new String[list.size()]));
}
/**
* Processes the command line arguments
*
* @return the arguments to pass through to the launched application
* @param args the command line arguments
*/
protected String[] processCommandLine(String[] args) throws Exception {
int[] configArgs = new int[100];
configArgs[0] = -1; // need to initialize the first element to something that could not be an index.
int configArgIndex = 0;
for (int i = 0; i < args.length; i++) {
boolean found = false;
// check for args without parameters (i.e., a flag arg)
// check if debug should be enabled for the entire platform
if (args[i].equalsIgnoreCase(DEBUG)) {
debug = true;
// passed thru this arg (i.e., do not set found = true
continue;
}
// check if this is initialization pass
if (args[i].equalsIgnoreCase(INITIALIZE)) {
cmdInitialize = true;
// passed thru this arg (i.e., do not set found = true
continue;
}
// check if development mode should be enabled for the entire platform
// If this is the last arg or there is a following arg (i.e., arg+1 has a leading -),
// simply enable development mode. Otherwise, assume that that the following arg is
// actually some additional development time class path entries. This will be processed below.
if (args[i].equalsIgnoreCase(DEV) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$
inDevelopmentMode = true;
// do not mark the arg as found so it will be passed through
continue;
}
// done checking for args. Remember where an arg was found
if (found) {
configArgs[configArgIndex++] = i;
continue;
}
// check for args with parameters. If we are at the last argument or if the next one
// has a '-' as the first character, then we can't have an arg with a parm so continue.
if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$
continue;
String arg = args[++i];
// look for the laucher to run
if (args[i - 1].equalsIgnoreCase(BOOT)) {
bootLocation = arg;
found = true;
}
// look explicitly set install root
if (args[i - 1].equalsIgnoreCase(INSTALL)) {
rootLocation = arg;
found = true;
}
// look for the development mode and class path entries.
if (args[i - 1].equalsIgnoreCase(DEV)) {
inDevelopmentMode = true;
devClassPath = arg;
continue;
}
// look for the location of workspace
if (args[i - 1].equalsIgnoreCase(DATA)) {
baseLocation = arg;
continue; // pass the arg on
}
// look for the application to run
if (args[i - 1].equalsIgnoreCase(APPLICATION)) {
application = arg;
found = true;
}
// look for the feature to run
if (args[i - 1].equalsIgnoreCase(FEATURE)) {
feature = arg;
continue; // pass the arg on [20063]
}
// look for the configuration to use
if (args[i - 1].equalsIgnoreCase(CONFIGURATION)) {
configuration = arg;
// we mark -configuration for removal. It will be
// reinserted after we determine the actual URL of
// the configuration file to use.
found = true;
}
// look for token to use to show the splash screen
if (args[i - 1].equalsIgnoreCase(SHOWSPLASH)) {
showSplash = arg;
found = true;
}
// look for token to use to end the splash screen
if (args[i - 1].equalsIgnoreCase(ENDSPLASH)) {
endSplash = arg;
found = true;
}
// done checking for args. Remember where an arg was found
if (found) {
configArgs[configArgIndex++] = i - 1;
configArgs[configArgIndex++] = i;
}
}
// remove all the arguments consumed by this argument parsing
if (configArgIndex == 0)
return args;
String[] passThruArgs = new String[args.length - configArgIndex];
configArgIndex = 0;
int j = 0;
for (int i = 0; i < args.length; i++) {
if (i == configArgs[configArgIndex])
configArgIndex++;
else
passThruArgs[j++] = args[i];
}
return passThruArgs;
}
/**
* Runs the application to be launched.
*
* @return the return value from the launched application
* @param args the arguments to pass to the application
* @exception thrown if a problem occurs during launching
*/
public Object run(String[] args) throws Exception {
String[] passThruArgs = processCommandLine(args);
passThruArgs = processConfiguration(passThruArgs);
return basicRun(passThruArgs);
}
/*
* After the command line arguments have been processed, we try
* to locate and load the platform configuration file. It contains
* information maintained by the install/ update support. In
* particular, the following are needed at this point
* in the startup sequence:
* -> if -boot was not specified, which boot.jar to load
* BootLoader from (original core.boot plugin may have been updated)
* -> if -feature was not specified, what is the default feature
* (product packagers can set the default)
* -> if we were requested to put up the splash (-showsplash
* was specified), which one (based on defaulted or
* specified feature information)
* Note, that if we can't find the platform configuration file,
* or it does not contain the information we are looking for,
* the startup support ends up computing "reasonable" defaults
* as before (based on relative locations within the file system)
*/
private String[] processConfiguration(String[] passThruArgs) throws MalformedURLException {
// get install root location, if not specified
if (rootLocation == null)
rootLocation = getRootURL().toExternalForm();
// attempt to locate configuration file
URL configURL = null;
if (configuration != null && !configuration.trim().equals("")) { //$NON-NLS-1$
configuration = configuration.replace(File.separatorChar, '/');
if (configuration.equalsIgnoreCase(ARG_USER_DIR)) {
// configuration is in current working directory
String tmp = System.getProperty("user.dir"); //$NON-NLS-1$
if (!tmp.endsWith(File.separator))
tmp += File.separator;
configURL = new URL("file:" + tmp.replace(File.separatorChar,'/') + CONFIG_FILE); //$NON-NLS-1$
} else if(configuration.endsWith("/")) { //$NON-NLS-1$
// configuration specified as directory URL
configURL = new URL(configuration + CONFIG_FILE);
} else {
// configuration specified down to a file
configURL = new URL(configuration);
}
} else {
// configuration not specified - defer to BootLoader
}
// load configuration
loadConfiguration(configURL);
// get boot url, if none was specified
if (bootLocation == null) {
String urlString = loadAttribute(props, CFG_CORE_BOOT, null);
if (urlString != null) {
try {
urlString = resolve(urlString);
URL bootDir = new URL(urlString);
URL bootURL = new URL(bootDir, BOOTJAR);
if (bootDir.getProtocol().equals("file")) { //$NON-NLS-1$
File jar = new File(bootURL.getFile());
if (jar.exists())
// verify boot dir exists
bootLocation = bootURL.toExternalForm();
else
// Somebody turned the tables on us. The info in
// platform.cfg is stale, or the workspace is being used
// with a new install. Do default search for boot and force
// "first use" processing (optimistic reconciliation)
cmdFirstUse = true;
} else
bootLocation = bootURL.toExternalForm();
} catch(MalformedURLException e) {
// continue ... will do default search for boot
}
}
}
// reconstruct command line arguments for configuration elements
// (-boot and -application are not passed to BootLoader)
if (configURL == null && rootLocation == null)
return passThruArgs;
ArrayList args = new ArrayList(Arrays.asList(passThruArgs));
if (configURL != null) {
args.add(CONFIGURATION);
args.add(decode(configURL.toExternalForm()));
}
if (cmdFirstUse) {
args.add(FIRST_USE);
}
// pass root location downstream
if (rootLocation != null) {
args.add(INSTALL);
args.add(rootLocation);
}
return (String[])args.toArray(new String[0]);
}
/**
* Returns url of the location this class was loaded from
*/
private URL getRootURL() throws MalformedURLException {
if (rootLocation != null)
return new URL(rootLocation);
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
String path = decode(url.getFile());
path = new File(path).getAbsolutePath().replace(File.separatorChar,'/');
if (path.endsWith(".jar")) //$NON-NLS-1$
path = path.substring(0, path.lastIndexOf("/")+1); //$NON-NLS-1$
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
rootLocation = url.toExternalForm();
return url;
}
/*
* Load the configuration file. If not specified, default to the workspace
*/
private void loadConfiguration(URL url) {
if (url == null) {
// configuration URL was not specified ..... search
String base = baseLocation;
if (base == null) {
// determine default workspace
base = System.getProperty("user.dir"); //$NON-NLS-1$
if (!base.endsWith(File.separator))
base += File.separator;
base += "workspace" + File.separator; //$NON-NLS-1$
} else {
base = base.replace('/',File.separatorChar);
}
if (!base.endsWith(File.separator))
base += File.separator;
File cfg = null;
try {
// first look for configuration in base location (workspace or as specified)
cfg = new File(base + ".metadata" + File.separator + ".config" + File.separator + CONFIG_FILE); //$NON-NLS-1$ //$NON-NLS-2$
url = new URL("file", null, 0, cfg.getAbsolutePath()); //$NON-NLS-1$
props = loadProperties(url);
if (debug)
System.out.println("Startup: using configuration " + url.toString()); //$NON-NLS-1$
return; // we're done looking
} catch(IOException e) {
// continue ...
}
try {
// look for configuration in install root (set up by -initialize)
String install = getRootURL().getFile().replace('/',File.separatorChar);
if (!install.endsWith(File.separator))
install += File.separator;
cfg = new File(install + ".config" + File.separator + CONFIG_FILE); //$NON-NLS-1$
url = new URL("file", null, 0, cfg.getAbsolutePath()); //$NON-NLS-1$
props = loadProperties(url);
if (debug)
System.out.println("Startup: using configuration " + url.toString()); //$NON-NLS-1$
} catch(IOException e) {
// continue ...
if (debug)
System.out.println("Startup: unable to load configuration\n" + e); //$NON-NLS-1$
}
} else {
try {
// configuration url was specified ... use it
props = loadProperties(url);
if (debug)
System.out.println("Startup: using configuration " + url.toString()); //$NON-NLS-1$
} catch(IOException e) {
// continue ...
if (debug)
System.out.println("Startup: unable to load configuration\n" + e); //$NON-NLS-1$
}
}
}
private Properties loadProperties(URL url) throws IOException {
// try to load saved configuration file (watch for failed prior save())
Properties props = null;
IOException originalException = null;
try {
props = load(url, null); // try to load config file
} catch(IOException e1) {
originalException = e1;
try {
props = load(url, CONFIG_FILE_TEMP_SUFFIX); // check for failures on save
} catch(IOException e2) {
try {
props = load(url, CONFIG_FILE_BAK_SUFFIX); // check for failures on save
} catch(IOException e3) {
throw originalException; // we tried, but no config here ...
}
}
}
return props;
}
/*
* Load the configuration
*/
private Properties load(URL url, String suffix) throws IOException {
// figure out what we will be loading
if (suffix != null && !suffix.equals("")) //$NON-NLS-1$
url = new URL(url.getProtocol(),url.getHost(),url.getPort(),url.getFile()+suffix);
// try to load saved configuration file
Properties props = new Properties();
InputStream is = null;
try {
is = url.openStream();
props.load(is);
// check to see if we have complete config file
if (!CFG_EOF.equals(props.getProperty(CFG_EOF))) {
throw new IOException();
}
} finally {
if (is!=null) {
try {
is.close();
} catch(IOException e) {
//ignore failure to close
}
}
}
// load feature index
if (props != null) {
String id = props.getProperty(CFG_FEATURE_ENTRY+".0."+CFG_FEATURE_ENTRY_ID); //$NON-NLS-1$
for (int i=1; id != null; i++) {
featureIndex.put(id, Integer.toString(i-1));
id = props.getProperty(CFG_FEATURE_ENTRY+"."+i+"."+CFG_FEATURE_ENTRY_ID); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return props;
}
/*
* Load a configuration attribute
*/
private String loadAttribute(Properties props, String name, String dflt) {
if (props == null)
return dflt;
String prop = props.getProperty(name);
if (prop == null)
return dflt;
else
return prop.trim();
}
/*
* Handle splash screen.
* We support 2 startup scenarios:
*
* (1) the executable launcher put up the splash screen. In that
* scenario we are invoked with -endsplash command which is
* fully formed to take down the splash screen
*
* (2) the executable launcher did not put up the splash screen,
* but invokes Eclipse with partially formed -showsplash command.
* In this scenario we determine which splash to display (based on
* feature information) and then call -showsplash command.
*
* In both scenarios we pass a handler (Runnable) to the platform.
* The handler is called as a result of the launched application calling
* Platform.endSplash(). In the first scenario this results in the
* -endsplash command being executed. In the second scenarios this
* results in the process created as a result of the -showsplash command
* being destroyed.
*
* @param bootPath search path for the boot plugin
*/
private void handleSplash(URL[] bootPath) {
// run without splash if we are initializing
if (cmdInitialize) {
showSplash = null;
endSplash = null;
return;
}
// if -endsplash is specified, use it and ignore any -showsplash command
if (endSplash != null) {
showSplash = null;
return;
}
// check if we are running without a splash screen
if (showSplash == null)
return;
// determine the splash path
String path = getSplashPath(bootPath);
if (debug && path != null) {
System.out.println("Startup: splash path = "+path); //$NON-NLS-1$
}
// Parse the showsplash command into its separate arguments.
// The command format is:
//