Replaced all tabs with spaces in java and pom.xml
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / java / org / onap / so / bpmn / core / plugins / WorkflowExceptionPlugin.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.core.plugins;
24
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.concurrent.atomic.AtomicInteger;
28 import org.camunda.bpm.engine.delegate.BpmnError;
29 import org.camunda.bpm.engine.delegate.DelegateExecution;
30 import org.camunda.bpm.engine.delegate.ExecutionListener;
31 import org.camunda.bpm.engine.delegate.JavaDelegate;
32 import org.camunda.bpm.engine.impl.bpmn.behavior.ClassDelegateActivityBehavior;
33 import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener;
34 import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener;
35 import org.camunda.bpm.engine.impl.bpmn.parser.FieldDeclaration;
36 import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin;
37 import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
38 import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
39 import org.camunda.bpm.engine.impl.pvm.PvmTransition;
40 import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
41 import org.camunda.bpm.engine.impl.pvm.process.TransitionImpl;
42 import org.camunda.bpm.engine.impl.util.xml.Element;
43 import org.onap.so.bpmn.core.WorkflowException;
44 import org.springframework.stereotype.Component;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * This plugin does the following:
50  * <ol>
51  * <li>Adds logic at the start of every Call Activity to remove any existing WorkflowException object from the execution
52  * (saving a copy of it in a different variable).</li>
53  * <li>Adds logic at the end of every Call Activity to generate a MSOWorkflowException event if there is a
54  * WorkflowException object in the execution.</li>
55  * </ol>
56  */
57 @Component
58 public class WorkflowExceptionPlugin extends AbstractProcessEnginePlugin {
59     private static final Logger logger = LoggerFactory.getLogger(WorkflowExceptionPlugin.class);
60
61     @Override
62     public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
63         List<BpmnParseListener> preParseListeners = processEngineConfiguration.getCustomPreBPMNParseListeners();
64
65         if (preParseListeners == null) {
66             preParseListeners = new ArrayList<>();
67             processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners);
68         }
69
70         preParseListeners.add(new WorkflowExceptionParseListener());
71     }
72
73     public static class WorkflowExceptionParseListener extends AbstractBpmnParseListener {
74         @Override
75         public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {
76             AtomicInteger triggerTaskIndex = new AtomicInteger(1);
77             List<ActivityImpl> activities = new ArrayList<>(processDefinition.getActivities());
78             recurse(activities, triggerTaskIndex);
79         }
80
81         /**
82          * Helper method that recurses (into subprocesses) over all the listed activities.
83          * 
84          * @param activities a list of workflow activities
85          * @param triggerTaskIndex the index of the next trigger task (mutable)
86          */
87         private void recurse(List<ActivityImpl> activities, AtomicInteger triggerTaskIndex) {
88             for (ActivityImpl activity : activities) {
89                 String type = (String) activity.getProperty("type");
90
91                 if ("callActivity".equals(type)) {
92                     // Add a WorkflowExceptionResetListener to clear the WorkflowException
93                     // variable when each Call Activity starts.
94
95                     activity.addListener(ExecutionListener.EVENTNAME_START, new WorkflowExceptionResetListener());
96
97                     // Add a WorkflowExceptionTriggerTask after the call activity.
98                     // It must be a task because a listener cannot be used to generate
99                     // an event. Throwing BpmnError from an execution listener will
100                     // cause the process to die.
101
102                     List<PvmTransition> outTransitions = new ArrayList<>(activity.getOutgoingTransitions());
103
104                     for (PvmTransition transition : outTransitions) {
105                         String triggerTaskId = "WorkflowExceptionTriggerTask_" + triggerTaskIndex;
106
107                         ActivityImpl triggerTask = activity.getFlowScope().createActivity(triggerTaskId);
108
109                         ClassDelegateActivityBehavior behavior = new ClassDelegateActivityBehavior(
110                                 WorkflowExceptionTriggerTask.class.getName(), new ArrayList<>(0));
111
112                         triggerTask.setActivityBehavior(behavior);
113                         triggerTask.setName("Workflow Exception Trigger Task " + triggerTaskIndex);
114                         triggerTaskIndex.getAndIncrement();
115
116                         TransitionImpl transitionImpl = (TransitionImpl) transition;
117                         TransitionImpl triggerTaskOutTransition = triggerTask.createOutgoingTransition();
118                         triggerTaskOutTransition.setDestination((ActivityImpl) transitionImpl.getDestination());
119                         transitionImpl.setDestination(triggerTask);
120                     }
121                 } else if ("subProcess".equals(type)) {
122                     recurse(new ArrayList<>(activity.getActivities()), triggerTaskIndex);
123                 }
124             }
125         }
126     }
127
128     /**
129      * If there is a WorkflowException object in the execution, this method removes it (saving a copy of it in a
130      * different variable).
131      */
132     public static class WorkflowExceptionResetListener implements ExecutionListener {
133         public void notify(DelegateExecution execution) throws Exception {
134             Object workflowException = execution.getVariable("WorkflowException");
135
136             if (workflowException instanceof WorkflowException) {
137                 int index = 1;
138                 String saveName = "SavedWorkflowException" + index;
139                 while (execution.getVariable(saveName) != null) {
140                     saveName = "SavedWorkflowException" + (++index);
141                 }
142
143                 logger.debug("WorkflowExceptionResetTask is moving WorkflowException to " + saveName);
144
145                 execution.setVariable(saveName, workflowException);
146                 execution.setVariable("WorkflowException", null);
147             }
148         }
149     }
150
151     /**
152      * Generates an MSOWorkflowException event if there is a WorkflowException object in the execution.
153      */
154     public static class WorkflowExceptionTriggerTask implements JavaDelegate {
155         public void execute(DelegateExecution execution) throws Exception {
156             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
157                 logger.debug("WorkflowExceptionTriggerTask is generating a MSOWorkflowException event");
158                 throw new BpmnError("MSOWorkflowException");
159             }
160         }
161     }
162 }