Executing commands programmatically

Executing commands (e.g. from a SWT listener) is a pretty handy thing. You don’t have to care about, where the handler is registered, you simply execute the command via the ICommandService, the delegation is provided by the framework.


...
ICommandService commandService = (ICommandService)getViewSite().getService(ICommandService.class);
try {
commandService.getCommand("com.foo.the.command").executeWithChecks(new ExecutionEvent());
}
catch (Exception exception) {
logger.error(exception.getMessage(), exception);
}
...

There is just one thing about the snippet above that is bad: The way the ExecutionEvent is created. Using the default constructor results in hard time for a handler, as the HandlerUtil class cannot be used due to the missing context information. A better way is to pass on some parameters to the ExecutionEvent to be created. The most important one is the last parameter, the application context object. It can be obtained via the IEvaluationService.


...
ICommandService commandService = (ICommandService)getViewSite().getService(ICommandService.class);
IEvaluationService evaluationService = (IEvaluationService)getViewSite().getService(IEvaluationService.class);
try {
Command theCommand = commandService.getCommand("com.foo.the.command");
theCommand.executeWithChecks(new ExecutionEvent(theCommand, new HashMap(), control, evaluationService.getCurrentState()));
}
catch (Exception exception) {
logger.error(exception.getMessage(), exception);
}
...

This command invokation can be processed by any handler using the HandlerUtil class.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>