source: trunk/java-utils/src/main/java/de/ugoe/cs/util/console/CommandExecuter.java @ 664

Last change on this file since 664 was 664, checked in by sherbold, 12 years ago
  • modified Command.help(): the help now returns a string with its usage instead of writing directly to the console
  • modified listCommands: now writes the help string of each command instead of just the name; this way, the parameters are displayed directly
  • moved listCommands from quest-ui-core to java-utils
File size: 10.7 KB
Line 
1
2package de.ugoe.cs.util.console;
3
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FilenameFilter;
7import java.io.IOException;
8import java.net.URL;
9import java.security.InvalidParameterException;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collections;
13import java.util.Comparator;
14import java.util.Enumeration;
15import java.util.List;
16import java.util.jar.JarEntry;
17import java.util.jar.JarInputStream;
18import java.util.logging.Level;
19
20/**
21 * <p>
22 * Executes commands. The commands have to implement the {@link Command} interface and be in
23 * packages registered using addCommandPackage(). Additionally, default commands are implemented in
24 * the de.ugoe.cs.util.console.defaultcommands package.
25 * </p>
26 * <p>
27 * This class is implemented as a <i>Singleton</i>.
28 * </p>
29 *
30 * @author Steffen Herbold
31 * @version 1.0
32 */
33public class CommandExecuter {
34
35    /**
36     * <p>
37     * Handle of the CommandExecuter instance.
38     * </p>
39     */
40    private final static CommandExecuter theInstance = new CommandExecuter();
41
42    /**
43     * <p>
44     * Prefix of all command classes.
45     * </p>
46     */
47    private static final String cmdPrefix = "CMD";
48
49    /**
50     * <p>
51     * Name of the package for default commands.
52     * </p>
53     */
54    private static final String defaultPackage = "de.ugoe.cs.util.console.defaultcommands";
55
56    /**
57     * <p>
58     * List of packages in which commands may be defined. The exec methods trys to load command from
59     * these packages in the order they have been added.
60     * </p>
61     * <p>
62     * The de.ugoe.cs.util.console.defaultcommands package has always lowest priority, unless it is
63     * specifically added.
64     * </p>
65     */
66    private List<String> commandPackageList;
67
68    /**
69     * <p>
70     * Returns the instance of CommandExecuter. If no instances exists yet, a new one is created.
71     * </p>
72     *
73     * @return the instance of CommandExecuter
74     */
75    public static synchronized CommandExecuter getInstance() {
76        return theInstance;
77    }
78
79    /**
80     * <p>
81     * Creates a new CommandExecuter. Private to prevent multiple instances (Singleton).
82     * </p>
83     */
84    private CommandExecuter() {
85        commandPackageList = new ArrayList<String>();
86    }
87
88    /**
89     * <p>
90     * Adds a package that will be used by {@link #exec(String)} to load command from.
91     * </p>
92     *
93     * @param pkg
94     *            package where commands are located
95     * @throws InvalidParameterException
96     *             thrown if the package name is null or empty string
97     */
98    public void addCommandPackage(String pkg) {
99        if ("".equals(pkg) || pkg == null) {
100            throw new InvalidParameterException("package name must not be null or empty string");
101        }
102        commandPackageList.add(pkg);
103    }
104
105    /**
106     * <p>
107     * Executes the command defined by string. A command has the following form (mix of EBNF and
108     * natural language):
109     * </p>
110     * <code>
111     * &lt;command&gt; := &lt;commandname&gt;&lt;whitespace&gt;{&lt;parameter&gt;}<br>
112     * &lt;commandname&gt; := String without whitespaces. Has to be a valid Java class name<br>
113     * &lt;parameter&gt; := &lt;string&gt;|&lt;stringarray&gt;<br>
114     * &lt;string&gt; := &lt;stringwithoutwhitespaces&gt;|&lt;stringwithwhitespaces&gt;
115     * &lt;stringwithoutwhitespaces&gt; := a string without whitespaces<br>
116     * &lt;stringwithoutwhitespaces&gt; := a string, that can have whitespaces, but must be in double quotes<br>
117     * &lt;stringarray&gt; := "["&lt;string&gt;{&lt;whitespace&gt;&lt;string&gt;"]"
118     * </code>
119     *
120     * @param command
121     *            the command as a string
122     */
123    public void exec(String command) {
124        Console.commandNotification(command);
125        Command cmd = null;
126        CommandParser parser = new CommandParser();
127        parser.parse(command);
128        for (int i = 0; cmd == null && i < commandPackageList.size(); i++) {
129            cmd = loadCMD(commandPackageList.get(i) + "." + cmdPrefix + parser.getCommandName());
130        }
131        if (cmd == null) { // check if command is available as default command
132            cmd = loadCMD(defaultPackage + "." + cmdPrefix + parser.getCommandName());
133        }
134        if (cmd == null) {
135            Console.println("Unknown command");
136        }
137        else {
138            try {
139                cmd.run(parser.getParameters());
140            }
141            catch (InvalidParameterException e) {
142                Console.println("Usage: " + cmd.help());
143            }
144        }
145    }
146
147    /**
148     * <p>
149     * Helper method that loads a class and tries to cast it to {@link Command}.
150     * </p>
151     *
152     * @param className
153     *            qualified name of the class (including package name)
154     * @return if class is available and implement {@link Command} and instance of the class, null
155     *         otherwise
156     */
157    private Command loadCMD(String className) {
158        Command cmd = null;
159        try {
160            Class<?> cmdClass = Class.forName(className);
161            cmd = (Command) cmdClass.newInstance();
162        }
163        catch (NoClassDefFoundError e) {
164            String[] splitResult = e.getMessage().split("CMD");
165            String correctName = splitResult[splitResult.length - 1].replace(")", "");
166            Console.println("Did you mean " + correctName + "?");
167        }
168        catch (ClassNotFoundException e) {}
169        catch (IllegalAccessException e) {}
170        catch (InstantiationException e) {}
171        catch (ClassCastException e) {
172            Console.traceln(Level.WARNING, className + "found, but does not implement Command");
173        }
174        return cmd;
175    }
176
177    /**
178     * <p>
179     * reads all available commands from the registered command packages and returns a list of
180     * their names
181     * </p>
182     *
183     * @return an array containing the names of the available commands.
184     */
185    public Command[] getAvailableCommands() {
186        List<Command> commands = new ArrayList<Command>();
187        List<String> packages = new ArrayList<String>();
188        packages.addAll(commandPackageList);
189        packages.add(defaultPackage);
190       
191        FilenameFilter filter = new FilenameFilter() {
192            @Override
193            public boolean accept(File dir, String name) {
194                return (name != null) && (name.startsWith(cmdPrefix)) && (name.endsWith(".class"));
195            }
196        };
197       
198        List<String> classNames = new ArrayList<String>();
199        for (String packageName : packages) {
200            String path = packageName.replace('.', '/');
201            try {
202                Enumeration<URL> resources = ClassLoader.getSystemResources(path);
203               
204                while (resources.hasMoreElements()) {
205                    URL resource = resources.nextElement();
206                    File packageDir = new File(resource.getFile());
207                   
208                    if (packageDir.isDirectory()) {
209                        for (File classFile : packageDir.listFiles(filter)) {
210                            String className = classFile.getName().substring
211                                (0, classFile.getName().lastIndexOf('.'));
212                            classNames.add(packageName + "." + className);
213                        }
214                    }
215                    else {
216                        resource.getFile().startsWith("file:");
217                        int index = resource.getFile().lastIndexOf('!');
218                        if ((index > 0) && (resource.getFile().startsWith("file:")) &&
219                            (resource.getFile().endsWith("!/" + path)))
220                        {
221                            String jarFile = resource.getFile().substring("file:".length(), index);
222                           
223                            // we have to read the package content from a jar file
224                            JarInputStream jarInputStream = null;
225                            try {
226                                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
227                            }
228                            catch (Exception e) {
229                                e.printStackTrace();
230                                Console.traceln
231                                    (Level.WARNING, "could not read contents of jar " + jarFile);
232                            }
233
234                            JarEntry entry = null;
235                            do {
236                                entry = jarInputStream.getNextJarEntry();
237                                if ((entry != null) && (!entry.isDirectory()) &&
238                                    (entry.getName().startsWith(path)))
239                                {
240                                    String className = entry.getName().substring
241                                        (path.length(), entry.getName().lastIndexOf('.'));
242                                    classNames.add(packageName + "." + className);
243                                }
244                            }
245                            while (entry != null);
246                        }
247                    }
248                }
249            }
250            catch (IOException e) {
251                Console.traceln(Level.WARNING, "could not read commands of package " + packageName);
252            }
253        }
254       
255        Collections.sort(classNames, new Comparator<String>() {
256            @Override
257            public int compare(String arg1, String arg2) {
258                String str1 = arg1.substring(arg1.lastIndexOf('.') + cmdPrefix.length() + 1);
259                String str2 = arg2.substring(arg2.lastIndexOf('.') + cmdPrefix.length() + 1);
260                return str1.compareTo(str2);
261            }
262           
263        });
264        for (String className : classNames) {
265            String commandStr =
266                className.substring(className.lastIndexOf('.') + cmdPrefix.length() + 1);
267           
268            // commands may be found twice as a package may be available twice on the
269            // class path. Therefore check, if the command was already dumped before
270            // dumping it.
271            if (!commands.contains(commandStr)) {
272                // class may still be inner classes. Therefore load the command, to
273                // see if it is really available and a command.
274                Command cmd = loadCMD(className);
275                if (cmd != null) {
276                    commands.add(cmd);
277                }
278            }
279        }
280       
281        Command[] commandArray = commands.toArray(new Command[commands.size()]);
282        return commandArray;
283    }
284}
Note: See TracBrowser for help on using the repository browser.