SwingCommand part 7 – Composite Commands

There are occasions when it is useful to group commands together and execute several in combination. SwingCommand provides a CompositeCommandTask which allows you to group commands together in a single task which executes them sequentially.

TaskListeners on the CompositeCommandTask receive progress events as each child command is processed. The example below creates a String progress value to describe the current child command being processed.

Cancelling the composite task will cause the currently processing child command to be cancelled (if it supports cancellation), and will cause the composite task to abort processing for any remaining child command tasks. The reverse is also true – if the currently processing child command’s task is cancelled, this will cause the composite task to be cancelled and abort early.

If any of the child commands fail, the composite task will also fail with a CompositeCommandTaskException, which has the child task’s exception as the cause.

Here is a simple example of a composite task:

  SwingCommand loadThreeUsersMessages = new SwingCommand() {
 
      protected Task createTask() {
 
          CompositeCommandTask compositeTask = new CompositeCommandTask() {
 
              //let's send progress as a String update to any TaskListeners
              protected String getProgress(int currentCommandId, int totalCommands, Task currentChildCommand) {
                  return "Now running number " + currentCommandId + " out of " + totalCommands + " commands";
              }
          };
 
          compositeTask.addCommand(new LoadMessagesCommand("User 1"));
          compositeTask.addCommand(new LoadMessagesCommand("User 2"));
          compositeTask.addCommand(new LoadMessagesCommand("User 3"));
          return compositeTask;
      }
  };
 
  loadThreeUsersMessages.execute();

The composite task implements the getProgress() method to generate the String used in the progress event.


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply