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