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

Last change on this file since 2282 was 2282, checked in by pharms, 5 years ago
File size: 16.1 KB
RevLine 
[927]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.
[661]14
[1]15package de.ugoe.cs.util.console;
16
[661]17import java.io.File;
18import java.io.FileInputStream;
19import java.io.FilenameFilter;
20import java.io.IOException;
[2260]21import java.lang.reflect.InvocationTargetException;
[661]22import java.net.URL;
[1]23import java.util.ArrayList;
[1271]24import java.util.Arrays;
[664]25import java.util.Comparator;
[661]26import java.util.Enumeration;
[1]27import java.util.List;
[669]28import java.util.SortedSet;
29import java.util.TreeSet;
[661]30import java.util.jar.JarEntry;
31import java.util.jar.JarInputStream;
[639]32import java.util.logging.Level;
[1]33
[1243]34import de.ugoe.cs.util.StringTools;
35
[1]36/**
37 * <p>
[661]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.
[1]41 * </p>
42 * <p>
[175]43 * This class is implemented as a <i>Singleton</i>.
[1]44 * </p>
45 *
46 * @author Steffen Herbold
[175]47 * @version 1.0
[1]48 */
49public class CommandExecuter {
50
[661]51    /**
52     * <p>
53     * Handle of the CommandExecuter instance.
54     * </p>
55     */
56    private final static CommandExecuter theInstance = new CommandExecuter();
[1]57
[661]58    /**
59     * <p>
60     * Prefix of all command classes.
61     * </p>
62     */
63    private static final String cmdPrefix = "CMD";
[175]64
[661]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";
[1]71
[661]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     */
[2281]82    private List<CommandPackage> commandPackageList;
83
[1238]84    /**
85     * <p>
86     * the list of available commands (lazy instantiation in the method
87     * {@link #getAvailableCommands()})
88     * <p>
89     */
90    private Command[] availableCommands;
[1]91
[661]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    }
[1]102
[661]103    /**
104     * <p>
105     * Creates a new CommandExecuter. Private to prevent multiple instances (Singleton).
106     * </p>
107     */
108    private CommandExecuter() {
[2281]109        commandPackageList = new ArrayList<CommandPackage>();
[661]110    }
[1]111
[661]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
[766]119     * @throws IllegalArgumentException
[661]120     *             thrown if the package name is null or empty string
121     */
[2281]122    public void addCommandPackage(String pkg, ClassLoader loader) {
[661]123        if ("".equals(pkg) || pkg == null) {
[766]124            throw new IllegalArgumentException("package name must not be null or empty string");
[661]125        }
[2281]126        commandPackageList.add(new CommandPackage(pkg, loader));
127        availableCommands = null;
[661]128    }
[1]129
[661]130    /**
131     * <p>
132     * Executes the command defined by string. A command has the following form (mix of EBNF and
133     * natural language):
134     * </p>
135     * <code>
136     * &lt;command&gt; := &lt;commandname&gt;&lt;whitespace&gt;{&lt;parameter&gt;}<br>
137     * &lt;commandname&gt; := String without whitespaces. Has to be a valid Java class name<br>
138     * &lt;parameter&gt; := &lt;string&gt;|&lt;stringarray&gt;<br>
139     * &lt;string&gt; := &lt;stringwithoutwhitespaces&gt;|&lt;stringwithwhitespaces&gt;
140     * &lt;stringwithoutwhitespaces&gt; := a string without whitespaces<br>
141     * &lt;stringwithoutwhitespaces&gt; := a string, that can have whitespaces, but must be in double quotes<br>
142     * &lt;stringarray&gt; := "["&lt;string&gt;{&lt;whitespace&gt;&lt;string&gt;"]"
143     * </code>
144     *
145     * @param command
146     *            the command as a string
147     */
148    public void exec(String command) {
149        Console.commandNotification(command);
150        CommandParser parser = new CommandParser();
151        parser.parse(command);
[2281]152
153        Command cmd = getCMD(parser.getCommandName());
154
[661]155        if (cmd == null) {
156            Console.println("Unknown command");
157        }
158        else {
159            try {
160                cmd.run(parser.getParameters());
161            }
[766]162            catch (IllegalArgumentException e) {
[1355]163                Console.println("invalid parameter provided: " + e.getMessage());
[664]164                Console.println("Usage: " + cmd.help());
[661]165            }
[1355]166            catch (Exception e) {
167                Console.println("error executing command: " + e);
168                Console.logException(e);
169                Console.println("Usage: " + cmd.help());
170            }
[661]171        }
172    }
[1]173
[661]174    /**
175     * <p>
176     * Helper method that loads a class and tries to cast it to {@link Command}.
177     * </p>
178     *
179     * @param className
180     *            qualified name of the class (including package name)
181     * @return if class is available and implement {@link Command} and instance of the class, null
182     *         otherwise
183     */
[718]184    public Command getCMD(String commandName) {
[2281]185        for (Command candidate : getAvailableCommands()) {
186            if (candidate.getClass().getSimpleName().equals(cmdPrefix + commandName)) {
187                return candidate;
188            }
[718]189        }
[2281]190
191        return null;
[718]192    }
[661]193
194    /**
195     * <p>
[669]196     * reads all available commands from the registered command packages and returns a list of their
197     * names
[661]198     * </p>
[669]199     *
[661]200     * @return an array containing the names of the available commands.
201     */
[664]202    public Command[] getAvailableCommands() {
[1238]203        if (availableCommands == null) {
[2281]204            // List<Command> commands = new ArrayList<Command>();
205            List<CommandPackage> packages = new ArrayList<CommandPackage>();
[1238]206            packages.addAll(commandPackageList);
[2281]207            packages.add(new CommandPackage(defaultPackage, this.getClass().getClassLoader()));
[669]208
[1238]209            FilenameFilter filter = new FilenameFilter() {
210                @Override
211                public boolean accept(File dir, String name) {
[2281]212                    return (name != null) && (name.startsWith(cmdPrefix)) &&
213                        (name.endsWith(".class"));
[1238]214                }
215            };
[669]216
[2281]217            SortedSet<Command> commands = new TreeSet<Command>(new Comparator<Command>() {
[1238]218                @Override
[2281]219                public int compare(Command arg1, Command arg2) {
220                    String str1 = arg1.getClass().getSimpleName().substring(cmdPrefix.length());
221                    String str2 = arg2.getClass().getSimpleName().substring(cmdPrefix.length());
[1238]222                    return str1.compareTo(str2);
223                }
[669]224
[1238]225            });
[669]226
[2281]227            for (CommandPackage commandPackage : packages) {
228                String path = commandPackage.getPackageName().replace('.', '/');
[1238]229                try {
[2281]230                    ClassLoader loader = commandPackage.getClassLoader();
[669]231
[2281]232                    if (loader == null) {
233                        loader = ClassLoader.getSystemClassLoader();
234                    }
235
236                    Enumeration<URL> resources = loader.getResources(path);
237
[1238]238                    while (resources.hasMoreElements()) {
239                        URL resource = resources.nextElement();
240                        File packageDir = new File(resource.getFile());
[669]241
[1238]242                        if (packageDir.isDirectory()) {
[2281]243                            File[] classFiles = packageDir.listFiles(filter);
244                            if (classFiles != null) {
245                                for (File classFile : classFiles) {
246                                    String className = classFile.getName()
247                                        .substring(0, classFile.getName().lastIndexOf('.'));
248                                    Class<?> clazz =
249                                        loader.loadClass(commandPackage.getPackageName() + "." +
250                                            className);
251                                    if (Command.class.isAssignableFrom(clazz)) {
[2282]252                                        commands.add((Command) clazz.getConstructor().newInstance());
[2281]253                                    }
254                                }
255                            }
[661]256                        }
[1238]257                        else {
258                            int index = resource.getFile().lastIndexOf('!');
259                            if ((index > 0) && (resource.getFile().startsWith("file:")) &&
260                                (resource.getFile().endsWith("!/" + path)))
261                            {
262                                String jarFile =
263                                    resource.getFile().substring("file:".length(), index);
[669]264
[1238]265                                // we have to read the package content from a jar file
266                                JarInputStream jarInputStream = null;
267                                try {
268                                    jarInputStream =
269                                        new JarInputStream(new FileInputStream(jarFile));
270                                    JarEntry entry = null;
271                                    do {
272                                        entry = jarInputStream.getNextJarEntry();
273                                        if ((entry != null) && (!entry.isDirectory()) &&
[2281]274                                            (entry.getName().startsWith(path)))
[1238]275                                        {
[2281]276                                            String className = entry.getName()
277                                                .substring(path.length() + 1,
278                                                           entry.getName().lastIndexOf('.'));
279                                            Class<?> clazz =
280                                                loader.loadClass(commandPackage.getPackageName() +
281                                                    "." + className);
[2282]282                                           
283                                            Console.traceln(Level.WARNING, clazz.getName());
[2281]284                                            if (Command.class.isAssignableFrom(clazz)) {
285                                                commands.add((Command) clazz.getConstructor().newInstance());
286                                            }
[1238]287                                        }
[749]288                                    }
[1238]289                                    while (entry != null);
[749]290                                }
[1238]291                                finally {
292                                    if (jarInputStream != null) {
293                                        jarInputStream.close();
294                                    }
295                                }
296
[661]297                            }
298                        }
299                    }
300                }
[1238]301                catch (IOException e) {
[2281]302                    Console.traceln(Level.WARNING, "could not read commands of package " +
303                        commandPackage.getPackageName());
[1238]304                }
[2281]305                catch (ClassNotFoundException e) {
306                    Console.traceln(Level.WARNING, "could not load a command of package " +
307                        commandPackage.getPackageName() + ": " + e);
[1238]308                }
[2281]309                catch (InstantiationException e) {
310                    Console.traceln(Level.WARNING, "could not load a command of package " +
311                        commandPackage.getPackageName() + ": " + e);
312                }
313                catch (IllegalAccessException e) {
314                    Console.traceln(Level.WARNING, "could not load a command of package " +
315                        commandPackage.getPackageName() + ": " + e);
316                }
317                catch (IllegalArgumentException e) {
318                    Console.traceln(Level.WARNING, "could not load a command of package " +
319                        commandPackage.getPackageName() + ": " + e);
320                }
321                catch (InvocationTargetException e) {
322                    Console.traceln(Level.WARNING, "could not load a command of package " +
323                        commandPackage.getPackageName() + ": " + e);
324                }
325                catch (NoSuchMethodException e) {
326                    Console.traceln(Level.WARNING, "could not load a command of package " +
327                        commandPackage.getPackageName() + ": " + e);
328                }
329                catch (SecurityException e) {
330                    Console.traceln(Level.WARNING, "could not load a command of package " +
331                        commandPackage.getPackageName() + ": " + e);
332                }
[661]333            }
[669]334
[1238]335            availableCommands = commands.toArray(new Command[commands.size()]);
[661]336        }
[2281]337
[1271]338        return Arrays.copyOf(availableCommands, availableCommands.length);
[661]339    }
[2281]340
[731]341    /**
342     * <p>
343     * Get a copy of the currently registered command packages.
344     * </p>
345     *
346     * @return currently registered command packages
347     */
348    public List<String> getCommandPackages() {
[2281]349        List<String> commandPackageListCopy = new ArrayList<>();
350
351        commandPackageListCopy.add(defaultPackage);
352
353        for (CommandPackage pkg : commandPackageList) {
354            commandPackageListCopy.add(pkg.getPackageName());
355        }
356
[731]357        return commandPackageListCopy;
358    }
[1238]359
360    /**
361     * <p>
362     * this method method performs an auto completion of the provided String as far as possible
[2281]363     * regarding the available commands. It auto completes to the full command name, if only one
364     * command matches the given prefix. It auto completes to the common denominator, if several
365     * commands match the prefix
[1238]366     * </p>
367     *
[2281]368     * @param commandPrefix
369     *            the prefix to be auto completed
[1238]370     *
371     * @return as described
372     */
373    public String autoCompleteCommand(String commandPrefix) {
374        Command[] commands = getAvailableCommands();
[2281]375
[1243]376        String[] completions = new String[commands.length];
[2281]377
[1243]378        for (int i = 0; i < commands.length; i++) {
379            completions[i] = commands[i].getClass().getSimpleName().substring(3);
[1238]380        }
[2281]381
[1243]382        return StringTools.autocomplete(commandPrefix, completions);
[1238]383    }
[2281]384
385    /**
386     * represents a command package with a package name and the class loader to use
387     */
388    private class CommandPackage {
389        /**
390         * the name of the represented package
391         */
392        private String packageName;
393
394        /**
395         * the class loader to use to load the package
396         */
397        private ClassLoader classLoader;
398
399        /**
400         * <p>
401         * instantiate the fields
402         * </p>
403         */
404        public CommandPackage(String packageName, ClassLoader classLoader) {
405            super();
406            this.packageName = packageName;
407            this.classLoader = classLoader;
408        }
409
410        /**
411         * @return the packageName
412         */
413        public String getPackageName() {
414            return packageName;
415        }
416
417        /**
418         * @return the classLoader
419         */
420        public ClassLoader getClassLoader() {
421            return classLoader;
422        }
423
424    }
[1]425}
Note: See TracBrowser for help on using the repository browser.