Camunda Team Blog

Fluent API for Message Correlation

Written by Daniel Meyer on , under Execution category.
camunda BPM 7.1.0-alpha4 features a new fluent API for message correlation.

BPMN 2.0 defines events and tasks catching messages. The following is a fragment of a process waiting for an order to be cancelled:
Intermediate Message Catch Event
In BPMN 2.0 XML you have to provide a name for the message you want to catch:

<bpmn2:definitions ...>
  ...
  <bpmn2:message id="Message_1" name="orderCancelled"/>
  ...
  <bpmn2:process id="Process_1" isExecutable="false">
    ...
    <bpmn2:intermediateCatchEvent id="IntermediateCatchEvent_2" name="Order &#xA;Cancelled">      
      <bpmn2:messageEventDefinition messageRef="Message_1"/>

    </bpmn2:intermediateCatchEvent>
    
  </bpmn2:process>

New Fluent API

camunda Engine now featues a fluent DSL for correlating this message to the process engine:

  runtimeService.createMessageCorrelation("orderCancelled")
      .processInstanceBusinessKey("someOrderId")
      .setVariable("CANCEL_REASON", "someReason")
      .setVariable("CANCEL_TIMESTAMP", new Date())
      .correlate();

The fluent DSL makes it easy to define a complex correlation set based on different restrictions. The above example correlates the message on the business key. On top of that, correlation based on process variables and process instance id is supported:

  runtimeService.createMessageCorrelation("orderCancelled")
      .processInstanceVariableEquals("orderId", "someOrderId")
      .processInstanceVariableEquals("customerId", "someCustomerId")
      .correlate();

  runtimeService.createMessageCorrelation("orderCancelled")
      .processInstanceId("someProcessInstanceId")
      .correlate();

The API also makes it easy to provide the message payload as a single or multiple variables through setVariable(varName, value).

More Efficient than Query + Trigger

We recommend using the fluent DSL or the RuntimeService.correlateMessage(...) methods introduced in 7.0 over the Query + Trigger pattern. Using the Query + Trigger pattern you first query for an execution having a message event subscription and then trigger that execution:

Not as efficient:

  // Query
  Execution e = runtimeService.createExecutionQuery()
    .processInstanceBusinessKey("someOrderId")
    .messageEventSubscriptionName("orderCancelled")
    .singleResult();

  Map<String, Object> variables = new HashMap<String, Object>();
  variables.put("CANCEL_REASON", "someReason");
  variables.put("CANCEL_TIMESTAMP", new Date());

  // Trigger
  runtimeService.messageEventReceived("orderCancelled", e.getId(), variables);

The Query + Trigger pattern has two disadvantages:
  1. More lines of code :)
  2. Two process engine commands instead of a single one. This makes it less efficient in terms of performance.