List Tasks waiting on a given MessageBoundaryEvent message name

Is it possible using the Java API to list all tasks for a given ProcessInstanceId / BusinessKey that are waiting on a given MessageBoundaryEvent?

One way I can potentially do it is to

  1. List all tasks via “createTaskQuery()”
  2. Get the ProcessDefinitionID from the Task
  3. Load the Process definition
  4. Get the Boundary Events attached to the Task step
  5. Compare these to the Messages defined in the definition

This all seems very laborious though and given that “MessageCorrelationBuilder” must do something similar to work out which tasks to complete when the message is signalled I’m wondering if I’m missing something simple?

Thanks Steve

To answer my own question, here’s the code I used to achieve this.

TaskInstanceDetails & TaskInstanceDetailList are my own DTOs…

public TaskInstanceDetailList listTasksWaitingOnMessage(String businessKey, String message, PageRequest pageRequest)
{
    List<TaskInstanceDetails> taskInstanceDetails = new ArrayList<>();

    List<Task> tasks = taskService.createTaskQuery()
                                  .processInstanceBusinessKey(businessKey)
                                  .initializeFormKeys()
                                  .active()
                                  .listPage(pageRequest.getPageNumber() * pageRequest.getPageSize(), pageRequest.getPageSize());

    Set<String> processInstanceIds = new HashSet<>();
    Map<String, String> executionIdsToTaskIds = new HashMap<>();

    tasks.forEach(t -> {
        processInstanceIds.add(t.getProcessInstanceId());
        executionIdsToTaskIds.put(t.getExecutionId(), t.getId());
    });

    Set<String> executionIds = executionIdsToTaskIds.keySet();

    processInstanceIds.forEach(pid -> {

        List<EventSubscription> eventSubscriptions = runtimeService.createEventSubscriptionQuery()
                                                                   .processInstanceId(pid)
                                                                   .eventName(message)
                                                                   .list();

        eventSubscriptions.forEach(e -> {

            if (executionIds.contains(e.getExecutionId()))
            {
                String taskId = executionIdsToTaskIds.get(e.getExecutionId());

                log.debug("FOUND TASK ID : {}", taskId);

                Optional<Task> task = tasks.stream().filter(t -> t.getId().equals(taskId)).findFirst();
                task.ifPresent(value -> taskInstanceDetails.add(getTaskInstanceDetails(value)));
            }

        });
    });

    TaskInstanceDetailList taskInstanceDetailList = new TaskInstanceDetailList();
    taskInstanceDetailList.setPagingInfo(new PagingInfo(pageRequest, taskInstanceDetails.size()));
    taskInstanceDetailList.setTaskInstances(taskInstanceDetails);

    return taskInstanceDetailList;
}