loading...

Executing groovy script on a camunda process

liviasilvasantos profile image Lívia Silva Santos ・2 min read

Today I've bumped into a specific problem: I've a web app in Java running a Camunda process. At some point of the process, there's a Condition Expression on Sequence Flow that goes like:

${variable.contains('astring')}

But now I need to compare if the variable started with 'astring'. Since variable is a set collection, I had to find a way to iterate the itens and check the start of the string. Since I couldn't find a way to do it using expression language, I've found out a way to do it using a script in Groovy.

So I've changed the Condition Type at Camunda to 'Script' and Script Format to 'groovy', to indicate that the conditional needed to be evaluated as a groovy script.

Nice. But I've never wrote a single line in Groovy!

To test it first, I've used the page https://groovyconsole.appspot.com/, so I could test all my conditions.

I also had to change my application. At some point on the application, I show the user the next User Task, evaluating the expressions of the process. I was using a Camunda's ExpressionFactory to do it. So I've added a check at the SequenceFlow object to check if the condition was written in groovy and evaluated it, something like:

if ("groovy".equalsIgnoreCase(sf.getConditionExpression().getLanguage())) {
  //create a groovy engine
  ScriptEngineManager factory = new ScriptEngineManager();
  ScriptEngine engine = factory.getEngineByName("groovy");

  //added all the Camunda's variables at the groovy engine to evaluation
  for (Map.Entry<String, Object> v : variables.entrySet()) {
    if (v.getValue() != null) {
      engine.put(v.getKey(), v.getValue());
    }
  }

  try {
    //evaluate the conditional expression 
    next = (Boolean) engine.eval(sf.getConditionExpression().getTextContent());
  } catch (Exception e) {
    next = false;
  }
}  else { // EL evaluations } 

Also I had to add a maven dependency:

  <dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.4.5</version>
  </dependency>

And that's it!

--
Integrating Groovy in a Java application: http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html

Discussion

markdown guide