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

Last change on this file since 1271 was 1271, checked in by pharms, 11 years ago
  • removed find bugs warnings
File size: 13.9 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15
16package de.ugoe.cs.util.console;
17
18import java.io.File;
19import java.io.FileInputStream;
20import java.io.FilenameFilter;
21import java.io.IOException;
22import java.net.URL;
23import java.util.ArrayList;
24import java.util.Arrays;
25import java.util.Comparator;
26import java.util.Enumeration;
27import java.util.List;
28import java.util.SortedSet;
29import java.util.TreeSet;
30import java.util.jar.JarEntry;
31import java.util.jar.JarInputStream;
32import java.util.logging.Level;
33
34import de.ugoe.cs.util.StringTools;
35
36/**
37 * <p>
38 * Executes commands. The commands have to implement the {@link Command} interface and be in
39 * packages registered using addCommandPackage(). Additionally, default commands are implemented in
40 * the de.ugoe.cs.util.console.defaultcommands package.
41 * </p>
42 * <p>
43 * This class is implemented as a <i>Singleton</i>.
44 * </p>
45 *
46 * @author Steffen Herbold
47 * @version 1.0
48 */
49public class CommandExecuter {
50
51    /**
52     * <p>
53     * Handle of the CommandExecuter instance.
54     * </p>
55     */
56    private final static CommandExecuter theInstance = new CommandExecuter();
57
58    /**
59     * <p>
60     * Prefix of all command classes.
61     * </p>
62     */
63    private static final String cmdPrefix = "CMD";
64
65    /**
66     * <p>
67     * Name of the package for default commands.
68     * </p>
69     */
70    private static final String defaultPackage = "de.ugoe.cs.util.console.defaultcommands";
71
72    /**
73     * <p>
74     * List of packages in which commands may be defined. The exec methods trys to load command from
75     * these packages in the order they have been added.
76     * </p>
77     * <p>
78     * The de.ugoe.cs.util.console.defaultcommands package has always lowest priority, unless it is
79     * specifically added.
80     * </p>
81     */
82    private List<String> commandPackageList;
83   
84    /**
85     * <p>
86     * the list of available commands (lazy instantiation in the method
87     * {@link #getAvailableCommands()})
88     * <p>
89     */
90    private Command[] availableCommands;
91
92    /**
93     * <p>
94     * Returns the instance of CommandExecuter. If no instances exists yet, a new one is created.
95     * </p>
96     *
97     * @return the instance of CommandExecuter
98     */
99    public static synchronized CommandExecuter getInstance() {
100        return theInstance;
101    }
102
103    /**
104     * <p>
105     * Creates a new CommandExecuter. Private to prevent multiple instances (Singleton).
106     * </p>
107     */
108    private CommandExecuter() {
109        commandPackageList = new ArrayList<String>();
110    }
111
112    /**
113     * <p>
114     * Adds a package that will be used by {@link #exec(String)} to load command from.
115     * </p>
116     *
117     * @param pkg
118     *            package where commands are located
119     * @throws IllegalArgumentException
120     *             thrown if the package name is null or empty string
121     */
122    public void addCommandPackage(String pkg) {
123        if ("".equals(pkg) || pkg == null) {
124            throw new IllegalArgumentException("package name must not be null or empty string");
125        }
126        commandPackageList.add(pkg);
127    }
128
129    /**
130     * <p>
131     * Executes the command defined by string. A command has the following form (mix of EBNF and
132     * natural language):
133     * </p>
134     * <code>
135     * &lt;command&gt; := &lt;commandname&gt;&lt;whitespace&gt;{&lt;parameter&gt;}<br>
136     * &lt;commandname&gt; := String without whitespaces. Has to be a valid Java class name<br>
137     * &lt;parameter&gt; := &lt;string&gt;|&lt;stringarray&gt;<br>
138     * &lt;string&gt; := &lt;stringwithoutwhitespaces&gt;|&lt;stringwithwhitespaces&gt;
139     * &lt;stringwithoutwhitespaces&gt; := a string without whitespaces<br>
140     * &lt;stringwithoutwhitespaces&gt; := a string, that can have whitespaces, but must be in double quotes<br>
141     * &lt;stringarray&gt; := "["&lt;string&gt;{&lt;whitespace&gt;&lt;string&gt;"]"
142     * </code>
143     *
144     * @param command
145     *            the command as a string
146     */
147    public void exec(String command) {
148        Console.commandNotification(command);
149        Command cmd = null;
150        CommandParser parser = new CommandParser();
151        parser.parse(command);
152        for (int i = 0; cmd == null && i < commandPackageList.size(); i++) {
153            cmd = loadCMD(commandPackageList.get(i) + "." + cmdPrefix + parser.getCommandName());
154        }
155        if (cmd == null) { // check if command is available as default command
156            cmd = loadCMD(defaultPackage + "." + cmdPrefix + parser.getCommandName());
157        }
158        if (cmd == null) {
159            Console.println("Unknown command");
160        }
161        else {
162            try {
163                cmd.run(parser.getParameters());
164            }
165            catch (IllegalArgumentException e) {
166                Console.println("Usage: " + cmd.help());
167            }
168        }
169    }
170
171    /**
172     * <p>
173     * Helper method that loads a class and tries to cast it to {@link Command}.
174     * </p>
175     *
176     * @param className
177     *            qualified name of the class (including package name)
178     * @return if class is available and implement {@link Command} and instance of the class, null
179     *         otherwise
180     */
181    public Command loadCMD(String className) {
182        Command cmd = null;
183        try {
184            Class<?> cmdClass = Class.forName(className);
185            cmd = (Command) cmdClass.newInstance();
186        }
187        catch (NoClassDefFoundError e) {
188            String[] splitResult = e.getMessage().split("CMD");
189            String correctName = splitResult[splitResult.length - 1].replace(")", "");
190            Console.println("Did you mean " + correctName + "?");
191        }
192        catch (ClassNotFoundException e) {}
193        catch (IllegalAccessException e) {}
194        catch (InstantiationException e) {}
195        catch (ClassCastException e) {
196            Console.traceln(Level.WARNING, className + "found, but does not implement Command");
197        }
198        return cmd;
199    }
200   
201    /**
202     * <p>
203     * Helper method that loads a class and tries to cast it to {@link Command}.
204     * </p>
205     *
206     * @param className
207     *            qualified name of the class (including package name)
208     * @return if class is available and implement {@link Command} and instance of the class, null
209     *         otherwise
210     */
211    public Command getCMD(String commandName) {
212        Command cmd = null;
213        for (int i = 0; cmd == null && i < commandPackageList.size(); i++) {
214            cmd = loadCMD(commandPackageList.get(i) + "." + cmdPrefix + commandName);
215        }
216        if (cmd == null) { // check if command is available as default command
217            cmd = loadCMD(defaultPackage + "." + cmdPrefix + commandName);
218        }
219        return cmd;
220    }
221
222    /**
223     * <p>
224     * reads all available commands from the registered command packages and returns a list of their
225     * names
226     * </p>
227     *
228     * @return an array containing the names of the available commands.
229     */
230    public Command[] getAvailableCommands() {
231        if (availableCommands == null) {
232            List<Command> commands = new ArrayList<Command>();
233            List<String> packages = new ArrayList<String>();
234            packages.addAll(commandPackageList);
235            packages.add(defaultPackage);
236
237            FilenameFilter filter = new FilenameFilter() {
238                @Override
239                public boolean accept(File dir, String name) {
240                    return
241                        (name != null) && (name.startsWith(cmdPrefix)) && (name.endsWith(".class"));
242                }
243            };
244
245            SortedSet<String> classNames = new TreeSet<String>(new Comparator<String>() {
246                @Override
247                public int compare(String arg1, String arg2) {
248                    String str1 = arg1.substring(arg1.lastIndexOf('.') + cmdPrefix.length() + 1);
249                    String str2 = arg2.substring(arg2.lastIndexOf('.') + cmdPrefix.length() + 1);
250                    return str1.compareTo(str2);
251                }
252
253            });
254
255            for (String packageName : packages) {
256                String path = packageName.replace('.', '/');
257                try {
258                    Enumeration<URL> resources = ClassLoader.getSystemResources(path);
259
260                    while (resources.hasMoreElements()) {
261                        URL resource = resources.nextElement();
262                        File packageDir = new File(resource.getFile());
263
264                        if (packageDir.isDirectory()) {
265                            for (File classFile : packageDir.listFiles(filter)) {
266                                String className = classFile.getName().substring
267                                    (0, classFile.getName().lastIndexOf('.'));
268                                classNames.add(packageName + "." + className);
269                            }
270                        }
271                        else {
272                            int index = resource.getFile().lastIndexOf('!');
273                            if ((index > 0) && (resource.getFile().startsWith("file:")) &&
274                                (resource.getFile().endsWith("!/" + path)))
275                            {
276                                String jarFile =
277                                    resource.getFile().substring("file:".length(), index);
278
279                                // we have to read the package content from a jar file
280                                JarInputStream jarInputStream = null;
281                                try {
282                                    jarInputStream =
283                                        new JarInputStream(new FileInputStream(jarFile));
284                                    JarEntry entry = null;
285                                    do {
286                                        entry = jarInputStream.getNextJarEntry();
287                                        if ((entry != null) && (!entry.isDirectory()) &&
288                                                (entry.getName().startsWith(path)))
289                                        {
290                                            String className = entry.getName().substring
291                                                (path.length() + 1, entry.getName().lastIndexOf('.'));
292                                            classNames.add(packageName + "." + className);
293                                        }
294                                    }
295                                    while (entry != null);
296                                }
297                                catch (Exception e) {
298                                    e.printStackTrace();
299                                    Console.traceln(Level.WARNING, "could not read contents of " +
300                                                    "jar " + jarFile);
301                                }
302                                finally {
303                                    if (jarInputStream != null) {
304                                        jarInputStream.close();
305                                    }
306                                }
307
308                            }
309                        }
310                    }
311                }
312                catch (IOException e) {
313                    Console.traceln
314                        (Level.WARNING, "could not read commands of package " + packageName);
315                }
316            }
317
318            for (String className : classNames) {
319                // class may still be inner classes. Therefore load the command, to
320                // see if it is really available and a command.
321                Command cmd = loadCMD(className);
322                if (cmd != null) {
323                    commands.add(cmd);
324                }
325            }
326
327            availableCommands = commands.toArray(new Command[commands.size()]);
328        }
329       
330        return Arrays.copyOf(availableCommands, availableCommands.length);
331    }
332   
333    /**
334     * <p>
335     * Get a copy of the currently registered command packages.
336     * </p>
337     *
338     * @return currently registered command packages
339     */
340    public List<String> getCommandPackages() {
341        List<String> commandPackageListCopy = new ArrayList<String>(commandPackageList);
342        commandPackageListCopy.add(0, defaultPackage);
343        return commandPackageListCopy;
344    }
345
346    /**
347     * <p>
348     * this method method performs an auto completion of the provided String as far as possible
349     * regarding the available commands. It auto completes to the full command name, if only
350     * one command matches the given prefix. It auto completes to the common denominator, if
351     * several commands match the prefix
352     * </p>
353     *
354     * @param commandPrefix the prefix to be auto completed
355     *
356     * @return as described
357     */
358    public String autoCompleteCommand(String commandPrefix) {
359        Command[] commands = getAvailableCommands();
360       
361        String[] completions = new String[commands.length];
362       
363        for (int i = 0; i < commands.length; i++) {
364            completions[i] = commands[i].getClass().getSimpleName().substring(3);
365        }
366       
367        return StringTools.autocomplete(commandPrefix, completions);
368    }
369}
Note: See TracBrowser for help on using the repository browser.