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