2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.so.bpmn.common.workflow.service;
25 import java.util.HashMap;
27 import java.util.Objects;
28 import java.util.UUID;
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;
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;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.stereotype.Component;
51 import io.swagger.annotations.Api;
52 import io.swagger.annotations.ApiOperation;
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
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
66 @Api(value = "/async", description = "Provides asynchronous starting of a bpmn process")
69 public class WorkflowAsyncResource extends ProcessEngineAwareService {
71 private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
73 long workflowPollInterval=1000;
76 private WorkflowProcessor processor;
79 private WorkflowContextHolder workflowContext;
81 public void setProcessor(WorkflowProcessor processor) {
82 this.processor = processor;
85 protected static final Logger logger = LoggerFactory.getLogger(WorkflowAsyncResource.class);
86 protected static final long DEFAULT_WAIT_TIME = 60000; //default wait time
89 * Asynchronous JAX-RS method that starts a process instance.
90 * @param processKey the process key
91 * @param variableMap input variables to the process
96 @Path("/services/{processKey}")
98 value = "Starts a new process with the appropriate process Key",
99 notes = "Aysnc fall outs are only logged"
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);
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();
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);
131 throw new Exception("TimeOutOccured");
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);
142 private WorkflowResponse buildResponse(WorkflowContext foundContext) {
143 return foundContext.getWorkflowResponse();
146 protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
147 String value = Objects.toString(inputVariables.get(key), null);
149 value = UUID.randomUUID().toString();
150 inputVariables.put(key, value);
155 protected static String getRequestId(Map<String, Object> inputVariables) {
156 return getOrCreate(inputVariables, "mso-request-id");
159 protected boolean isProcessEnded(String processInstanceId) {
160 ProcessEngineServices pes = getProcessEngineServices();
161 return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
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"));
175 return inputVariables;