Listeners
There are several approaches to handle process engine events like task creation, activity completion, and so on.
Spring Events for BPM
BPM add-on additionally introduces a set of Spring application events. The following events are published:
-
UserTaskAssignedEvent
-
UserTaskCreatedEvent
-
UserTaskCompletedEvent
-
ActivityStartedEvent
-
ActivityCompletedEvent
-
ProcessStartedEvent
-
ProcessCompletedEvent
Here is an example of an event listener that sends an email notification each time a user task is assigned to a user:
@Component("smpl_TaskAssignedNotificationSender")
public class TaskAssignedNotificationSender {
@Autowired
private Emailer emailer;
@Autowired
private DataManager dataManager;
@EventListener (1)
public void onTaskAssigned(UserTaskAssignedEvent event) { (2)
User user = dataManager.load(User.class) (3)
.query("select u from smpl_User u where u.username = :username")
.parameter("username", event.getUsername())
.one();
Task task = event.getTask(); (4)
String emailTitle = "New process task " + task.getName();
String emailBody = "Hi " + user.getFirstName() + "\n" +
"The task " + task.getName() + " has been assigned.";
EmailInfo emailInfo = EmailInfoBuilder.create()
.setAddresses(user.getEmail())
.setSubject(emailTitle)
.setFrom(null)
.setBody(emailBody)
.build();
emailer.sendEmailAsync(emailInfo); (5)
}
}
1 | Declares that the method is an event listener. |
2 | The listener is fired each time the UserTaskAssignedEvent is published. |
3 | Gets User entity to receive a user first name and email address.The UserTaskAssignedEvent contains a username of a user who is the task assigned to. |
4 | The UserTaskAssignedEvent contains a Task object which holds information about the user task. |
5 | Creates and sends email. See the Email Sending Guide for details. |
If you need to get a process variable value in the listener, you can do it this way:
@Autowired
private RuntimeService runtimeService;
@EventListener
public void onOtherProcessTaskAssigned(UserTaskAssignedEvent event) {
Order order = (Order) runtimeService.getVariable(event.getTask().getExecutionId(), "order");
// ...
}
By default, a listener is fired when the user task is assigned in any process. If you want to send notifications only for specific process definition, you can check the process definition in the listener method body:
@EventListener
protected void onOtherProcessTaskAssigned(UserTaskAssignedEvent event) {
if ("order-approval".equals(event.getProcessDefinition().getKey())) {
// ...
}
}
or you can define a SpEL (Spring Expression Language) expression that should match in order to handle the event:
@EventListener(condition = "#event.processDefinitionData.key == 'order-approval'")
protected void onOtherProcessTaskAssigned(UserTaskAssignedEvent event) {
// ...
}