da24ba14fd20739d96f921d350bb623697ab71dd
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / java / org / onap / so / bpmn / common / workflow / service / WorkflowProcessor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.common.workflow.service;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Objects;
26 import java.util.UUID;
27
28 import org.camunda.bpm.engine.RuntimeService;
29 import org.camunda.bpm.engine.runtime.ProcessInstance;
30 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
31 import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
32 import org.onap.so.logger.MsoLogger;
33 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowProcessorException;
34 import org.slf4j.MDC;
35 import org.springframework.scheduling.annotation.Async;
36 import org.springframework.stereotype.Service;
37
38 @Service
39 public class WorkflowProcessor extends ProcessEngineAwareService {
40         
41         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, WorkflowProcessor.class);
42         
43         protected static final String logMarker = "[WRKFLOW-RESOURCE]";
44         protected static final long DEFAULT_WAIT_TIME = 30000;  //default wait time
45         
46         @Async
47         public void startProcess( String processKey, VariableMapImpl variableMap) throws InterruptedException
48         {
49                 MDC.getCopyOfContextMap();
50                 long startTime = System.currentTimeMillis();
51                 Map<String, Object> inputVariables = null;
52                 String processInstanceId = null;
53                 try {
54                         inputVariables = getInputVariables(variableMap);
55                         setLogContext(processKey, inputVariables);
56
57                         // This variable indicates that the flow was invoked asynchronously
58                         inputVariables.put("isAsyncProcess", "true");
59                         
60                         
61                         setLogContext(processKey, inputVariables);
62
63                         // Note: this creates a random businessKey if it wasn't specified.
64                         String businessKey = getBusinessKey(inputVariables);
65
66                         msoLogger.debug("***Received MSO startProcessInstanceByKey with processKey: " + processKey
67                                         + " and variables: " + inputVariables);
68
69                         RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
70                         ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey,
71                                         inputVariables);
72                         processInstanceId = processInstance.getId();
73
74                         msoLogger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " "
75                                         + (processInstance.isEnded() ? "ENDED" : "RUNNING"));
76                 } catch (Exception e) {
77
78                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
79                                         logMarker + "Error in starting the process: " + e.getMessage());
80
81                         WorkflowResponse workflowResponse = new WorkflowResponse();
82                         workflowResponse.setResponse("Error occurred while executing the process: " + e);
83                         workflowResponse.setProcessInstanceID(processInstanceId);
84                         workflowResponse.setMessageCode(500);
85                         workflowResponse.setMessage("Fail");
86                         throw new WorkflowProcessorException(workflowResponse);
87                 }
88         }
89         
90         protected static void setLogContext(String processKey,
91                         Map<String, Object> inputVariables) {
92                 MsoLogger.setServiceName("MSO." + processKey);
93                 if (inputVariables != null) {
94                         MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"mso-service-instance-id"));
95                 }
96         }
97         
98         protected static String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {
99                 if (inputVariables == null) {
100                         return "";
101                 }
102
103                 return Objects.toString(inputVariables.get(key), "N/A");
104         }
105         
106         // Note: the business key is used to identify the process in unit tests
107         protected static String getBusinessKey(Map<String, Object> inputVariables) {
108         return getOrCreate(inputVariables, "mso-business-key");
109         }
110
111         protected static String getRequestId(Map<String, Object> inputVariables) {
112         return getOrCreate(inputVariables, "mso-request-id");
113         }
114         
115         protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
116                 Map<String, Object> inputVariables = new HashMap<>();
117                 @SuppressWarnings("unchecked")
118                 Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
119                 for (Map.Entry<String, Object> entry : vMap.entrySet()) {
120                         String vName = entry.getKey();
121                         Object value = entry.getValue();
122                         @SuppressWarnings("unchecked")
123                         Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
124                         inputVariables.put(vName, valueMap.get("value"));
125                 }
126                 return inputVariables;
127         }
128         
129     protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
130         String value = Objects.toString(inputVariables.get(key), null);
131         if (value == null) {
132             value = UUID.randomUUID().toString();
133             inputVariables.put(key, value);
134         }
135         return value;
136     }
137     
138         protected long getWaitTime(Map<String, Object> inputVariables)
139         {
140             
141                 String timeout = Objects.toString(inputVariables.get("mso-service-request-timeout"), null);
142
143                 if (timeout != null) {
144                         try {
145                                 return Long.parseLong(timeout)*1000;
146                         } catch (NumberFormatException nex) {
147                                 msoLogger.debug("Invalid input for mso-service-request-timeout");
148                         }
149                 }
150
151                 return DEFAULT_WAIT_TIME;
152         }
153 }