added svcapi ui and camunda code
[it/otf.git] / otf-camunda / src / main / java / org / oran / otf / camunda / workflow / handler / ExternalTaskIncidentHandler.java
1 /*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ##############################################################################*/\r
15 \r
16 \r
17 package org.oran.otf.camunda.workflow.handler;\r
18 \r
19 import org.oran.otf.camunda.configuration.OtfCamundaConfiguration;\r
20 import org.oran.otf.camunda.exception.TestExecutionException;\r
21 import org.oran.otf.camunda.model.ExecutionConstants.TestResult;\r
22 import org.oran.otf.camunda.workflow.utility.WorkflowTask;\r
23 import org.oran.otf.common.model.TestExecution;\r
24 import org.oran.otf.common.repository.TestExecutionRepository;\r
25 import org.oran.otf.common.utility.Utility;\r
26 import org.oran.otf.service.impl.DeleteProcessInstanceServiceImpl;\r
27 import com.mongodb.client.result.UpdateResult;\r
28 \r
29 import java.util.Date;\r
30 import java.util.List;\r
31 \r
32 import org.camunda.bpm.BpmPlatform;\r
33 import org.camunda.bpm.engine.RuntimeService;\r
34 import org.camunda.bpm.engine.impl.incident.IncidentContext;\r
35 import org.camunda.bpm.engine.impl.incident.IncidentHandler;\r
36 import org.camunda.bpm.engine.runtime.Execution;\r
37 import org.camunda.bpm.engine.runtime.Incident;\r
38 import org.slf4j.Logger;\r
39 import org.slf4j.LoggerFactory;\r
40 import org.springframework.beans.factory.annotation.Autowired;\r
41 import org.springframework.boot.context.event.ApplicationReadyEvent;\r
42 import org.springframework.context.event.EventListener;\r
43 import org.springframework.data.mongodb.core.MongoTemplate;\r
44 import org.springframework.data.mongodb.core.query.Criteria;\r
45 import org.springframework.data.mongodb.core.query.Query;\r
46 import org.springframework.data.mongodb.core.query.Update;\r
47 import org.springframework.stereotype.Service;\r
48 \r
49 @Service\r
50 public class ExternalTaskIncidentHandler implements IncidentHandler {\r
51 \r
52   private static final Logger logger = LoggerFactory.getLogger(ExternalTaskIncidentHandler.class);\r
53   private static final String logPrefix = Utility.getLoggerPrefix();\r
54 \r
55   @Autowired\r
56   private TestExecutionRepository testExecutionRepository;\r
57   @Autowired\r
58   private MongoTemplate mongoOperation;\r
59   @Autowired\r
60   private DeleteProcessInstanceServiceImpl deleteProcessInstanceService;\r
61 \r
62   @Override\r
63   public String getIncidentHandlerType() {\r
64     return Incident.EXTERNAL_TASK_HANDLER_TYPE;\r
65   }\r
66 \r
67   @Override\r
68   public Incident handleIncident(IncidentContext context, String message) {\r
69     //need to get process instance id from executionid (parent process)\r
70     String executionId = context.getExecutionId();\r
71     RuntimeService runtimeService = BpmPlatform.getProcessEngineService().getProcessEngine(OtfCamundaConfiguration.processEngineName).getRuntimeService();\r
72 \r
73     Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();\r
74     String processInstanceId = execution.getProcessInstanceId();\r
75     TestExecution testExecution =\r
76         testExecutionRepository.findFirstByProcessInstanceId(processInstanceId).orElse(null);\r
77 \r
78     if (testExecution == null) {\r
79       String error =\r
80           String.format(\r
81               "%sUnable to find testExecution with processInstanceId %s. This process instance will forcefully be terminated to avoid a rogue process.",\r
82               logPrefix, processInstanceId);\r
83       logger.error(error);\r
84       deleteProcessInstanceService.deleteProcessInstanceInternal(processInstanceId, error);\r
85     } else {\r
86       if(!testExecution.getTestResult().equals(TestResult.TERMINATED)){\r
87         updateTestResult(testExecution, TestResult.WORKFLOW_ERROR, message);\r
88       }\r
89       deleteProcessInstanceService.deleteProcessInstanceInternal(processInstanceId, message);\r
90 \r
91       List<WorkflowTask> workflowTasks =\r
92           WorkflowTask.workflowTasksByExecutionId.getOrDefault(processInstanceId, null);\r
93 \r
94       if (workflowTasks != null) {\r
95         logger.debug("Forcefully terminating workflow tasks for processInstanceId: " + processInstanceId);\r
96         for (WorkflowTask workflowTask : workflowTasks) {\r
97           workflowTask.shutdown(true);\r
98         }\r
99       }\r
100     }\r
101 \r
102     return null;\r
103   }\r
104 \r
105   private void updateTestResult(TestExecution testExecution, String testResult, String testResultMessage) {\r
106     // Set the test result\r
107     testExecution.setTestResult(testResult);\r
108     testExecution.setTestResultMessage(testResultMessage);\r
109     Query query = new Query();\r
110     query.addCriteria(Criteria.where("_id").is(testExecution.get_id()));\r
111     // Also add businessKey as a criteria because the object won't be found if the business key\r
112     // was somehow modified in the workflow.\r
113     query.addCriteria(Criteria.where("businessKey").is(testExecution.getBusinessKey()));\r
114     Update update = new Update();\r
115     update.set("testResult", testExecution.getTestResult());\r
116     update.set("testResultMessage", testExecution.getTestResultMessage());\r
117     update.set("endTime", new Date(System.currentTimeMillis()));\r
118     UpdateResult result = mongoOperation.updateFirst(query, update, TestExecution.class);\r
119     // Check the status of the findAndUpdate database, and appropriately handle the errors.\r
120     if (result.getMatchedCount() == 0) {\r
121       throw new TestExecutionException(\r
122           String.format(\r
123               "Unable to log the test result because a testExecution associated with _id, %s and businessKey %s, was not found.",\r
124               testExecution.get_id(), testExecution.getBusinessKey()));\r
125     } else if (result.getModifiedCount() == 0) {\r
126       throw new TestExecutionException("Unable to persist the testExecution to the database.");\r
127     }\r
128   }\r
129 \r
130   @Override\r
131   public void resolveIncident(IncidentContext context) {\r
132     //    logger.info("incident resolved");\r
133   }\r
134 \r
135   @Override\r
136   public void deleteIncident(IncidentContext context) {\r
137     //    logger.info("incident deleted");\r
138   }\r
139 }\r