How to loop through Element Types of Model Instance and Add Extension Elements

consider the following:

    def sequenceFlows = model.getModelElementsByType(org.camunda.bpm.model.bpmn.instance.SequenceFlow.class).collect {it.getId()}
    println '\nSequence Flows:'
    println sequenceFlows
    sequenceFlows.each {
      def sequenceFlow = model.getModelElementById(it)

I am using the following as reference:

The issue is that it seems that you cant update the model a second time? Only the last update to the model in the loop is kept. Previous writes are overwritten with the original model.

Missing something?

Well that was very painful…

so the issue is the instance of the ExecutionListener had to be created everytime you wanted to insert. I was only creating it once; as i was assuming that it was a generic instance that could be applied… that was the wrong assumption…

so solution snipper of code is

  def addExecutionListener(model, elementId, scriptResource, scriptFormat){
    // @TODO NOTE: The estLis had to be new for every instance
    CamundaExecutionListener extLis = model.newInstance(CamundaExecutionListener.class);
    CamundaScript camScript = model.newInstance(CamundaScript.class);

    def newModel = model.getModelElementById(elementId).builder().addExtensionElement(extLis).done()
    return newModel

  def setupSequenceFlowListeners(model, scriptResource, scriptFormat){

    def sequenceFlows = model.getModelElementsByType(org.camunda.bpm.model.bpmn.instance.SequenceFlow.class).collect {it.getId()}

    def newModel = model
    sequenceFlows.each {
      newModel = addExecutionListener(newModel, it, scriptResource, scriptFormat)
    return newModel

def preppedModel = setupSequenceFlowListeners(myBpmnModelInstance, 'deployment://flownode.js', 'javascript')

Note: this was mainly painful because it seems the Model API does not throw a error when trying to add the same Extension instance into a Model more than once.