main(String[])
. This particular class uses several system
* properties to control features:
*
* Note: not all threads created by the target application are guaranteed to
* use this class. Target application's may bypass this class by creating a
* thread using the {@link Thread#Thread(ThreadGroup, String)} or other similar
* constructors.
*
* @author Patrick Luby
*/
public class ExitOnErrorThreadGroup extends ThreadGroup {
//------------------------------------------------------------ Constructors
/**
* Constructs a new thread group. The parent of this new group is the
* thread group of the currently running thread.
*
* @param name the name of the new thread group
*/
public ExitOnErrorThreadGroup(String name) {
super(name);
}
//----------------------------------------------------------------- Methods
/**
* Trap any uncaught {@link Error} other than {@link ThreadDeath} and exit.
*
* @param t the thread that is about to exit
* @param e the uncaught exception
*/
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof ThreadDeath)
return;
Launcher.error(e);
System.exit(1);
}
}
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/LaunchCommand.java 0100644 0001750 0001750 00000033235 10020100364 030102 0 ustar arnaud arnaud /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.launcher;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A class that represents the holds the various argument types that are used
* in a Java command. In addition, it holds many of the flags that are used
* by the {@link LaunchTask} class when executing a JVM process.
*
* @author Patrick Luby
*/
public class LaunchCommand {
//------------------------------------------------------------------ Fields
/**
* Cached appendOutput flag.
*/
private boolean appendOutput = false;
/**
* Cached classpath.
*/
private String classpath = null;
/**
* Cached debug flag.
*/
private boolean debug = false;
/**
* Cached displayMinimizedWindow flag.
*/
private boolean displayMinimizedWindow = false;
/**
* Cached disposeMinimizedWindow flag.
*/
private boolean disposeMinimizedWindow = true;
/**
* Cached failOnError flag.
*/
private boolean failOnError = true;
/**
* Cached main class name.
*/
private String mainClassName = null;
/**
* Cached minimizedWindowIcon.
*/
private File minimizedWindowIcon = null;
/**
* Cached minimizedWindowTitle.
*/
private String minimizedWindowTitle = null;
/**
* Cached output file.
*/
private File outputFile = null;
/**
* Cached print flag.
*/
private boolean print = false;
/**
* Cached requireTools flag.
*/
private boolean requireTools = false;
/**
* Cached redirect flag.
*/
private boolean redirect = false;
/**
* Cached arg elements
*/
private ArrayList args = null;
/**
* Cached jvmarg elements
*/
private ArrayList jvmArgs = null;
/**
* Cached sysproperty elements
*/
private HashMap sysProperties = null;
/**
* Cached useSystemIn flag.
*/
private boolean useSystemIn = true;
/**
* Cached waitForChild flag.
*/
private boolean waitForChild = true;
//----------------------------------------------------------------- Methods
/**
* Get the class name.
*
* @return the class to execute main(String[])
*/
public String getClassname() {
return mainClassName;
}
/**
* Get the classpath.
*
* @return the classpath
*/
public String getClasspath() {
return classpath;
}
/**
* Get the debug flag.
*
* @return the debug flag
*/
public boolean getDebug() {
return debug;
}
/**
* Get the displayMinimizedWindow flag.
*
* @return the displayMinimizedWindow flag
*/
public boolean getDisplayminimizedwindow() {
return displayMinimizedWindow;
}
/**
* Get the disposeMinimizedWindow flag.
*
* @return the disposeMinimizedWindow flag
*/
public boolean getDisposeminimizedwindow() {
return disposeMinimizedWindow;
}
/**
* Get the failOnError flag.
*
* @return the failOnError flag
*/
public boolean getFailonerror() {
return failOnError;
}
/**
* Get the title for the minimized window that will be displayed in the
* Windows taskbar.
*
* @return the title to set for any minimized window that is displayed
* in the Windows taskbar
*/
public String getMinimizedwindowtitle() {
return minimizedWindowTitle;
}
/**
* Get the icon file for the minimized window that will be displayed in the
* Windows taskbar.
*
* @return the icon file to use for any minimized window that is displayed
* in the Windows taskbar
*/
public File getMinimizedwindowicon() {
return minimizedWindowIcon;
}
/**
* Get the file that the child JVM's System.out and System.err will be
* redirected to.
*
* @return the File to redirect System.out and System.err to
*/
public File getOutput() {
return outputFile;
}
/**
* Get the appendOutput flag.
*
* @return the appendOutput flag
*/
public boolean getAppendoutput() {
return appendOutput;
}
/**
* Get the redirect flag.
*
* @return the redirect flag
*/
public boolean getRedirectoutput() {
return redirect;
}
/**
* Get the list of nested arg elements.
*
* @return the list of {@link String} objects
*/
public ArrayList getArgs() {
return args;
}
/**
* Get the list of nested jvmarg elements.
*
* @return the list of {@link String} objects
*/
public ArrayList getJvmargs() {
return jvmArgs;
}
/**
* Get the print flag.
*
* @return the print flag
*/
public boolean getPrint() {
return print;
}
/**
* Get the requireTools flag.
*
* @return the requireTools flag
*/
public boolean getRequiretools() {
return requireTools;
}
/**
* Get the list of nested sysproperty elements.
*
* @return the {@link String} objects
*/
public HashMap getSysproperties() {
return sysProperties;
}
/**
* Get the useSystemIn flag.
*
* @return the useSystemIn flag
*/
public boolean getUsesystemin() {
return useSystemIn;
}
/**
* Get the waitForChild flag.
*
* @return the waitForChild flag
*/
public boolean getWaitforchild() {
return waitForChild;
}
/**
* Set the print flag.
*
* @param print the print flag
*/
public void setPrint(boolean print) {
this.print = print;
}
/**
* Set the requireTools flag.
*
* @param requireTools the requireTools flag
*/
public void setRequiretools(boolean requireTools) {
this.requireTools = requireTools;
}
/**
* Set the useSystemIn flag. Setting this flag to false will cause this
* task to not read System.in. This will cause the child JVM to never
* receive any bytes when it reads System.in. Setting this flag to false
* is useful in some Unix environments where processes cannot be put in
* the background when they read System.in.
*
* @param useSystemIn the useSystemIn flag
*/
public void setUsesystemin(boolean useSystemIn) {
this.useSystemIn = useSystemIn;
}
/**
* Set the waitForChild flag. Setting this flag to true will cause this
* task to wait for the child JVM to finish executing before the task
* completes. Setting this flag to false will cause this task to complete
* immediately after it starts the execution of the child JVM. Setting it
* false emulates the "&" background operator in most Unix shells and is
* most of set to false when launching server or GUI applications.
*
* @param waitForChild the waitForChild flag
*/
public void setWaitforchild(boolean waitForChild) {
this.waitForChild = waitForChild;
}
/**
* Set the class name.
*
* @param mainClassName the class to execute main(String[])
*/
public void setClassname(String mainClassName) {
this.mainClassName = mainClassName;
}
/**
* Set the classpath.
*
* @param classpath the classpath
*/
public void setClasspath(String classpath) {
this.classpath = classpath;
}
/**
* Set the debug flag.
*
* @param debug the debug flag
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Set the displayMinimizedWindow flag. Note that this flag has no effect
* on non-Windows platforms. On Windows platform, setting this flag to true
* will cause a minimized window to be displayed in the Windows task bar
* while the child process is executing. This flag is usually set to true
* for server applications that also have their "waitForChild" attribute
* set to false via the {@link #setWaitforchild(boolean)} method.
*
* @param displayMinimizedWindow true if a minimized window should be
* displayed in the Windows task bar while the child process is executing
*/
public void setDisplayminimizedwindow(boolean displayMinimizedWindow) {
this.displayMinimizedWindow = displayMinimizedWindow;
}
/**
* Set the disposeMinimizedWindow flag. Note that this flag has no effect
* on non-Windows platforms. On Windows platform, setting this flag to true
* will cause any minimized window that is display by setting the
* "displayMinimizedWindow" attribute to true via the
* {@link #setDisplayminimizedwindow(boolean)} to be automatically
* disposed of when the child JVM's main(String[])
returns.
* This flag is normally used for applications that don't explicitly call
* {@link System#exit(int)}. If an application does not explicitly call
* {@link System#exit(int)}, an minimized windows need to be disposed of
* for the child JVM to exit.
*
* @param disposeMinimizedWindow true if a minimized window in the Windows
* taskbar should be automatically disposed of after the child JVM's
* main(String[])
returns
*/
public void setDisposeminimizedwindow(boolean disposeMinimizedWindow) {
this.disposeMinimizedWindow = disposeMinimizedWindow;
}
/**
* Set the failOnError flag.
*
* @param failOnError the failOnError flag
*/
public void setFailonerror(boolean failOnError) {
this.failOnError = failOnError;
}
/**
* Set the title for the minimized window that will be displayed in the
* Windows taskbar. Note that this property has no effect on non-Windows
* platforms.
*
* @param minimizedWindowTitle the title to set for any minimized window
* that is displayed in the Windows taskbar
*/
public void setMinimizedwindowtitle(String minimizedWindowTitle) {
this.minimizedWindowTitle = minimizedWindowTitle;
}
/**
* Set the icon file for the minimized window that will be displayed in the
* Windows taskbar. Note that this property has no effect on non-Windows
* platforms.
*
* @param minimizedWindowIcon the icon file to use for any minimized window
* that is displayed in the Windows taskbar
*/
public void setMinimizedwindowicon(File minimizedWindowIcon) {
this.minimizedWindowIcon = minimizedWindowIcon;
}
/**
* Set the file that the child JVM's System.out and System.err will be
* redirected to. Output will only be redirected if the redirect flag
* is set to true via the {@link #setRedirectoutput(boolean)} method.
*
* @param outputFile a File to redirect System.out and System.err to
*/
public void setOutput(File outputFile) {
this.outputFile = outputFile;
}
/**
* Set the appendOutput flag. Setting this flag to true will cause the child
* JVM to append System.out and System.err to the file specified by the
* {@link #setOutput(File)} method. Setting this flag to false will cause
* the child to overwrite the file.
*
* @param appendOutput true if output should be appended to the output file
*/
public void setAppendoutput(boolean appendOutput) {
this.appendOutput = appendOutput;
}
/**
* Set the list of nested arg elements.
*
* @param args a list of {@link String} objects
*/
public void setArgs(ArrayList args) {
this.args = args;
}
/**
* Set the list of nested jvmarg elements.
*
* @param jvmArgs a list of {@link String} objects
*/
public void setJvmargs(ArrayList jvmArgs) {
this.jvmArgs = jvmArgs;
}
/**
* Set the list of nested sysproperty elements.
*
* @param sysProperties a map of {@link String} objects
*/
public void setSysproperties(HashMap sysProperties) {
this.sysProperties = sysProperties;
}
/**
* Set the redirect flag. Setting this flag to true will cause the child
* JVM's System.out and System.err to be redirected to file set using the
* {@link #setOutput(File)} method. Setting this flag to false will
* cause no redirection.
*
* @param redirect true if System.out and System.err should be redirected
*/
public void setRedirectoutput(boolean redirect) {
this.redirect = redirect;
}
}
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/LaunchFilter.java 0100644 0001750 0001750 00000004260 10020100364 027745 0 ustar arnaud arnaud /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.launcher;
import org.apache.tools.ant.BuildException;
/**
* An interface that provides a means for application developers to perform
* dynamic configuration and error checking of the attributes and nested
* elements associated with a "launch" task that connot be easily done within
* the constraints of Ant.
*
* An implementor of this interface can be attached to a "launch" task by * setting the following "launch" task attributes in the Launcher's XML * file: *
filterclassname
- The name of the class that implements
* this interface
* filterclasspath
- (Optional) The classpath for the class
* that implements
* java.endorsed.dirs
when running with JDK 1.4.
* main(String[])
*/
public void setClassname(String mainClassName) {
this.mainClassName = mainClassName;
}
/**
* Set the classpath.
*
* @param classpath the classpath
*/
public void setClasspath(Path classpath) {
createClasspath().append(classpath);
}
/**
* Adds a reference to a classpath defined elsewhere.
*
* @param ref reference to the classpath
*/
public void setClasspathref(Reference ref) {
createClasspath().setRefid(ref);
}
/**
* Set the debug flag. Setting this flag to true will cause this
* task to run the child JVM using the JDB debugger.
*
* @param debug the debug flag
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Set the displayMinimizedWindow flag. Note that this flag has no effect
* on non-Windows platforms. On Windows platform, setting this flag to true
* will cause a minimized window to be displayed in the Windows task bar
* while the child process is executing. This flag is usually set to true
* for server applications that also have their "waitForChild" attribute
* set to false via the {@link #setWaitforchild(boolean)} method.
*
* @param displayMinimizedWindow true if a minimized window should be
* displayed in the Windows task bar while the child process is executing
*/
public void setDisplayminimizedwindow(boolean displayMinimizedWindow) {
this.displayMinimizedWindow = displayMinimizedWindow;
}
/**
* Set the disposeMinimizedWindow flag. Note that this flag has no effect
* on non-Windows platforms. On Windows platform, setting this flag to true
* will cause any minimized window that is display by setting the
* "displayMinimizedWindow" attribute to true via the
* {@link #setDisplayminimizedwindow(boolean)} to be automatically
* disposed of when the child JVM's main(String[])
returns.
* This flag is normally used for applications that don't explicitly call
* {@link System#exit(int)}. If an application does not explicitly call
* {@link System#exit(int)}, an minimized windows need to be disposed of
* for the child JVM to exit.
*
* @param disposeMinimizedWindow true if a minimized window in the Windows
* taskbar should be automatically disposed of after the child JVM's
* main(String[])
returns
*/
public void setDisposeminimizedwindow(boolean disposeMinimizedWindow) {
this.disposeMinimizedWindow = disposeMinimizedWindow;
}
/**
* Set the failOnError flag.
*
* @param failOnError true if the launch process should stop if the child
* JVM returns an exit value other than 0
*/
public void setFailonerror(boolean failOnError) {
this.failOnError = failOnError;
}
/**
* Set the filter class name.
*
* @param filterClassName the class that implements the
* {@link LaunchFilter} interface
*/
public void setFilterclassname(String filterClassName) {
this.filterClassName = filterClassName;
}
/**
* Set the filter class' classpath.
*
* @param classpath the classpath for the filter class
*/
public void setFilterclasspath(Path filterClasspath) {
createFilterclasspath().append(filterClasspath);
}
/**
* Set the title for the minimized window that will be displayed in the
* Windows taskbar. Note that this property has no effect on non-Windows
* platforms.
*
* @param minimizedWindowTitle the title to set for any minimized window
* that is displayed in the Windows taskbar
*/
public void setMinimizedwindowtitle(String minimizedWindowTitle) {
this.minimizedWindowTitle = minimizedWindowTitle;
}
/**
* Set the icon file for the minimized window that will be displayed in the
* Windows taskbar. Note that this property has no effect on non-Windows
* platforms.
*
* @param minimizedWindowIcon the icon file to use for any minimized window
* that is displayed in the Windows taskbar
*/
public void setMinimizedwindowicon(File minimizedWindowIcon) {
this.minimizedWindowIcon = minimizedWindowIcon;
}
/**
* Set the file that the child JVM's System.out and System.err will be
* redirected to. Output will only be redirected if the redirect flag
* is set to true via the {@link #setRedirectoutput(boolean)} method.
*
* @param outputFile a File to redirect System.out and System.err to
*/
public void setOutput(File outputFile) {
this.outputFile = outputFile;
}
/**
* Set the print flag. Setting this flag to true will cause the full child
* JVM command to be printed to {@link System#out}.
*
* @param print the print flag
*/
public void setPrint(boolean print) {
this.print = print;
}
/**
* Set the appendOutput flag. Setting this flag to true will cause the child
* JVM to append System.out and System.err to the file specified by the
* {@link #setOutput(File)} method. Setting this flag to false will cause
* the child to overwrite the file.
*
* @param appendOutput true if output should be appended to the output file
*/
public void setAppendoutput(boolean appendOutput) {
this.appendOutput = appendOutput;
}
/**
* Set the redirect flag. Setting this flag to true will cause the child
* JVM's System.out and System.err to be redirected to file set using the
* {@link #setOutput(File)} method. Setting this flag to false will
* cause no redirection.
*
* @param redirect true if System.out and System.err should be redirected
*/
public void setRedirectoutput(boolean redirect) {
this.redirect = redirect;
}
/**
* Set the requireTools flag. Setting this flag to true will cause the
* JVM's tools.jar to be added to the child JVM's classpath. This
* sets an explicit requirement that the user use a JDK instead of a
* JRE. Setting this flag to false explicitly allows the user to use
* a JRE.
*
* @param redirect true if a JDK is required and false if only a JRE
* is required
*/
public void setRequiretools(boolean requireTools) {
this.requireTools = requireTools;
}
/**
* Determine if the "if" condition flag for a nested element meets all
* criteria for use.
*
* @param ifCondition the "if" condition flag for a nested element
* @return true if the nested element should be process and false if it
* should be ignored
*/
private boolean testIfCondition(String ifCondition) {
if (ifCondition == null || "".equals(ifCondition))
return true;
return project.getProperty(ifCondition) != null;
}
/**
* Determine if the "unless" condition flag for a nested element meets all
* criteria for use.
*
* @param unlessCondition the "unless" condition flag for a nested element
* @return true if the nested element should be process and false if it
* should be ignored
*/
private boolean testUnlessCondition(String unlessCondition) {
if (unlessCondition == null || "".equals(unlessCondition))
return true;
return project.getProperty(unlessCondition) == null;
}
}
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/LaunchTask_en.properties 0100644 0001750 0001750 00000001412 07556213346 031404 0 ustar arnaud arnaud #
# Localized strings for LaunchTask class
#
classname.null=The "classname" attribute must be set
output.file.null=The "output" attribute must be set when the "redirect" attribute is enabled
output.file.not.creatable=output file cannot be created
output.file.not.writable=output file is not writable
redirect.notice=Redirecting application output to
launch.task.stopped=This task has been stopped
no.run.standalone=This task can only be used within the Launcher application. It cannot be used within a regular Ant buildfile.
filter.not.filter=class does not implement the LaunchFilter interface
filter.exception=filter class encountered a problem
child.failed=The launched process returned an exit value of
executing.child.command=Executing the following command
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/Launcher.java 0100644 0001750 0001750 00000104331 10100516556 027143 0 ustar arnaud arnaud /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.launcher;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ResourceBundle;
import org.apache.commons.launcher.types.ArgumentSet;
import org.apache.commons.launcher.types.JVMArgumentSet;
import org.apache.commons.launcher.types.SysPropertySet;
import org.apache.tools.ant.Main;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.taskdefs.Ant;
import org.apache.tools.ant.taskdefs.Available;
import org.apache.tools.ant.taskdefs.CallTarget;
import org.apache.tools.ant.taskdefs.ConditionTask;
import org.apache.tools.ant.taskdefs.Exit;
import org.apache.tools.ant.taskdefs.Property;
import org.apache.tools.ant.taskdefs.Mkdir;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Delete;
import org.apache.tools.ant.types.Description;
import org.apache.tools.ant.types.FileList;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PatternSet;
/**
* A class that is used to launch a Java process. The primary purpose of this
* class is to eliminate the need for a batch or shell script to launch a Java
* process. Some situations where elimination of a batch or shell script may be
* desirable are:
* main(String[]) method for this class except that this method
* never invokes {@link System#exit(int)}. This method is designed for
* applications that wish to invoke this class directly from within their
* application's code.
*
* @param args command line arguments
* @return the exit value of the last synchronous child JVM that was
* launched or 1 if any other error occurs
* @throws IllegalArgumentException if any error parsing the args parameter
* occurs
*/
public static int start(String[] args) throws IllegalArgumentException {
// Check make sure that neither this method or the stop() method is
// already running since we do not support concurrency
synchronized (Launcher.lock) {
if (Launcher.isStarted() || Launcher.isStopped())
return 1;
Launcher.setStarted(true);
}
int returnValue = 0;
ClassLoader parentLoader = null;
Thread shutdownHook = new Thread(new Launcher());
Runtime runtime = Runtime.getRuntime();
try {
// Cache the current class loader for this thread and set the class
// loader before running Ant. Note that we only set the class loader
// if we are running a Java version earlier than 1.4 as on 1.4 this
// causes unnecessary loading of the XML parser classes.
parentLoader = Thread.currentThread().getContextClassLoader();
boolean lessThan14 = true;
try {
Class.forName("java.lang.CharSequence");
lessThan14 = false;
} catch (ClassNotFoundException cnfe) {
// If this class does not exist, then we are not running Java 1.4
}
if (lessThan14)
Thread.currentThread().setContextClassLoader(Launcher.class.getClassLoader());
Project project = new Project();
// Set the project's class loader
project.setCoreLoader(Launcher.class.getClassLoader());
// Initialize the project. Note that we don't invoke the
// Project.init() method directly as this will cause all of
// the myriad of Task subclasses to load which is a big
// performance hit. Instead, we load only the
// Launcher.SUPPORTED_ANT_TASKS and Launcher.SUPPORTED_ANT_TYPES
// into the project that the Launcher supports.
for (int i = 0; i < Launcher.SUPPORTED_ANT_TASKS.length; i++) {
// The even numbered elements should be the task name
String taskName = (String)Launcher.SUPPORTED_ANT_TASKS[i];
// The odd numbered elements should be the task class
Class taskClass = (Class)Launcher.SUPPORTED_ANT_TASKS[++i];
project.addTaskDefinition(taskName, taskClass);
}
for (int i = 0; i < Launcher.SUPPORTED_ANT_TYPES.length; i++) {
// The even numbered elements should be the type name
String typeName = (String)Launcher.SUPPORTED_ANT_TYPES[i];
// The odd numbered elements should be the type class
Class typeClass = (Class)Launcher.SUPPORTED_ANT_TYPES[++i];
project.addDataTypeDefinition(typeName, typeClass);
}
// Add all system properties as project properties
project.setSystemProperties();
// Parse the arguments
int currentArg = 0;
// Set default XML file
File launchFile = new File(Launcher.getBootstrapDir(), Launcher.DEFAULT_XML_FILE_NAME);
// Get standard launcher arguments
for ( ; currentArg < args.length; currentArg++) {
// If we find a "-" argument or an argument without a
// leading "-", there are no more standard launcher arguments
if ("-".equals(args[currentArg])) {
currentArg++;
break;
} else if (args[currentArg].length() > 0 && !"-".equals(args[currentArg].substring(0, 1))) {
break;
} else if ("-help".equals(args[currentArg])) {
throw new IllegalArgumentException();
} else if ("-launchfile".equals(args[currentArg])) {
if (currentArg + 1 < args.length){
String fileArg = args[++currentArg];
launchFile = new File(fileArg);
if (!launchFile.isAbsolute())
launchFile = new File(Launcher.getBootstrapDir(), fileArg);
} else {
throw new IllegalArgumentException(args[currentArg] + " " + Launcher.getLocalizedString("missing.arg"));
}
} else if ("-executablename".equals(args[currentArg])) {
if (currentArg + 1 < args.length)
System.setProperty(ChildMain.EXECUTABLE_PROP_NAME, args[++currentArg]);
else
throw new IllegalArgumentException(args[currentArg] + " " + Launcher.getLocalizedString("missing.arg"));
} else if ("-verbose".equals(args[currentArg])) {
Launcher.setVerbose(true);
} else {
throw new IllegalArgumentException(args[currentArg] + " " + Launcher.getLocalizedString("invalid.arg"));
}
}
// Get target
String target = null;
if (currentArg < args.length)
target = args[currentArg++];
else
throw new IllegalArgumentException(Launcher.getLocalizedString("missing.target"));
// Get user properties
for ( ; currentArg < args.length; currentArg++) {
// If we don't find any more "-" or "-D" arguments, there are no
// more user properties
if ("-".equals(args[currentArg])) {
currentArg++;
break;
} else if (args[currentArg].length() <= 2 || !"-D".equals(args[currentArg].substring(0, 2))) {
break;
}
int delimiter = args[currentArg].indexOf('=', 2);
String key = null;
String value = null;
if (delimiter >= 2) {
key = args[currentArg].substring(2, delimiter);
value = args[currentArg].substring(delimiter + 1);
} else {
// Unfortunately, MS-DOS batch scripts will split an
// "-Dname=value" argument into "-Dname" and "value"
// arguments. So, we need to assume that the next
// argument is the property value unless it appears
// to be a different type of argument.
key = args[currentArg].substring(2);
if (currentArg + 1 < args.length &&
!"-D".equals(args[currentArg + 1].substring(0, 2)))
{
value = args[++currentArg];
} else {
value = "";
}
}
project.setUserProperty(key, value);
}
// Treat all remaining arguments as application arguments
String[] appArgs = new String[args.length - currentArg];
for (int i = 0; i < appArgs.length; i++) {
appArgs[i] = args[i + currentArg];
project.setUserProperty(LaunchTask.ARG_PROP_NAME + Integer.toString(i), appArgs[i]);
}
// Set standard Ant user properties
project.setUserProperty("ant.version", Main.getAntVersion());
project.setUserProperty("ant.file", launchFile.getCanonicalPath());
project.setUserProperty("ant.java.version", System.getProperty("java.specification.version"));
// Set the buildfile
ProjectHelper.configureProject(project, launchFile);
// Check that the target exists
if (!project.getTargets().containsKey(target))
throw new IllegalArgumentException(target + " " + Launcher.getLocalizedString("invalid.target"));
// Execute the target
try {
runtime.addShutdownHook(shutdownHook);
} catch (NoSuchMethodError nsme) {
// Early JVMs do not support this method
}
project.executeTarget(target);
} catch (Throwable t) {
// Log any errors
returnValue = 1;
String message = t.getMessage();
if (t instanceof IllegalArgumentException) {
Launcher.error(message, true);
} else {
if (Launcher.verbose)
Launcher.error(t);
else
Launcher.error(message, false);
}
} finally {
synchronized (Launcher.lock) {
// Remove the shutdown hook
try {
runtime.removeShutdownHook(shutdownHook);
} catch (NoSuchMethodError nsme) {
// Early JVMs do not support this method
}
// Reset the class loader after running Ant
Thread.currentThread().setContextClassLoader(parentLoader);
// Reset stopped flag
Launcher.setStarted(false);
// Notify the stop() method that we have set the class loader
Launcher.lock.notifyAll();
}
}
// Override return value with exit value of last synchronous child JVM
Process[] childProcesses = LaunchTask.getChildProcesses();
if (childProcesses.length > 0)
returnValue = childProcesses[childProcesses.length - 1].exitValue();
return returnValue;
}
/**
* Interrupt the {@link #start(String[])} method. This is done
* by forcing the current or next scheduled invocation of the
* {@link LaunchTask#execute()} method to throw an exception. In addition,
* this method will terminate any synchronous child processes that any
* instances of the {@link LaunchTask} class have launched. Note, however,
* that this method will not terminate any asynchronous child
* processes that have been launched. Accordingly, applications that use
* this method are encouraged to always set the LaunchTask.TASK_NAME task's
* "waitForChild" attribute to "true" to ensure that the
* application that you want to control can be terminated via this method.
* After this method has been executed, it will not return until is safe to
* execute the {@link #start(String[])} method.
*
* @return true if this method completed without error and false if an
* error occurred or the launch process is already stopped
*/
public static boolean stop() {
synchronized (Launcher.lock) {
// Check the stopped flag to avoid concurrent execution of this
// method
if (Launcher.isStopped())
return false;
// Make sure that the start() method is running. If not, just
// return as there is nothing to do.
if (Launcher.isStarted())
Launcher.setStopped(true);
else
return false;
}
boolean returnValue = true;
try {
// Kill all of the synchronous child processes
killChildProcesses();
// Wait for the start() method to reset the start flag
synchronized (Launcher.lock) {
if (Launcher.isStarted())
Launcher.lock.wait();
}
// Make sure that the start() method has really finished
if (Launcher.isStarted())
returnValue = true;
} catch (Throwable t) {
// Log any errors
returnValue = false;
String message = t.getMessage();
if (Launcher.verbose)
Launcher.error(t);
else
Launcher.error(message, false);
} finally {
// Reset stopped flag
Launcher.setStopped(false);
}
return returnValue;
}
/**
* Print a detailed error message and exit.
*
* @param message the message to be printed
* @param usage if true, print a usage statement after the message
*/
public static void error(String message, boolean usage) {
if (message != null)
Launcher.getLog().println(Launcher.getLocalizedString("error") + ": " + message);
if (usage)
Launcher.getLog().println(Launcher.getLocalizedString("usage"));
}
/**
* Print a detailed error message and exit.
*
* @param message the exception whose stack trace is to be printed.
*/
public static void error(Throwable t) {
String message = t.getMessage();
if (!Launcher.verbose && message != null)
Launcher.getLog().println(Launcher.getLocalizedString("error") + ": " + message);
else
t.printStackTrace(Launcher.getLog());
}
/**
* Get the canonical directory of the class or jar file that this class was
* loaded. This method can be used to calculate the root directory of an
* installation.
*
* @return the canonical directory of the class or jar file that this class
* file was loaded from
* @throws IOException if the canonical directory or jar file
* cannot be found
*/
public static File getBootstrapDir() throws IOException {
File file = Launcher.getBootstrapFile();
if (file.isDirectory())
return file;
else
return file.getParentFile();
}
/**
* Get the canonical directory or jar file that this class was loaded
* from.
*
* @return the canonical directory or jar file that this class
* file was loaded from
* @throws IOException if the canonical directory or jar file
* cannot be found
*/
public static File getBootstrapFile() throws IOException {
if (bootstrapFile == null) {
// Get a URL for where this class was loaded from
String classResourceName = "/" + Launcher.class.getName().replace('.', '/') + ".class";
URL resource = Launcher.class.getResource(classResourceName);
if (resource == null)
throw new IOException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
String resourcePath = null;
String embeddedClassName = null;
boolean isJar = false;
String protocol = resource.getProtocol();
if ((protocol != null) &&
(protocol.indexOf("jar") >= 0)) {
isJar = true;
}
if (isJar) {
resourcePath = URLDecoder.decode(resource.getFile());
embeddedClassName = "!" + classResourceName;
} else {
resourcePath = URLDecoder.decode(resource.toExternalForm());
embeddedClassName = classResourceName;
}
int sep = resourcePath.lastIndexOf(embeddedClassName);
if (sep >= 0)
resourcePath = resourcePath.substring(0, sep);
// Now that we have a URL, make sure that it is a "file" URL
// as we need to coerce the URL into a File object
if (resourcePath.indexOf("file:") == 0)
resourcePath = resourcePath.substring(5);
else
throw new IOException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
// Coerce the URL into a file and check that it exists. Note that
// the JVM File(String)
constructor automatically
// flips all '/' characters to '\' on Windows and there are no
// valid escape characters so we sould not have to worry about
// URL encoded slashes.
File file = new File(resourcePath);
if (!file.exists() || !file.canRead())
throw new IOException(Launcher.getLocalizedString("bootstrap.file.not.found") + ": " + Launcher.class.getName());
bootstrapFile = file.getCanonicalFile();
}
return bootstrapFile;
}
/**
* Get the full path of the Java command to execute.
*
* @return a string suitable for executing a child JVM
*/
public static synchronized String getJavaCommand() {
if (javaCmd == null) {
String osname = System.getProperty("os.name").toLowerCase();
String commandName = null;
if (osname.indexOf("windows") >= 0) {
// Always use javaw.exe on Windows so that we aren't bound to an
// MS-DOS window
commandName = "javaw.exe";
} else {
commandName = "java";
}
javaCmd = System.getProperty("java.home") + File.separator + "bin" + File.separator + commandName;
}
return javaCmd;
}
/**
* Get the full path of the JDB command to execute.
*
* @return a string suitable for executing a child JDB debugger
*/
public static synchronized String getJDBCommand() {
if (jdbCmd == null) {
String osname = System.getProperty("os.name").toLowerCase();
String commandName = null;
if (osname.indexOf("windows") >= 0)
commandName = "jdb.exe";
else
commandName = "jdb";
jdbCmd = new File(System.getProperty("java.home")).getParent() + File.separator + "bin" + File.separator + commandName;
}
return jdbCmd;
}
/**
* Get the PrintStream that all output should printed to. The default
* PrintStream returned in System.err.
*
* @return the PrintStream instance to print output to
*/
public static synchronized PrintStream getLog() {
return Launcher.log;
}
/**
* Set the classpath to the current JVM's tools classes.
*
* @return a string suitable for use as a JVM's -classpath argument
* @throws IOException if the tools classes cannot be found
*/
public static synchronized String getToolsClasspath() throws IOException {
if (toolsClasspath == null) {
File javaHome = null;
javaHome = new File(System.getProperty("java.home")).getCanonicalFile();
Class clazz = null;
String[] toolsPaths = new String[2];
toolsPaths[0] = javaHome.getParent() + File.separator +
"lib" + File.separator + "tools.jar";
toolsPaths[1] = javaHome.getPath() + File.separator +
"lib" + File.separator + "tools.jar";
File toolsFile = null;
for (int i = 0; i < toolsPaths.length; i++) {
ClassLoader loader = ClassLoader.getSystemClassLoader();
toolsFile = new File(toolsPaths[i]);
// Check if the jar file exists and is readable
if (!toolsFile.isFile() || !toolsFile.canRead())
toolsFile = null;
if (toolsFile != null) {
try {
URL toolsURL = toolsFile.toURL();
loader = new URLClassLoader(new URL[]{toolsURL}, loader);
} catch (Exception e) {
toolsFile = null;
}
}
// Try to load the javac class just to be sure. Note that we
// use the system class loader if the file does not exist to
// handle cases like Mac OS X where the tools.jar classes are
// loaded by the bootstrap class loader.
try {
clazz = loader.loadClass("sun.tools.javac.Main");
if (clazz != null)
break;
} catch (Exception e) {}
}
if (clazz == null)
throw new IOException(Launcher.getLocalizedString("sdk.tools.not.found"));
// Save classpath.
if (toolsFile != null)
toolsClasspath = toolsFile.getPath();
else
toolsClasspath = "";
}
return toolsClasspath;
}
/**
* Get a localized property. This method will search for localized
* properties and will resolve ${...} style macros in the localized string.
*
* @param key the localized property to retrieve
* @return the localized and resolved property value
*/
public static String getLocalizedString(String key) {
return Launcher.getLocalizedString(key, Launcher.class.getName());
}
/**
* Get a localized property. This method will search for localized
* properties and will resolve ${...} style macros in the localized string.
*
* @param key the localized property to retrieve
* @param className the name of the class to retrieve the property for
* @return the localized and resolved property value
*/
public static String getLocalizedString(String key, String className) {
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(className);
return Launcher.resolveString(resourceBundle.getString(key));
} catch (Exception e) {
// We should at least make it clear that the property is not
// defined in the properties file
return "<" + key + " property>";
}
}
/**
* Resolve ${...} style macros in strings. This method will replace any
* embedded ${...} strings in the specified unresolved parameter with the
* value of the system property in the enclosed braces. Note that any '$'
* characters can be escaped by putting '$$' in the specified parameter.
* In additional, the following special macros will be resolved:
*
* ${launcher.executable.name}
will be substituted with the
* value of the "org.apache.commons.launcher.executableName" system
* property, the "-executablename" command line argument, or, if both of
* those are undefined, with the absolute path to the Java executable plus
* its classpath and main class name arguments
* ${launcher.bootstrap.file}
will get substituted with
* the value returned by {@link #getBootstrapFile()}
* ${launcher.bootstrap.dir}
will get substituted with
* the value returned by {@link #getBootstrapDir()}
*
* @param unresolved the string to be resolved
* @return the resolved String
* @throws IOException if any error occurs
*/
private static String resolveString(String unresolved) throws IOException {
if (unresolved == null)
return null;
// Substitute system property strings
StringBuffer buf = new StringBuffer();
int tokenEnd = 0;
int tokenStart = 0;
char token = '$';
boolean escapeChar = false;
boolean firstToken = true;
boolean lastToken = false;
while (!lastToken) {
tokenEnd = unresolved.indexOf(token, tokenStart);
// Determine if this is the first token
if (firstToken) {
firstToken = false;
// Skip if first token is zero length
if (tokenEnd - tokenStart == 0) {
tokenStart = ++tokenEnd;
continue;
}
}
// Determine if this is the last token
if (tokenEnd < 0) {
lastToken = true;
tokenEnd = unresolved.length();
}
if (escapeChar) {
// Don't parse the string
buf.append(token + unresolved.substring(tokenStart, tokenEnd));
escapeChar = !escapeChar;
} else {
// Parse the string
int openProp = unresolved.indexOf('{', tokenStart);
int closeProp = unresolved.indexOf('}', tokenStart + 1);
String prop = null;
// We must have a '{' in the first character and a closing
// '}' after that
if (openProp != tokenStart ||
closeProp < tokenStart + 1 ||
closeProp >= tokenEnd)
{
buf.append(unresolved.substring(tokenStart, tokenEnd));
} else {
// Property found
String propName = unresolved.substring(tokenStart + 1, closeProp);
if ("launcher.executable.name".equals(propName)) {
prop = System.getProperty(ChildMain.EXECUTABLE_PROP_NAME);
if (prop != null) {
// Quote the property
prop = "\"" + prop + "\"";
} else {
// Set property to fully quoted Java command line
String classpath = Launcher.getBootstrapFile().getPath();
prop = "\"" + System.getProperty("java.home") + File.separator + "bin" + File.separator + "java\" -classpath \"" + classpath + "\" LauncherBootstrap";
}
} else if ("launcher.bootstrap.file".equals(propName)) {
prop = Launcher.getBootstrapFile().getPath();
} else if ("launcher.bootstrap.dir".equals(propName)) {
prop = Launcher.getBootstrapDir().getPath();
} else {
prop = System.getProperty(unresolved.substring(tokenStart + 1, closeProp));
}
if (prop == null)
prop = "";
buf.append(prop + unresolved.substring(++closeProp, tokenEnd));
}
}
// If this is a blank token, then the next starts with the
// token character. So, treat this token as an escape
// character for the next token.
if (tokenEnd - tokenStart == 0)
escapeChar = !escapeChar;
tokenStart = ++tokenEnd;
}
return buf.toString();
}
/**
* Set the PrintStream that all output should printed to.
*
* @param a PrintStream instance to print output to
*/
public static synchronized void setLog(PrintStream log) {
if (log != null)
Launcher.log = log;
else
Launcher.log = System.err;
}
/**
* Set the started flag.
*
* @param started the value of the started flag
*/
private static synchronized void setStarted(boolean started) {
Launcher.started = started;
}
/**
* Set the stopped flag.
*
* @param stopped the value of the stopped flag
*/
private static synchronized void setStopped(boolean stopped) {
Launcher.stopped = stopped;
}
/**
* Set the verbose flag.
*
* @param verbose the value of the verbose flag
*/
public static synchronized void setVerbose(boolean verbose) {
Launcher.verbose = verbose;
}
/**
* Iterate through the list of synchronous child process launched by
* all of the {@link LaunchTask} instances.
*/
public static void killChildProcesses() {
Process[] procs = LaunchTask.getChildProcesses();
for (int i = 0; i < procs.length; i++)
procs[i].destroy();
}
//----------------------------------------------------------------- Methods
/**
* Wrapper to allow the {@link #killChildProcesses()} method to be
* invoked in a shutdown hook.
*/
public void run() {
Launcher.killChildProcesses();
}
}
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/Launcher_en.properties 0100644 0001750 0001750 00000002402 07556213350 031103 0 ustar arnaud arnaud #
# Localized strings for Launcher class
#
error=Error
bootstrap.file.not.found=Cannot determine directory or jar file where the following class was loaded from
bootstrap.file.not.file=The following class must be loaded from a local file
sdk.tools.not.found=Could not find Java(TM) 2 SDK classes. This application cannot run using the Java(TM) 2 JRE. It requires the full SDK.
launch.already.started=The launching process has already started and cannot be restarted until it has finished or been stopped
launch.already.stopped=The launching process is already in the process of being stopped
missing.arg=requires an argument immediately after it
invalid.arg=is not a valid argument
missing.target=A target is required
invalid.target=is not a valid target
usage=Usage: ${launcher.executable.name} [options] [-] target [-D=...] [-] [application arguments...]${line.separator}\
where options include:${line.separator}\
\ -help Print this usage statement${line.separator}\
\ -launchfile The XML file to use (the default is "launcher.xml")${line.separator}\
\ -executablename The executable name to print in this usage statement${line.separator}\
\ -verbose Print stack traces with error messages
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/ParentListener.java 0100644 0001750 0001750 00000012025 10020100364 030322 0 ustar arnaud arnaud /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.launcher;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
/**
* A class for detecting if the parent JVM that launched this process has
* terminated.
*
* @author Patrick Luby
*/
public class ParentListener extends Thread {
//------------------------------------------------------------------ Fields
/**
* Cached heartbeat file.
*/
private File heartbeatFile = null;
//------------------------------------------------------------ Constructors
/**
* Validates and caches a lock file created by the parent JVM.
*
* @param path the lock file that the parent JVM has an open
* FileOutputStream
* @throws IOException if the heartbeat cannot be converted into a valid
* File object
*/
public ParentListener(String path) throws IOException {
if (path == null)
throw new IOException();
// Make sure we have a valid path
heartbeatFile = new File(path);
heartbeatFile.getCanonicalPath();
}
//----------------------------------------------------------------- Methods
/**
* Periodically check that the parent JVM has not terminated. On all
* platforms other than Windows, this method will check that System.in has
* not been closed. On Windows NT, 2000, and XP the lock file specified in
* the {@link #ParentListener(String)} constructor is monitored as reading
* System.in will block the entire process on Windows machines that use
* some versions of Unix shells such as MKS, etc. No monitoring is done
* on Window 95, 98, and ME.
*/
public void run() {
String osname = System.getProperty("os.name").toLowerCase();
// We need to use file locking on Windows since reading System.in
// will block the entire process on some Windows machines.
if (osname.indexOf("windows") >= 0) {
// Do nothing if this is a Windows 9x platform since our file
// locking mechanism does not work on the early versions of
// Windows
if (osname.indexOf("nt") == -1 && osname.indexOf("2000") == -1 && osname.indexOf("xp") == -1)
return;
// If we can delete the heartbeatFile on Windows, it means that
// the parent JVM has closed its FileOutputStream on the file.
// Note that the parent JVM's stream should only be closed when
// it exits.
for ( ; ; ) {
if (heartbeatFile.delete())
break;
// Wait awhile before we try again
yield();
try {
sleep(5000);
} catch (Exception e) {}
}
} else {
// Cache System.in in case the application redirects
InputStream is = System.in;
int bytesAvailable = 0;
int bytesRead = 0;
byte[] buf = new byte[1024];
try {
while (true) {
synchronized (is) {
// Mark the stream position so that other threads can
// reread the strea
is.mark(buf.length);
// Read one more byte than has already been read to
// force the stream to wait for input
bytesAvailable = is.available();
if (bytesAvailable < buf.length) {
bytesRead = is.read(buf, 0, bytesAvailable + 1);
// Reset so that we "unread" the bytes that we read
is.reset();
if (bytesRead == -1)
break;
} else {
// Make the buffer larger
if (buf.length < Integer.MAX_VALUE / 2)
buf = new byte[buf.length * 2];
}
}
yield();
}
} catch (IOException ioe) {}
}
// Clean up before exiting
if (heartbeatFile != null)
heartbeatFile.delete();
// Exit this process since the parent JVM has exited
System.exit(0);
}
}
libcommons-launcher-java-1.1/src/java/org/apache/commons/launcher/StreamConnector.java 0100644 0001750 0001750 00000004622 10020100364 030475 0 ustar arnaud arnaud /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.launcher;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* A class for connecting an OutputStream to an InputStream.
*
* @author Patrick Luby
*/
public class StreamConnector extends Thread {
//------------------------------------------------------------------ Fields
/**
* Input stream to read from.
*/
private InputStream is = null;
/**
* Output stream to write to.
*/
private OutputStream os = null;
//------------------------------------------------------------ Constructors
/**
* Specify the streams that this object will connect in the {@link #run()}
* method.
*
* @param is the InputStream to read from.
* @param os the OutputStream to write to.
*/
public StreamConnector(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
//----------------------------------------------------------------- Methods
/**
* Connect the InputStream and OutputStream objects specified in the
* {@link #StreamConnector(InputStream, OutputStream)} constructor.
*/
public void run() {
// If the InputStream is null, don't do anything
if (is == null)
return;
// Connect the streams until the InputStream is unreadable
try {
int bytesRead = 0;
byte[] buf = new byte[4096];
while ((bytesRead = is.read(buf)) != -1) {
if (os != null && bytesRead > 0) {
os.write(buf, 0, bytesRead);
os.flush();
}
yield();
}
} catch (IOException e) {}
}
}
libcommons-launcher-java-1.1/src/java/LauncherBootstrap.java 0100644 0001750 0001750 00000016273 10020100364 023547 0 ustar arnaud arnaud /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* This class is used as a wrapper for loading the
* org.apache.commons.launcher.Launcher class and invoking its
* main(String[])
method. This particular
* class is primary used by the Windows 95, 98, ME, and 2000 platforms to
* overcome the difficulty of putting a jar file directly into the JVM's
* classpath when using batch scripts on these platforms.
*
* Specifically, the problem on thse platforms is when Windows uses the PATH
* environment variable to find and run a batch script, %0 will resolve
* incorrectly in that batch script.
*
* The way to work around this Windows limitation is to do the following:
*
* - Put this class' class file - LauncherBootstrap.class - in the same
* directory as the batch script. Do not put this class file in a jar file.
*
- Put the jar file containing the launcher's classes in the same
* directory as the batch script and this class' class file. Be sure that
* that the jar file is named "commons-launcher.jar".
*
- Make the Java command in the batch script invoke Java use the following
* classpath arguments. Be sure to include the quotes to ensure that paths
* containing spaces are handled properly:
*
-classpath %0\..;"%PATH%"
*
*
* @author Patrick Luby
*/
public class LauncherBootstrap {
//---------------------------------------------------------- Static Fields
/**
* Ant classpath property name
*/
public final static String ANT_CLASSPATH_PROP_NAME = "ant.class.path";
/**
* Jar file name
*/
public final static String LAUNCHER_JAR_FILE_NAME = "commons-launcher.jar";
/**
* Properties file name
*/
public final static String LAUNCHER_PROPS_FILE_NAME = "launcher.properties";
/**
* Class name to load
*/
public final static String LAUNCHER_MAIN_CLASS_NAME = "org.apache.commons.launcher.Launcher";
/**
* Cached Laucher class.
*/
private static Class launcherClass = null;
//---------------------------------------------------------- Static Methods
/**
* The main method.
*
* @param args command line arguments
*/
public static void main(String[] args) {
try {
// Try to find the LAUNCHER_JAR_FILE_NAME file in the class
// loader's and JVM's classpath.
URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);
if (coreURL == null)
throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);
// Coerce the coreURL's directory into a file
File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile();
// Try to find the LAUNCHER_PROPS_FILE_NAME file in the same
// directory as this class
File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME);
if (!propsFile.canRead())
throw new FileNotFoundException(propsFile.getPath());
// Load the properties in the LAUNCHER_PROPS_FILE_NAME
Properties props = new Properties();
FileInputStream fis = new FileInputStream(propsFile);
props.load(fis);
fis.close();
// Create a class loader that contains the Launcher, Ant, and
// JAXP classes.
URL[] antURLs = LauncherBootstrap.fileListToURLs((String)props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME));
URL[] urls = new URL[1 + antURLs.length];
urls[0] = coreURL;
for (int i = 0; i < antURLs.length; i++)
urls[i + 1] = antURLs[i];
ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader loader = null;
if (parentLoader != null)
loader = new URLClassLoader(urls, parentLoader);
else
loader = new URLClassLoader(urls);
// Load the LAUNCHER_MAIN_CLASS_NAME class
launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME);
// Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString()
// method as we need it for printing the usage statement
Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString", new Class[]{ String.class });
// Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method.
// If the ant.class.path property is not set correctly in the
// LAUNCHER_PROPS_FILE_NAME, this will throw an exception.
Method startMethod = launcherClass.getDeclaredMethod("start", new Class[]{ String[].class });
int returnValue = ((Integer)startMethod.invoke(null, new Object[]{ args })).intValue();
// Always exit cleanly after invoking the start() method
System.exit(returnValue);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Convert a ":" separated list of URL file fragments into an array of URL
* objects. Note that any all URL file fragments must conform to the format
* required by the "file" parameter in the
* {@link URL(String, String, String)} constructor.
*
* @param fileList the ":" delimited list of URL file fragments to be
* converted
* @return an array of URL objects
* @throws MalformedURLException if the fileList parameter contains any
* malformed URLs
*/
private static URL[] fileListToURLs(String fileList)
throws MalformedURLException
{
if (fileList == null || "".equals(fileList))
return new URL[0];
// Parse the path string
ArrayList list = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(fileList, ":");
URL bootstrapURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.class.getName() + ".class");
while (tokenizer.hasMoreTokens())
list.add(new URL(bootstrapURL, tokenizer.nextToken()));
return (URL[])list.toArray(new URL[list.size()]);
}
}
libcommons-launcher-java-1.1/xdocs/ 0040755 0001750 0001750 00000000000 10132743155 016666 5 ustar arnaud arnaud libcommons-launcher-java-1.1/xdocs/images/ 0040755 0001750 0001750 00000000000 10132743155 020133 5 ustar arnaud arnaud libcommons-launcher-java-1.1/xdocs/images/launcher-logo-white.png 0100644 0001750 0001750 00000032534 10034045144 024514 0 ustar arnaud arnaud ‰PNG
IHDR æ Q Æ¥Úv bKGD ÿ ÿ ÿ ½§“ pHYs ÒÝ~ü tIMEÔ0çáîÇ IDATxœí}ktTU–ÿ¯’ ó±Ry2óaº /E ЂF1@HTZ´g|t‹¢3v;Ú@ƒ ¢ Aå!òz´U´IèÀ(ï„7¶Ä¼±TUªÎÿCÜ×}÷ÝçVuþ3ke¯uWݺ÷<öÙ{ÿöÞçÜS·ÆƒV/Þʪ.
îïST'Ñ>d]¿z~÷ZË«VþRx¶oKkWö©úL„çï#[û?¦
ùÉ.(0ËË˃¨K—.8p rss‘••åaÔÓÙ·ßµÁ”——ã‹/¾Àúõë]÷rss‘››‹ºÚ÷ M §OŸÆºuë0hÐ äææzÚÛ¹s'ÊË˱sçNgŒ®¾m´aÃìÚµ_|ñ…«nnn®Uq’_É÷Î;±~ýz<ÿüóêØ×¯_;w:}æææ¢°°Ð£M»vírÉšêfgg'įM¿Ô>É‘x€ììl§Ÿx¦ô$›ÂÂBG—Ô&Ùé
PXX·??’ò€ÂÂB4È‘ù£>ŠçŸÞê¼ý¾;ç&½ðÂ&;;Û ð=
ÌÉ“'M(²ápØ„Ãa‰DLss³‰F£&šçŸ>¡>²³³Í”)SZÝOss³Y³f),,tÚZ³finn6‘HÄ„ÃaSZZjhí{àÀæÄ‰æâÅ‹žãÙgŸõåŸê655¹ê555™¦¦&ß‘HÄœ:uÊ<ÿüó&77×iƒx%~çÌ™ãÛçC=äéïâÅ‹æøñãæ¡‡ò•3Õ¥Cã•óËu¹cÇßñl¦¤¤Ä„B!Wš>iìeeeæá‡vý·Þräò׿þÕL™2Å׆V®\é‘‹M4¾GyÄÕFaa¡),,tµ À±¡Dí’äFM,3±XÌcŒ˜ååå®Á?òÈ#¦¬¬ÌÀÉ“'MAAgà+V¬0çÏŸ÷.\p@Œ®^½ÚÕÇÃ?lJKKM86¡PÈœ