1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package it.jnrpe.commands;
17
18 import it.jnrpe.JNRPELIB;
19 import it.jnrpe.ReturnValue;
20 import it.jnrpe.Status;
21 import it.jnrpe.events.EventsUtil;
22 import it.jnrpe.events.IJNRPEEventListener;
23 import it.jnrpe.events.LogEvent;
24 import it.jnrpe.plugins.IPluginRepository;
25 import it.jnrpe.plugins.PluginProxy;
26
27 import java.util.Collection;
28 import java.util.regex.Matcher;
29
30
31
32
33
34
35
36 public final class CommandInvoker {
37
38
39
40
41 private final boolean acceptParams;
42
43
44
45
46 private final IPluginRepository pluginRepository;
47
48
49
50
51 private final CommandRepository commandRepository;
52
53
54
55
56 private final Collection<IJNRPEEventListener> listenersList;
57
58
59
60
61
62
63
64
65
66
67
68
69
70 public CommandInvoker(final IPluginRepository pluginRepo,
71 final CommandRepository commandRepo, final boolean acceptParams,
72 final Collection<IJNRPEEventListener> listeners) {
73 this.acceptParams = acceptParams;
74 pluginRepository = pluginRepo;
75 commandRepository = commandRepo;
76 listenersList = listeners;
77 }
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92 public ReturnValue invoke(final String commandName, final String[] argsAry) {
93 if ("_NRPE_CHECK".equals(commandName)) {
94 return new ReturnValue(Status.OK, JNRPELIB.VERSION);
95 }
96
97 CommandDefinition cd = commandRepository.getCommand(commandName);
98
99 if (cd == null) {
100 return new ReturnValue(Status.UNKNOWN, "Bad command");
101 }
102
103 return invoke(cd, argsAry);
104 }
105
106
107
108
109
110
111
112
113
114
115
116
117 public ReturnValue invoke(final CommandDefinition cd, final String[] argsAry) {
118 String pluginName = cd.getPluginName();
119 try {
120
121 String[] commandLine = cd.getCommandLine();
122
123 if (acceptParams) {
124 for (int j = 0; commandLine != null && j < commandLine.length; j++) {
125 for (int i = 0; i < argsAry.length; i++) {
126 commandLine[j] = commandLine[j].replaceAll(
127 "\\$[Aa][Rr][Gg]" + (i + 1) + "\\$",
128 Matcher.quoteReplacement(argsAry[i]));
129 }
130 }
131 }
132
133 PluginProxy plugin = (PluginProxy) pluginRepository
134 .getPlugin(pluginName);
135
136 if (plugin == null) {
137 EventsUtil.sendEvent(listenersList, this, LogEvent.INFO,
138 "Unable to instantiate plugin named " + pluginName);
139 return new ReturnValue(Status.UNKNOWN,
140 "Error instantiating plugin '" + pluginName
141 + "' : bad plugin name?");
142 }
143
144 plugin.addListeners(listenersList);
145
146 if (commandLine != null) {
147 return plugin.execute(commandLine);
148 } else {
149 return plugin.execute(new String[0]);
150 }
151 } catch (Throwable thr) {
152 return new ReturnValue(Status.UNKNOWN, "Plugin [" + pluginName
153 + "] execution error: " + thr.getMessage());
154 }
155 }
156 }