001 /*
002 * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
003 *
004 * This software is distributable under the BSD license. See the terms of the
005 * BSD license in the documentation provided with this software.
006 */
007 package jline;
008
009 import java.io.*;
010 import java.util.*;
011
012 /**
013 * <p>
014 * A pass-through application that sets the system input stream to a
015 * {@link ConsoleReader} and invokes the specified main method.
016 * </p>
017 * @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a>
018 */
019 public class ConsoleRunner {
020 public static final String property = "jline.history";
021
022 public static void main(final String[] args) throws Exception {
023 String historyFileName = null;
024
025 List argList = new ArrayList(Arrays.asList(args));
026
027 if (argList.size() == 0) {
028 usage();
029
030 return;
031 }
032
033 historyFileName = System.getProperty(ConsoleRunner.property, null);
034
035 // invoke the main() method
036 String mainClass = (String) argList.remove(0);
037
038 // setup the inpout stream
039 ConsoleReader reader = new ConsoleReader();
040
041 if (historyFileName != null) {
042 reader.setHistory(new History (new File
043 (System.getProperty("user.home"),
044 ".jline-" + mainClass
045 + "." + historyFileName + ".history")));
046 } else {
047 reader.setHistory(new History(new File
048 (System.getProperty("user.home"),
049 ".jline-" + mainClass + ".history")));
050 }
051
052 String completors = System.getProperty
053 (ConsoleRunner.class.getName() + ".completors", "");
054 List completorList = new ArrayList();
055
056 for (StringTokenizer tok = new StringTokenizer(completors, ",");
057 tok.hasMoreTokens();) {
058 completorList.add
059 ((Completor) Class.forName(tok.nextToken()).newInstance());
060 }
061
062 if (completorList.size() > 0) {
063 reader.addCompletor(new ArgumentCompletor(completorList));
064 }
065
066 ConsoleReaderInputStream.setIn(reader);
067
068 try {
069 Class.forName(mainClass).
070 getMethod("main", new Class[] { String[].class }).
071 invoke(null, new Object[] { argList.toArray(new String[0]) });
072 } finally {
073 // just in case this main method is called from another program
074 ConsoleReaderInputStream.restoreIn();
075 }
076 }
077
078 private static void usage() {
079 System.out.println("Usage: \n java " + "[-Djline.history='name'] "
080 + ConsoleRunner.class.getName()
081 + " <target class name> [args]"
082 + "\n\nThe -Djline.history option will avoid history"
083 + "\nmangling when running ConsoleRunner on the same application."
084 + "\n\nargs will be passed directly to the target class name.");
085 }
086 }