001 package org.shiftone.jrat.cli;
002
003
004 import org.shiftone.jrat.util.io.ResourceUtil;
005 import org.shiftone.jrat.util.log.Logger;
006
007 import java.io.PrintStream;
008 import java.lang.reflect.Method;
009 import java.util.Enumeration;
010 import java.util.Properties;
011
012
013 /**
014 * @author jeff@shiftone.org (Jeff Drost)
015 */
016 public class Cli {
017
018 private static final Logger LOG = Logger.getLogger(Cli.class);
019 private static final String PROPS = "org/shiftone/jrat/cli/cli.properties";
020 private static final Class[] MAIN_PARAMS = {String[].class};
021 private static PrintStream OUT = System.out;
022
023 public static void main(String[] args) {
024
025 try {
026 runMain(args);
027 }
028 catch (Exception e) {
029 LOG.error("error executing command", e);
030 }
031 }
032
033
034 private static void runMain(String[] args) throws Exception {
035
036 Properties properties = ResourceUtil.getResourceAsProperties(PROPS);
037 Class klass = null;
038 Method method = null;
039 String className = null;
040 String classKey = null;
041 String[] newArgs = null;
042
043 if (args.length == 0) {
044 newArgs = new String[0];
045 classKey = properties.getProperty("default");
046 } else {
047 newArgs = new String[args.length - 1];
048 classKey = args[0];
049
050 System.arraycopy(args, 1, newArgs, 0, newArgs.length);
051 }
052
053 classKey = classKey.toLowerCase();
054 className = properties.getProperty("main." + classKey + ".class");
055
056 if (className == null) {
057 printOptionsAndExit(classKey, properties);
058 }
059
060 LOG.debug("running " + className + ".main()");
061
062 klass = Class.forName(className);
063 method = klass.getMethod("main", MAIN_PARAMS);
064
065 method.invoke(null, new Object[]{newArgs});
066 }
067
068
069 private static void printOptionsAndExit(String classKey, Properties properties) {
070
071 OUT.println("Option '" + classKey + "' is not supported.");
072 OUT.println("Please try one of the following:");
073
074 Enumeration enumeration = properties.keys();
075
076 while (enumeration.hasMoreElements()) {
077 String str = (String) enumeration.nextElement();
078
079 if (str.startsWith("main.") && str.endsWith(".class")) {
080 str = str.substring(5);
081 str = str.substring(0, str.length() - 6);
082
083 OUT.println("\t" + str);
084 }
085 }
086
087 System.exit(3);
088 }
089 }