f9f06447a755a67c2d6861167ef77c4128613f01
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / java / org / onap / so / bpmn / common / workflow / service / WorkflowAsyncResource.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.common.workflow.service;
24
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.UUID;
29
30 import javax.ws.rs.Consumes;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.PathParam;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.ext.Provider;
37
38 import org.camunda.bpm.engine.ProcessEngineServices;
39 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
40 import org.onap.logging.ref.slf4j.ONAPLogConstants;
41 import org.onap.so.bpmn.common.workflow.context.WorkflowContext;
42 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
43 import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
44 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowProcessorException;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.slf4j.MDC;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.stereotype.Component;
50
51 import io.swagger.annotations.Api;
52 import io.swagger.annotations.ApiOperation;
53
54
55 /**
56  * 
57  * @version 1.0
58  * Asynchronous Workflow processing using JAX RS RESTeasy implementation
59  * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background
60  * and the server thread is freed up, server scales better to process more incoming requests
61  * 
62  * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response
63  * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process
64  */
65 @Path("/async")
66 @Api(value = "/async", description = "Provides asynchronous starting of a bpmn process")
67 @Provider
68 @Component
69 public class WorkflowAsyncResource extends ProcessEngineAwareService {
70
71         private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
72
73         long workflowPollInterval=1000; 
74
75         @Autowired
76         private WorkflowProcessor processor;
77         
78         @Autowired
79         private WorkflowContextHolder workflowContext;
80         
81         public void setProcessor(WorkflowProcessor processor) {
82                 this.processor = processor;
83         }
84
85         protected static final Logger logger = LoggerFactory.getLogger(WorkflowAsyncResource.class);
86         protected static final long DEFAULT_WAIT_TIME = 60000;  //default wait time
87         
88         /**
89          * Asynchronous JAX-RS method that starts a process instance.
90          * @param processKey the process key
91          * @param variableMap input variables to the process
92          * @return 
93          */
94         
95         @POST
96         @Path("/services/{processKey}")
97         @ApiOperation(
98                         value = "Starts a new process with the appropriate process Key",
99                         notes = "Aysnc fall outs are only logged"
100                     )
101         @Produces("application/json")
102         @Consumes("application/json")
103         public Response startProcessInstanceByKey (
104                         @PathParam("processKey") String processKey, VariableMapImpl variableMap){
105                 Map<String, Object> inputVariables = getInputVariables(variableMap);    
106                 try {           
107                         MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, getRequestId(inputVariables));
108                         processor.startProcess(processKey, variableMap);
109                         WorkflowResponse response = waitForResponse(getRequestId(inputVariables)); 
110                         return Response.status(202).entity(response).build();   
111                 } catch (WorkflowProcessorException e) {
112                         WorkflowResponse response =  e.getWorkflowResponse();
113                         return Response.status(500).entity(response).build();
114                 }catch (Exception e) {
115                         WorkflowResponse response =  buildUnkownError(getRequestId(inputVariables),e.getMessage());             
116                         return Response.status(500).entity(response).build();   
117                 }               
118         }
119         
120         private WorkflowResponse waitForResponse(String requestId) throws Exception {           
121                 long currentWaitTime = 0;               
122                 while (DEFAULT_WAIT_TIME > currentWaitTime ) {                  
123                         Thread.sleep(workflowPollInterval);
124                         currentWaitTime = currentWaitTime + workflowPollInterval;
125                         WorkflowContext foundContext = contextHolder.getWorkflowContext(requestId);
126                         if(foundContext!=null){
127                                 contextHolder.remove(foundContext);
128                                 return buildResponse(foundContext);
129                         }
130                 }
131                 throw new Exception("TimeOutOccured");
132         }
133
134         private WorkflowResponse buildUnkownError(String requestId,String error) {
135                 WorkflowResponse response = new WorkflowResponse();
136                 response.setMessage(error);
137                 response.setResponse("UnknownError, request id:" + requestId);          
138                 response.setMessageCode(500);
139                 return response;
140         }
141
142         private WorkflowResponse buildResponse(WorkflowContext foundContext) {
143                 return foundContext.getWorkflowResponse();
144         }
145         
146     protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
147         String value = Objects.toString(inputVariables.get(key), null);
148         if (value == null) {
149             value = UUID.randomUUID().toString();
150             inputVariables.put(key, value);
151         }
152         return value;
153     }
154
155         protected static String getRequestId(Map<String, Object> inputVariables) {
156         return getOrCreate(inputVariables, "mso-request-id");
157         }
158
159         protected boolean isProcessEnded(String processInstanceId) {
160                 ProcessEngineServices pes = getProcessEngineServices();
161                 return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
162         }
163         
164         protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
165                 Map<String, Object> inputVariables = new HashMap<>();
166                 @SuppressWarnings("unchecked")
167                 Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
168                 for (Map.Entry<String, Object> entry : vMap.entrySet()) {
169                         String vName = entry.getKey();
170                         Object value = entry.getValue();
171                         @SuppressWarnings("unchecked")
172                         Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
173                         inputVariables.put(vName, valueMap.get("value"));
174                 }
175                 return inputVariables;
176         }
177
178 }