1
votes

Consider a process instance variable which currently has some value. I would like to update its value, for instance increment it by one, using the REST API of Activiti / Camunda. How would you do this?

The problem is that the REST API has services for setting variable values and to get them. But incorporating such API could easily lead to race condition.

Also consider that my example is regarding integers while a variable could be a complex JSON object or array!

1

1 Answers

4
votes

This answer is for Camunda 7.3.0:

There is no out-of-the-box solution. You can do the following:

  1. Extend the REST API with a custom resource that implements an endpoint for variable modification. Since the Camunda REST API uses JAX-RS, it is possible to add the Camunda REST resources to a custom JAX-RS application. See [1] for details.
  2. In the custom resource endpoint, implement the read-modify-write cycle in one transaction using a custom command:

    protected void readModifyWriteVariable(CommandExecutor commandExecutor, final String processInstanceId,
          final String variableName, final int valueToAdd) {
    
      try {
        commandExecutor.execute(new Command<Void>() {
          public Void execute(CommandContext commandContext) {
            Integer myCounter = (Integer) runtimeService().getVariable(processInstanceId, variableName);
    
            // do something with variable
            myCounter += valueToAdd;
    
            // the update provokes an OptimisticLockingException when the command ends, if the variable was updated meanwhile
            runtimeService().setVariable(processInstanceId, variableName, myCounter);
    
            return null;
          }
        });
      } catch (OptimisticLockingException e) {
        // try again
        readModifyWriteVariable(commandExecutor, processInstanceId, variableName, valueToAdd);
      }
    }
    

See [2] for a detailed discussion.

[1] http://docs.camunda.org/manual/7.3/api-references/rest/#overview-embedding-the-api
[2] https://groups.google.com/d/msg/camunda-bpm-users/3STL8s9O2aI/Dcx6KtKNBgAJ