56d0b8a724a008f467e9113ca5bd6054a2051f31
[public/netxms.git] / src / java / netxms-eclipse / ObjectTools / src / org / netxms / ui / eclipse / objecttools / api / ObjectToolExecutor.java
1 /**
2 *
3 */
4 package org.netxms.ui.eclipse.objecttools.api;
5
6 import java.io.IOException;
7 import java.net.URLEncoder;
8 import java.util.Set;
9 import org.eclipse.core.runtime.IProgressMonitor;
10 import org.eclipse.core.runtime.Platform;
11 import org.eclipse.ui.IWorkbenchPage;
12 import org.eclipse.ui.IWorkbenchWindow;
13 import org.eclipse.ui.PartInitException;
14 import org.eclipse.ui.PlatformUI;
15 import org.netxms.client.AgentFile;
16 import org.netxms.client.NXCSession;
17 import org.netxms.client.objecttools.ObjectTool;
18 import org.netxms.ui.eclipse.console.resources.StatusDisplayInfo;
19 import org.netxms.ui.eclipse.jobs.ConsoleJob;
20 import org.netxms.ui.eclipse.objecttools.Activator;
21 import org.netxms.ui.eclipse.objecttools.Messages;
22 import org.netxms.ui.eclipse.objecttools.views.AgentActionResults;
23 import org.netxms.ui.eclipse.objecttools.views.BrowserView;
24 import org.netxms.ui.eclipse.objecttools.views.FileViewer;
25 import org.netxms.ui.eclipse.objecttools.views.LocalCommandResults;
26 import org.netxms.ui.eclipse.objecttools.views.TableToolResults;
27 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
28 import org.netxms.ui.eclipse.tools.MessageDialogHelper;
29
30 /**
31 * Executor for object tool
32 */
33 public final class ObjectToolExecutor
34 {
35 /**
36 * Private constructor to forbid instantiation
37 */
38 private ObjectToolExecutor()
39 {
40 }
41
42 /**
43 * Check if tool is allowed for execution on each node from set
44 *
45 * @param tool
46 * @param nodes
47 * @return
48 */
49 public static boolean isToolAllowed(ObjectTool tool, Set<NodeInfo> nodes)
50 {
51 if (tool.getType() != ObjectTool.TYPE_INTERNAL)
52 return true;
53
54 ObjectToolHandler handler = ObjectToolsCache.findHandler(tool.getData());
55 if (handler != null)
56 {
57 for(NodeInfo n : nodes)
58 if (!handler.canExecuteOnNode(n.object, tool))
59 return false;
60 return true;
61 }
62 else
63 {
64 return false;
65 }
66 }
67
68 /**
69 * Check if given tool is applicable for all nodes in set
70 *
71 * @param tool
72 * @param nodes
73 * @return
74 */
75 public static boolean isToolApplicable(ObjectTool tool, Set<NodeInfo> nodes)
76 {
77 for(NodeInfo n : nodes)
78 if (!tool.isApplicableForNode(n.object))
79 return false;
80 return true;
81 }
82
83 /**
84 * Execute object tool on node set
85 * @param tool Object tool
86 */
87 public static void execute(final Set<NodeInfo> nodes, final ObjectTool tool)
88 {
89 if ((tool.getFlags() & ObjectTool.ASK_CONFIRMATION) != 0)
90 {
91 String message = tool.getConfirmationText();
92 if (nodes.size() == 1)
93 {
94 NodeInfo node = nodes.iterator().next();
95 message = message.replace("%OBJECT_IP_ADDR%", node.object.getPrimaryIP().getHostAddress()); //$NON-NLS-1$
96 message = message.replace("%OBJECT_NAME%", node.object.getObjectName()); //$NON-NLS-1$
97 message = message.replace("%OBJECT_ID%", Long.toString(node.object.getObjectId())); //$NON-NLS-1$
98 message = message.replace("%USERNAME%", ConsoleSharedData.getSession().getUserName()); //$NON-NLS-1$
99 }
100 else
101 {
102 message = message.replace("%OBJECT_IP_ADDR%", Messages.get().ObjectToolsDynamicMenu_MultipleNodes); //$NON-NLS-1$
103 message = message.replace("%OBJECT_NAME%", Messages.get().ObjectToolsDynamicMenu_MultipleNodes); //$NON-NLS-1$
104 message = message.replace("%OBJECT_ID%", Messages.get().ObjectToolsDynamicMenu_MultipleNodes); //$NON-NLS-1$
105 message = message.replace("%USERNAME%", ConsoleSharedData.getSession().getUserName()); //$NON-NLS-1$
106 }
107 if (!MessageDialogHelper.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
108 Messages.get().ObjectToolsDynamicMenu_ConfirmExec, message))
109 return;
110 }
111
112 for(NodeInfo n : nodes)
113 executeOnNode(n, tool);
114 }
115
116 /**
117 * Execute object tool on single node
118 *
119 * @param node
120 * @param tool
121 */
122 private static void executeOnNode(final NodeInfo node, final ObjectTool tool)
123 {
124 switch(tool.getType())
125 {
126 case ObjectTool.TYPE_INTERNAL:
127 executeInternalTool(node, tool);
128 break;
129 case ObjectTool.TYPE_LOCAL_COMMAND:
130 executeLocalCommand(node, tool);
131 break;
132 case ObjectTool.TYPE_SERVER_COMMAND:
133 executeServerCommand(node, tool);
134 break;
135 case ObjectTool.TYPE_ACTION:
136 executeAgentAction(node, tool);
137 break;
138 case ObjectTool.TYPE_TABLE_AGENT:
139 case ObjectTool.TYPE_TABLE_SNMP:
140 executeTableTool(node, tool);
141 break;
142 case ObjectTool.TYPE_URL:
143 openURL(node, tool);
144 break;
145 case ObjectTool.TYPE_FILE_DOWNLOAD:
146 executeFileDownload(node, tool);
147 break;
148 }
149 }
150
151 /**
152 * Execute table tool
153 *
154 * @param node
155 * @param tool
156 */
157 private static void executeTableTool(final NodeInfo node, final ObjectTool tool)
158 {
159 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
160 try
161 {
162 final IWorkbenchPage page = window.getActivePage();
163 final TableToolResults view = (TableToolResults)page.showView(TableToolResults.ID,
164 Long.toString(tool.getId()) + "&" + Long.toString(node.object.getObjectId()), IWorkbenchPage.VIEW_ACTIVATE); //$NON-NLS-1$
165 view.refreshTable();
166 }
167 catch(PartInitException e)
168 {
169 MessageDialogHelper.openError(window.getShell(), Messages.get().ObjectToolsDynamicMenu_Error, String.format(Messages.get().ObjectToolsDynamicMenu_ErrorOpeningView, e.getLocalizedMessage()));
170 }
171 }
172
173 /**
174 * @param node
175 * @param tool
176 */
177 private static void executeAgentAction(final NodeInfo node, final ObjectTool tool)
178 {
179 final NXCSession session = (NXCSession)ConsoleSharedData.getSession();
180 final String action = substituteMacros(tool.getData(), node);
181
182 if ((tool.getFlags() & ObjectTool.GENERATES_OUTPUT) == 0)
183 {
184 new ConsoleJob(String.format(Messages.get().ObjectToolsDynamicMenu_ExecuteOnNode, node.object.getObjectName()), null, Activator.PLUGIN_ID, null) {
185 @Override
186 protected String getErrorMessage()
187 {
188 return String.format(Messages.get().ObjectToolsDynamicMenu_CannotExecuteOnNode, node.object.getObjectName());
189 }
190
191 @Override
192 protected void runInternal(IProgressMonitor monitor) throws Exception
193 {
194 session.executeAction(node.object.getObjectId(), action);
195 runInUIThread(new Runnable() {
196 @Override
197 public void run()
198 {
199 MessageDialogHelper.openInformation(null, Messages.get().ObjectToolsDynamicMenu_ToolExecution, String.format(Messages.get().ObjectToolsDynamicMenu_ExecSuccess, action, node.object.getObjectName()));
200 }
201 });
202 }
203 }.start();
204 }
205 else
206 {
207 final String secondaryId = Long.toString(node.object.getObjectId()) + "&" + Long.toString(tool.getId()); //$NON-NLS-1$
208 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
209 try
210 {
211 AgentActionResults view = (AgentActionResults)window.getActivePage().showView(AgentActionResults.ID, secondaryId, IWorkbenchPage.VIEW_ACTIVATE);
212 view.executeAction(action);
213 }
214 catch(Exception e)
215 {
216 MessageDialogHelper.openError(window.getShell(), Messages.get().ObjectToolsDynamicMenu_Error, String.format(Messages.get().ObjectToolsDynamicMenu_ErrorOpeningView, e.getLocalizedMessage()));
217 }
218 }
219 }
220
221 /**
222 * Execute server command
223 *
224 * @param node
225 * @param tool
226 */
227 private static void executeServerCommand(final NodeInfo node, final ObjectTool tool)
228 {
229 final NXCSession session = (NXCSession)ConsoleSharedData.getSession();
230 new ConsoleJob(Messages.get().ObjectToolsDynamicMenu_ExecuteServerCmd, null, Activator.PLUGIN_ID, null) {
231 @Override
232 protected void runInternal(IProgressMonitor monitor) throws Exception
233 {
234 session.executeServerCommand(node.object.getObjectId(), tool.getData());
235 runInUIThread(new Runnable() {
236 @Override
237 public void run()
238 {
239 MessageDialogHelper.openInformation(null, Messages.get().ObjectToolsDynamicMenu_Information, Messages.get().ObjectToolsDynamicMenu_ServerCommandExecuted);
240 }
241 });
242 }
243
244 @Override
245 protected String getErrorMessage()
246 {
247 return Messages.get().ObjectToolsDynamicMenu_ServerCmdExecError;
248 }
249 }.start();
250 }
251
252 /**
253 * Execute local command
254 *
255 * @param node
256 * @param tool
257 */
258 private static void executeLocalCommand(final NodeInfo node, final ObjectTool tool)
259 {
260 String command = substituteMacros(tool.getData(), node);
261
262 if ((tool.getFlags() & ObjectTool.GENERATES_OUTPUT) == 0)
263 {
264 final String os = Platform.getOS();
265
266 try
267 {
268 if (os.equals(Platform.OS_WIN32))
269 {
270 command = "CMD.EXE /C START \"NetXMS\" " + command; //$NON-NLS-1$
271 Runtime.getRuntime().exec(command);
272 }
273 else
274 {
275 Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command }); //$NON-NLS-1$ //$NON-NLS-2$
276 }
277 }
278 catch(IOException e)
279 {
280 // TODO Auto-generated catch block
281 e.printStackTrace();
282 }
283 }
284 else
285 {
286 final String secondaryId = Long.toString(node.object.getObjectId()) + "&" + Long.toString(tool.getId()); //$NON-NLS-1$
287 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
288 try
289 {
290 LocalCommandResults view = (LocalCommandResults)window.getActivePage().showView(LocalCommandResults.ID, secondaryId, IWorkbenchPage.VIEW_ACTIVATE);
291 view.runCommand(command);
292 }
293 catch(Exception e)
294 {
295 MessageDialogHelper.openError(window.getShell(), Messages.get().ObjectToolsDynamicMenu_Error, String.format(Messages.get().ObjectToolsDynamicMenu_ErrorOpeningView, e.getLocalizedMessage()));
296 }
297 }
298 }
299
300 /**
301 * @param node
302 * @param tool
303 */
304 private static void executeFileDownload(final NodeInfo node, final ObjectTool tool)
305 {
306 final NXCSession session = (NXCSession)ConsoleSharedData.getSession();
307 String[] parameters = tool.getData().split("\u007F"); //$NON-NLS-1$
308
309 final String fileName = parameters[0];
310 final int maxFileSize = Integer.parseInt(parameters[1]);
311 final boolean follow = parameters[2].equals("true") ? true : false; //$NON-NLS-1$
312
313 ConsoleJob job = new ConsoleJob(Messages.get().ObjectToolsDynamicMenu_DownloadFromAgent, null, Activator.PLUGIN_ID, null) {
314 @Override
315 protected String getErrorMessage()
316 {
317 return String.format(Messages.get().ObjectToolsDynamicMenu_DownloadError, fileName, node.object.getObjectName());
318 }
319
320 @Override
321 protected void runInternal(IProgressMonitor monitor) throws Exception
322 {
323 final AgentFile file = session.downloadFileFromAgent(node.object.getObjectId(), fileName, maxFileSize, follow);
324 runInUIThread(new Runnable() {
325 @Override
326 public void run()
327 {
328 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
329 try
330 {
331 String secondaryId = Long.toString(node.object.getObjectId()) + "&" + URLEncoder.encode(fileName, "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
332 FileViewer view = (FileViewer)window.getActivePage().showView(FileViewer.ID, secondaryId,
333 IWorkbenchPage.VIEW_ACTIVATE);
334 view.showFile(file.getFile(), follow, file.getId(), maxFileSize);
335 }
336 catch(Exception e)
337 {
338 MessageDialogHelper.openError(window.getShell(), Messages.get().ObjectToolsDynamicMenu_Error, String.format(Messages.get().ObjectToolsDynamicMenu_ErrorOpeningView, e.getLocalizedMessage()));
339 }
340 }
341 });
342 }
343 };
344 job.start();
345 }
346
347 /**
348 * @param node
349 * @param tool
350 */
351 private static void executeInternalTool(final NodeInfo node, final ObjectTool tool)
352 {
353 ObjectToolHandler handler = ObjectToolsCache.findHandler(tool.getData());
354 if (handler != null)
355 {
356 handler.execute(node.object, tool);
357 }
358 else
359 {
360 MessageDialogHelper.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages.get().ObjectToolsDynamicMenu_Error, Messages.get().ObjectToolsDynamicMenu_HandlerNotDefined);
361 }
362 }
363
364 /**
365 * @param node
366 * @param tool
367 */
368 private static void openURL(final NodeInfo node, final ObjectTool tool)
369 {
370 final String url = substituteMacros(tool.getData(), node);
371
372 final String sid = Long.toString(node.object.getObjectId()) + "&" + Long.toString(tool.getId()); //$NON-NLS-1$
373 final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
374 try
375 {
376 BrowserView view = (BrowserView)window.getActivePage().showView(BrowserView.ID, sid, IWorkbenchPage.VIEW_ACTIVATE);
377 view.openUrl(url);
378 }
379 catch(PartInitException e)
380 {
381 MessageDialogHelper.openError(window.getShell(), Messages.get().ObjectToolsDynamicMenu_Error, Messages.get().ObjectToolsDynamicMenu_CannotOpenWebBrowser + e.getLocalizedMessage());
382 }
383 }
384
385 /**
386 * Substitute macros in string
387 *
388 * @param s
389 * @param node
390 * @return
391 */
392 private static String substituteMacros(String s, NodeInfo node)
393 {
394 StringBuilder sb = new StringBuilder();
395
396 char[] src = s.toCharArray();
397 for(int i = 0; i < s.length(); i++)
398 {
399 if (src[i] == '%')
400 {
401 StringBuilder p = new StringBuilder();
402 for(i++; src[i] != '%' && i < s.length(); i++)
403 p.append(src[i]);
404 if (p.length() == 0) // %%
405 {
406 sb.append('%');
407 }
408 else
409 {
410 String name = p.toString();
411 if (name.equals("OBJECT_IP_ADDR")) //$NON-NLS-1$
412 {
413 sb.append(node.object.getPrimaryIP().getHostAddress());
414 }
415 else if (name.equals("OBJECT_NAME")) //$NON-NLS-1$
416 {
417 sb.append(node.object.getObjectName());
418 }
419 else if (name.equals("OBJECT_ID")) //$NON-NLS-1$
420 {
421 sb.append(node.object.getObjectId());
422 }
423 else if (name.equals("ALARM_ID")) //$NON-NLS-1$
424 {
425 if (node.alarm != null)
426 sb.append(node.alarm.getId());
427 }
428 else if (name.equals("ALARM_MESSAGE")) //$NON-NLS-1$
429 {
430 if (node.alarm != null)
431 sb.append(node.alarm.getMessage());
432 }
433 else if (name.equals("ALARM_SEVERITY")) //$NON-NLS-1$
434 {
435 if (node.alarm != null)
436 sb.append(node.alarm.getCurrentSeverity());
437 }
438 else if (name.equals("ALARM_SEVERITY_TEXT")) //$NON-NLS-1$
439 {
440 if (node.alarm != null)
441 sb.append(StatusDisplayInfo.getStatusText(node.alarm.getCurrentSeverity()));
442 }
443 else if (name.equals("ALARM_STATE")) //$NON-NLS-1$
444 {
445 if (node.alarm != null)
446 sb.append(node.alarm.getState());
447 }
448 else if (name.equals("USERNAME")) //$NON-NLS-1$
449 {
450 sb.append(ConsoleSharedData.getSession().getUserName());
451 }
452 else
453 {
454 String custAttr = node.object.getCustomAttributes().get(name);
455 if (custAttr != null)
456 sb.append(custAttr);
457 }
458 }
459 }
460 else
461 {
462 sb.append(src[i]);
463 }
464 }
465
466 return sb.toString();
467 }
468 }