2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.so.bpmn.common.workflow.service;
23 import java.util.HashMap;
25 import java.util.Objects;
26 import java.util.Optional;
27 import java.util.UUID;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.POST;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.PathParam;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.ext.Provider;
37 import org.camunda.bpm.engine.ProcessEngineServices;
38 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
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;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
47 import io.swagger.annotations.Api;
48 import io.swagger.annotations.ApiOperation;
54 * Asynchronous Workflow processing using JAX RS RESTeasy implementation
55 * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background
56 * and the server thread is freed up, server scales better to process more incoming requests
58 * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response
59 * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process
62 @Api(value = "/async", description = "Provides asynchronous starting of a bpmn process")
65 public class WorkflowAsyncResource extends ProcessEngineAwareService {
67 private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
70 protected Optional<ProcessEngineServices> pes4junit = Optional.empty();
72 long workflowPollInterval=1000;
75 private WorkflowProcessor processor;
78 private WorkflowContextHolder workflowContext;
80 public WorkflowProcessor getProcessor() {
86 public void setProcessor(WorkflowProcessor processor) {
87 this.processor = processor;
90 protected static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL,WorkflowAsyncResource.class);
91 protected static final long DEFAULT_WAIT_TIME = 60000; //default wait time
94 * Asynchronous JAX-RS method that starts a process instance.
95 * @param asyncResponse an object that will receive the asynchronous response
96 * @param processKey the process key
97 * @param variableMap input variables to the process
102 @Path("/services/{processKey}")
104 value = "Starts a new process with the appropriate process Key",
105 notes = "Aysnc fall outs are only logged"
107 @Produces("application/json")
108 @Consumes("application/json")
109 public Response startProcessInstanceByKey (
110 @PathParam("processKey") String processKey, VariableMapImpl variableMap){
111 Map<String, Object> inputVariables = getInputVariables(variableMap);
113 MDC.put(MsoLogger.REQUEST_ID, getRequestId(inputVariables));
114 processor.startProcess(processKey, variableMap);
115 WorkflowResponse response = waitForResponse(getRequestId(inputVariables));
116 return Response.status(202).entity(response).build();
117 } catch (Exception e) {
118 WorkflowResponse response = buildUnkownError(getRequestId(inputVariables),e.getMessage());
119 return Response.status(500).entity(response).build();
123 private WorkflowResponse waitForResponse(String requestId) throws Exception {
124 long currentWaitTime = 0;
125 while (DEFAULT_WAIT_TIME > currentWaitTime ) {
126 Thread.sleep(workflowPollInterval);
127 currentWaitTime = currentWaitTime + workflowPollInterval;
128 WorkflowContext foundContext = contextHolder.getWorkflowContext(requestId);
129 if(foundContext!=null){
130 contextHolder.remove(foundContext);
131 return buildResponse(foundContext);
134 throw new Exception("TimeOutOccured");
137 private WorkflowResponse buildTimeoutResponse(String requestId) {
138 WorkflowResponse response = new WorkflowResponse();
139 response.setMessage("Fail");
140 response.setResponse("Request timedout, request id:" + requestId);
141 response.setMessageCode(500);
145 private WorkflowResponse buildUnkownError(String requestId,String error) {
146 WorkflowResponse response = new WorkflowResponse();
147 response.setMessage(error);
148 response.setResponse("UnknownError, request id:" + requestId);
149 response.setMessageCode(500);
153 private WorkflowResponse buildResponse(WorkflowContext foundContext) {
154 return foundContext.getWorkflowResponse();
157 protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
158 String value = Objects.toString(inputVariables.get(key), null);
160 value = UUID.randomUUID().toString();
161 inputVariables.put(key, value);
166 // Note: the business key is used to identify the process in unit tests
167 protected static String getBusinessKey(Map<String, Object> inputVariables) {
168 return getOrCreate(inputVariables, "mso-business-key");
171 protected static String getRequestId(Map<String, Object> inputVariables) {
172 return getOrCreate(inputVariables, "mso-request-id");
177 protected void recordEvents(String processKey, WorkflowResponse response,
180 msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
181 response.getMessage() + " for processKey: "
182 + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null);
184 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
185 response.getMessage() + "for processKey: " + processKey + " with response: " + response.getResponse());
189 protected static void setLogContext(String processKey,
190 Map<String, Object> inputVariables) {
191 MsoLogger.setServiceName("MSO." + processKey);
192 if (inputVariables != null) {
193 MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"serviceInstanceId"));
197 protected static String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {
198 if (inputVariables == null) {
202 return Objects.toString(inputVariables.get(key), "N/A");
205 protected boolean isProcessEnded(String processInstanceId) {
206 ProcessEngineServices pes = getProcessEngineServices();
207 return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
210 protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
211 Map<String, Object> inputVariables = new HashMap<>();
212 @SuppressWarnings("unchecked")
213 Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
214 for (Map.Entry<String, Object> entry : vMap.entrySet()) {
215 String vName = entry.getKey();
216 Object value = entry.getValue();
217 @SuppressWarnings("unchecked")
218 Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
219 inputVariables.put(vName, valueMap.get("value"));
221 return inputVariables;
225 protected long getWaitTime(Map<String, Object> inputVariables)
228 String timeout = Objects.toString(inputVariables.get("mso-service-request-timeout"), null);
230 if (timeout != null) {
232 return Long.parseLong(timeout)*1000;
233 } catch (NumberFormatException nex) {
234 msoLogger.debug("Invalid input for mso-service-request-timeout");
238 return DEFAULT_WAIT_TIME;