1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package it.jnrpe.server.console;
17
18 import it.jnrpe.JNRPE;
19 import it.jnrpe.commands.CommandDefinition;
20 import it.jnrpe.commands.CommandRepository;
21 import it.jnrpe.plugins.IPluginRepository;
22 import it.jnrpe.plugins.PluginDefinition;
23 import it.jnrpe.plugins.UnknownPluginException;
24
25 import java.util.Map;
26 import java.util.TreeMap;
27
28 import jline.console.ConsoleReader;
29
30 import org.apache.commons.lang.text.StrMatcher;
31 import org.apache.commons.lang.text.StrTokenizer;
32
33
34
35
36
37
38 public class CommandExecutor {
39
40 private final Map<String, IConsoleCommand> commandMap = new TreeMap<String, IConsoleCommand>();
41
42 private static CommandExecutor instance = null;
43
44 public static synchronized CommandExecutor getInstance(
45 ConsoleReader consoleReader, JNRPE jnrpe,
46 IPluginRepository pluginRepository,
47 CommandRepository commandRepository) {
48 if (instance == null) {
49 instance = new CommandExecutor();
50 instance.commandMap.put(ExitCommand.NAME, new ExitCommand(
51 consoleReader, jnrpe));
52 instance.commandMap.put(HelpCommand.NAME, new HelpCommand(
53 consoleReader, jnrpe, instance.commandMap));
54
55 for (PluginDefinition pd : pluginRepository.getAllPlugins()) {
56 try {
57 instance.commandMap.put(PluginCommand.NAME
58 + pd.getName().toLowerCase(), new PluginCommand(
59 consoleReader, jnrpe, pd.getName(),
60 pluginRepository));
61 } catch (UnknownPluginException e) {
62
63 }
64 }
65
66 for (CommandDefinition cd : commandRepository.getAllCommands()) {
67 instance.commandMap
68 .put(CommandConsoleCommand.NAME
69 + cd.getName().toLowerCase(),
70 new CommandConsoleCommand(consoleReader, jnrpe,
71 cd.getName(), pluginRepository,
72 commandRepository));
73 }
74 }
75
76 return instance;
77 }
78
79 private IConsoleCommand getCommand(String commandName) {
80 return commandMap.get(commandName.toLowerCase());
81 }
82
83 public boolean executeCommand(String commandLine) throws Exception {
84 StrTokenizer strtok = new StrTokenizer(commandLine,
85 StrMatcher.charMatcher(' '), StrMatcher.quoteMatcher());
86 String[] tokensAry = strtok.getTokenArray();
87 String commandName = tokensAry[0];
88 String[] params;
89 if (tokensAry.length == 1) {
90 params = new String[0];
91 } else {
92 params = new String[tokensAry.length - 1];
93 System.arraycopy(tokensAry, 1, params, 0, params.length);
94 }
95
96 IConsoleCommand command = getCommand(commandName);
97 if (command != null) {
98 return command.execute(params);
99 } else {
100 throw new UnknownCommandException("Unknown command :'"
101 + commandName + "'");
102 }
103 }
104 }