public void invokeCommandLineJelly(String[] args) throws JellyException {
CommandLine cmdLine = null;
try {
cmdLine = parseCommandLineOptions(args);
} catch (ParseException e) {
throw new JellyException(e);
}
// check for -h or -v
if (cmdLine.hasOption("h")) {
new HelpFormatter().printHelp("jelly [scriptFile] [-script scriptFile] [-o outputFile] [-Dsysprop=syspropval] [-awt]",
cmdLineOptions);
System.exit(1);
}
if (cmdLine.hasOption("v")) {
System.err.println("Jelly " + Jelly.getJellyVersion());
System.err.println(" compiled: " + Jelly.getJellyBuildDate());
System.err.println("");
System.exit(1);
}
// get the -script option. If there isn't one then use args[0]
String scriptFile = null;
if (cmdLine.hasOption("script")) {
scriptFile = cmdLine.getOptionValue("script");
} else {
scriptFile = args[0];
}
// check the -awt option.
boolean runInSwingThread = cmdLine.hasOption("awt") || cmdLine.hasOption("swing");
//
// Use classloader to find file
//
URL url = ClassLoaderUtils.getClassLoader(getClass()).getResource(scriptFile);
// check if the script file exists
if (url == null && !(new File(scriptFile)).exists()) {
throw new JellyException("Script file " + scriptFile + " not found");
}
try {
// extract the -o option for the output file to use
final XMLOutput output = cmdLine.hasOption("o") ?
XMLOutput.createXMLOutput(new FileWriter(cmdLine.getOptionValue("o"))) :
XMLOutput.createXMLOutput(System.out);
Jelly jelly = new Jelly();
jelly.setScript(scriptFile);
final Script script = jelly.compileScript();
// add the system properties and the command line arguments
final JellyContext context = jelly.getJellyContext();
context.setVariable("args", args);
context.setVariable("commandLine", cmdLine);
if (runInSwingThread) {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() {
try {
script.run(context, output);
} catch (Exception ex) {
ex.printStackTrace();
}
} } ); } else {
script.run(context, output);
}
// now lets wait for all threads to close
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
output.close();
}
catch (Exception e) {
// ignore errors
}
}
}
);
} catch (Exception e) {
throw new JellyException(e);
}
}