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 | package de.ugoe.cs.util.console;
|
---|
16 |
|
---|
17 | import java.io.File;
|
---|
18 | import java.io.FileInputStream;
|
---|
19 | import java.io.FilenameFilter;
|
---|
20 | import java.io.IOException;
|
---|
21 | import java.lang.reflect.InvocationTargetException;
|
---|
22 | import java.net.URL;
|
---|
23 | import java.util.ArrayList;
|
---|
24 | import java.util.Arrays;
|
---|
25 | import java.util.Comparator;
|
---|
26 | import java.util.Enumeration;
|
---|
27 | import java.util.List;
|
---|
28 | import java.util.SortedSet;
|
---|
29 | import java.util.TreeSet;
|
---|
30 | import java.util.jar.JarEntry;
|
---|
31 | import java.util.jar.JarInputStream;
|
---|
32 | import java.util.logging.Level;
|
---|
33 |
|
---|
34 | import 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 | */
|
---|
49 | public 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<CommandPackage> 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<CommandPackage>();
|
---|
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, ClassLoader loader) {
|
---|
123 | if ("".equals(pkg) || pkg == null) {
|
---|
124 | throw new IllegalArgumentException("package name must not be null or empty string");
|
---|
125 | }
|
---|
126 | commandPackageList.add(new CommandPackage(pkg, loader));
|
---|
127 | availableCommands = null;
|
---|
128 | }
|
---|
129 |
|
---|
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 | CommandParser parser = new CommandParser();
|
---|
151 | parser.parse(command);
|
---|
152 |
|
---|
153 | Command cmd = getCMD(parser.getCommandName());
|
---|
154 |
|
---|
155 | if (cmd == null) {
|
---|
156 | Console.println("Unknown command");
|
---|
157 | }
|
---|
158 | else {
|
---|
159 | try {
|
---|
160 | cmd.run(parser.getParameters());
|
---|
161 | }
|
---|
162 | catch (IllegalArgumentException e) {
|
---|
163 | Console.println("invalid parameter provided: " + e.getMessage());
|
---|
164 | Console.println("Usage: " + cmd.help());
|
---|
165 | }
|
---|
166 | catch (Exception e) {
|
---|
167 | Console.println("error executing command: " + e);
|
---|
168 | Console.logException(e);
|
---|
169 | Console.println("Usage: " + cmd.help());
|
---|
170 | }
|
---|
171 | }
|
---|
172 | }
|
---|
173 |
|
---|
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 | */
|
---|
184 | public Command getCMD(String commandName) {
|
---|
185 | for (Command candidate : getAvailableCommands()) {
|
---|
186 | if (candidate.getClass().getSimpleName().equals(cmdPrefix + commandName)) {
|
---|
187 | return candidate;
|
---|
188 | }
|
---|
189 | }
|
---|
190 |
|
---|
191 | return null;
|
---|
192 | }
|
---|
193 |
|
---|
194 | /**
|
---|
195 | * <p>
|
---|
196 | * reads all available commands from the registered command packages and returns a list of their
|
---|
197 | * names
|
---|
198 | * </p>
|
---|
199 | *
|
---|
200 | * @return an array containing the names of the available commands.
|
---|
201 | */
|
---|
202 | public Command[] getAvailableCommands() {
|
---|
203 | if (availableCommands == null) {
|
---|
204 | // List<Command> commands = new ArrayList<Command>();
|
---|
205 | List<CommandPackage> packages = new ArrayList<CommandPackage>();
|
---|
206 | packages.addAll(commandPackageList);
|
---|
207 | packages.add(new CommandPackage(defaultPackage, this.getClass().getClassLoader()));
|
---|
208 |
|
---|
209 | FilenameFilter filter = new FilenameFilter() {
|
---|
210 | @Override
|
---|
211 | public boolean accept(File dir, String name) {
|
---|
212 | return (name != null) && (name.startsWith(cmdPrefix)) &&
|
---|
213 | (name.endsWith(".class"));
|
---|
214 | }
|
---|
215 | };
|
---|
216 |
|
---|
217 | SortedSet<Command> commands = new TreeSet<Command>(new Comparator<Command>() {
|
---|
218 | @Override
|
---|
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());
|
---|
222 | return str1.compareTo(str2);
|
---|
223 | }
|
---|
224 |
|
---|
225 | });
|
---|
226 |
|
---|
227 | for (CommandPackage commandPackage : packages) {
|
---|
228 | String path = commandPackage.getPackageName().replace('.', '/');
|
---|
229 | try {
|
---|
230 | ClassLoader loader = commandPackage.getClassLoader();
|
---|
231 |
|
---|
232 | if (loader == null) {
|
---|
233 | loader = ClassLoader.getSystemClassLoader();
|
---|
234 | }
|
---|
235 |
|
---|
236 | Enumeration<URL> resources = loader.getResources(path);
|
---|
237 |
|
---|
238 | while (resources.hasMoreElements()) {
|
---|
239 | URL resource = resources.nextElement();
|
---|
240 | File packageDir = new File(resource.getFile());
|
---|
241 |
|
---|
242 | if (packageDir.isDirectory()) {
|
---|
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)) {
|
---|
252 | commands.add((Command) clazz.getConstructor().newInstance());
|
---|
253 | }
|
---|
254 | }
|
---|
255 | }
|
---|
256 | }
|
---|
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);
|
---|
264 |
|
---|
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()) &&
|
---|
274 | (entry.getName().startsWith(path)))
|
---|
275 | {
|
---|
276 | String className = entry.getName()
|
---|
277 | .substring(path.length() + 1,
|
---|
278 | entry.getName().lastIndexOf('.'));
|
---|
279 | Class<?> clazz =
|
---|
280 | loader.loadClass(commandPackage.getPackageName() +
|
---|
281 | "." + className);
|
---|
282 |
|
---|
283 | Console.traceln(Level.WARNING, clazz.getName());
|
---|
284 | if (Command.class.isAssignableFrom(clazz)) {
|
---|
285 | commands.add((Command) clazz.getConstructor().newInstance());
|
---|
286 | }
|
---|
287 | }
|
---|
288 | }
|
---|
289 | while (entry != null);
|
---|
290 | }
|
---|
291 | finally {
|
---|
292 | if (jarInputStream != null) {
|
---|
293 | jarInputStream.close();
|
---|
294 | }
|
---|
295 | }
|
---|
296 |
|
---|
297 | }
|
---|
298 | }
|
---|
299 | }
|
---|
300 | }
|
---|
301 | catch (IOException e) {
|
---|
302 | Console.traceln(Level.WARNING, "could not read commands of package " +
|
---|
303 | commandPackage.getPackageName());
|
---|
304 | }
|
---|
305 | catch (ClassNotFoundException e) {
|
---|
306 | Console.traceln(Level.WARNING, "could not load a command of package " +
|
---|
307 | commandPackage.getPackageName() + ": " + e);
|
---|
308 | }
|
---|
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 | }
|
---|
333 | }
|
---|
334 |
|
---|
335 | availableCommands = commands.toArray(new Command[commands.size()]);
|
---|
336 | }
|
---|
337 |
|
---|
338 | return Arrays.copyOf(availableCommands, availableCommands.length);
|
---|
339 | }
|
---|
340 |
|
---|
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() {
|
---|
349 | List<String> commandPackageListCopy = new ArrayList<>();
|
---|
350 |
|
---|
351 | commandPackageListCopy.add(defaultPackage);
|
---|
352 |
|
---|
353 | for (CommandPackage pkg : commandPackageList) {
|
---|
354 | commandPackageListCopy.add(pkg.getPackageName());
|
---|
355 | }
|
---|
356 |
|
---|
357 | return commandPackageListCopy;
|
---|
358 | }
|
---|
359 |
|
---|
360 | /**
|
---|
361 | * <p>
|
---|
362 | * this method method performs an auto completion of the provided String as far as possible
|
---|
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
|
---|
366 | * </p>
|
---|
367 | *
|
---|
368 | * @param commandPrefix
|
---|
369 | * the prefix to be auto completed
|
---|
370 | *
|
---|
371 | * @return as described
|
---|
372 | */
|
---|
373 | public String autoCompleteCommand(String commandPrefix) {
|
---|
374 | Command[] commands = getAvailableCommands();
|
---|
375 |
|
---|
376 | String[] completions = new String[commands.length];
|
---|
377 |
|
---|
378 | for (int i = 0; i < commands.length; i++) {
|
---|
379 | completions[i] = commands[i].getClass().getSimpleName().substring(3);
|
---|
380 | }
|
---|
381 |
|
---|
382 | return StringTools.autocomplete(commandPrefix, completions);
|
---|
383 | }
|
---|
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 | }
|
---|
425 | }
|
---|