Containerization feature of SO
[so.git] / bpmn / mso-infrastructure-bpmn / src / test / java / org / onap / so / bpmn / common / BPMNUtil.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;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.ws.rs.core.Response;
35
36 import org.camunda.bpm.engine.HistoryService;
37 import org.camunda.bpm.engine.ProcessEngineServices;
38 import org.camunda.bpm.engine.RuntimeService;
39 import org.camunda.bpm.engine.history.HistoricProcessInstance;
40 import org.camunda.bpm.engine.history.HistoricVariableInstance;
41 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
42 import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
43 import org.onap.so.bpmn.common.workflow.service.WorkflowAsyncResource;
44 import org.onap.so.bpmn.common.workflow.service.WorkflowResource;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.stereotype.Component;
47
48 /**
49  * Set of utility methods used for Unit testing
50  *
51  */
52 @Component
53 public class BPMNUtil {
54
55         private static WorkflowAsyncResource workflowResource;
56         
57         @Autowired
58         public void setWorkflowResource(WorkflowAsyncResource workflowResource) {
59                 BPMNUtil.workflowResource = workflowResource;
60         }
61
62         public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {
63                 String pID = getProcessInstanceId(processEngineServices,
64                                 processDefinitionID);
65                 return getVariable( processEngineServices,  processDefinitionID,  name,  pID);
66         }
67         
68         public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name, String processInstanceId) {
69                 assertProcessInstanceFinished(processEngineServices, processInstanceId);
70                 HistoricVariableInstance responseData = processEngineServices.getHistoryService()
71                             .createHistoricVariableInstanceQuery().processInstanceId(processInstanceId)
72                             .variableName(name)
73                             .singleResult();
74                 
75                 if (responseData != null) {
76                         return (responseData.getValue() != null ? responseData.getValue().toString(): null); 
77                 }
78                 return null;
79         }
80
81         /*
82         @SuppressWarnings("unchecked")
83         public static <T extends Object> T getRawVariable(HistoryService historyService, String processDefinitionID, String name) {
84                 //String pID = getProcessInstanceId(processEngineServices,
85                 //              processDefinitionID);
86                 assertProcessInstanceFinished(historyService, pID);
87                 Object responseData = historyService
88                             .createHistoricVariableInstanceQuery().processInstanceId(pID)
89                             .variableName(name)
90                             .singleResult()
91                             .getValue();
92                 return (T) responseData;
93         }
94         */
95         
96         @SuppressWarnings("unchecked")
97         public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {
98                 String pID = getProcessInstanceId(processEngineServices,
99                                 processDefinitionID);
100                 return getRawVariable( processEngineServices,  processDefinitionID,  name,  pID);
101         }
102         
103         @SuppressWarnings("unchecked")
104         public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name, String processInstanceId) {
105                 assertProcessInstanceFinished(processEngineServices, processInstanceId);
106                 Object responseData = processEngineServices.getHistoryService()
107                             .createHistoricVariableInstanceQuery().processInstanceId(processInstanceId)
108                             .variableName(name)
109                             .singleResult()
110                             .getValue();
111                 return (T) responseData;
112         }
113
114         
115         public static void assertAnyProcessInstanceFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {
116                 String pID = getProcessInstanceId(processEngineServices,
117                                 processDefinitionID);
118                 assertNotNull(pID);
119             assertTrue(processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count() > 0);
120         }
121         
122         public static void assertNoProcessInstance(ProcessEngineServices processEngineServices, String processDefinitionID) {
123                 assertNull(getProcessInstanceId(processEngineServices, processDefinitionID));
124         }
125         
126         public static void assertProcessInstanceFinished(HistoryService historyService, String pid) {
127             assertEquals(1, historyService.createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());
128         }
129         
130         public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {
131             assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());
132         }
133         
134         public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {
135                 String pID = getProcessInstanceId(processEngineServices,
136                                 processDefinitionID);           
137             assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count());
138         }
139         
140         private static String getProcessInstanceId(
141                         ProcessEngineServices processEngineServices, String processDefinitionID) {
142                 List<HistoricProcessInstance> historyList =  processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();
143                 String pID = null;
144                 for (HistoricProcessInstance hInstance: historyList) {
145                         if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {
146                                 pID = hInstance.getId();
147                                 break;
148                         }
149                 }
150                 return pID;
151         }
152         
153         public static void cleanHistory(ProcessEngineServices processEngineServices) {
154                 List<HistoricProcessInstance> historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();
155                 List<String> pidList = new ArrayList<>();
156                 for (HistoricProcessInstance hInstance : historyList) {
157                         pidList.add(hInstance.getId());
158                 }
159                 if (pidList.size() > 0) {
160                         processEngineServices.getHistoryService().deleteHistoricProcessInstances(pidList);
161                 }
162         }
163         
164         private static String getProcessInstanceId(
165                         HistoryService historyService, String processDefinitionID) {
166                 List<HistoricProcessInstance> historyList =  historyService.createHistoricProcessInstanceQuery().list();
167                 String pID = null;
168                 for (HistoricProcessInstance hInstance: historyList) {
169                         if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {
170                                 pID = hInstance.getId();
171                                 break;
172                         }
173                 }
174                 return pID;
175         }
176
177         public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {
178             return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false;
179         }
180
181         
182         private static void buildVariable(String key, String value, Map<String,Object> variableValueType) {
183                 Map<String, Object> host = new HashMap<>();
184                 host.put("value", value);
185                 host.put("type", "String");
186                 variableValueType.put(key, host);
187         }
188         
189         public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) {
190                 VariableMapImpl variableMap = new VariableMapImpl();
191
192                 Map<String, Object> variableValueType = new HashMap<>();
193                 for (String key : variables.keySet()) {
194                         buildVariable(key, variables.get(key), variableValueType);
195                 }
196                 buildVariable("mso-service-request-timeout","600", variableValueType);
197                 variableMap.put("variables", variableValueType);
198                 
199                 workflowResource.setProcessEngineServices4junit(processEngineServices);
200                 Response response = workflowResource.startProcessInstanceByKey(
201                                         processKey, variableMap);
202                 WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();
203                 return workflowResponse;
204         }
205         
206         public static WorkflowResponse executeWorkFlow(RuntimeService runtimeService, String processKey, Map<String,String> variables, WorkflowResource workflowResource) {
207                 
208                 VariableMapImpl variableMap = new VariableMapImpl();
209
210                 Map<String, Object> variableValueType = new HashMap<String, Object>();
211                 for (String key : variables.keySet()) {
212                         buildVariable(key, variables.get(key), variableValueType);
213                 }
214                 buildVariable("mso-service-request-timeout","600", variableValueType);
215                 variableMap.put("variables", variableValueType);
216                 
217
218                 Response response = workflowResource.startProcessInstanceByKey(
219                                         processKey, variableMap);
220                 WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();
221                 return workflowResponse;
222         }
223
224         //Check the runtime service to see whether the process is completed
225         public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException {
226                 // Don't wait forever
227                 long waitTime = 120000;
228                 long endTime = System.currentTimeMillis() + waitTime;
229
230                 while (true) {
231                         if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {
232                                 break;
233                         }
234
235                         if (System.currentTimeMillis() >= endTime) {
236                                 fail("Process " + pid + " did not finish in " + waitTime + "ms");
237                         }
238
239                         Thread.sleep(200);
240                 }
241         }
242         
243         
244         //Check the runtime service to see whether the process is completed
245         public static void waitForWorkflowToFinish(RuntimeService runtimeService, String pid) throws InterruptedException {
246                 // Don't wait forever
247                 long waitTime = 120000;
248                 long endTime = System.currentTimeMillis() + waitTime;
249
250                 while (true) {
251                         if (runtimeService.createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {
252                                 break;
253                         }
254
255                         if (System.currentTimeMillis() >= endTime) {
256                                 fail("Process " + pid + " did not finish in " + waitTime + "ms");
257                         }
258
259                         Thread.sleep(200);
260                 }
261         }
262         
263         
264         /**
265          * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object
266          * @param processEngineServices
267          * @param processKey
268          * @param variables
269          * @return
270          * @throws InterruptedException
271          */
272         public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) throws InterruptedException {
273                 ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables);
274                 pthread.start();
275                 BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey);
276                 String pid = getProcessInstanceId(processEngineServices, processKey);
277                 //Caution: If there is a problem with workflow, this may wait for ever
278                 while (true) {
279                         pid = getProcessInstanceId(processEngineServices, processKey);
280                         if (!isProcessInstanceFinished(processEngineServices,pid)) {
281                                 Thread.sleep(200);
282                         } else{
283                                 break;
284                         }
285                 }
286                 //need to retrieve for second time ?
287                 pid = getProcessInstanceId(processEngineServices, processKey);
288                 waitForWorkflowToFinish(processEngineServices, pid);
289                 return pthread.workflowResponse;
290         }
291
292         /**
293          * Execute workflow using async resource
294          * @param processEngineServices
295          * @param processKey
296          * @param asyncResponse
297          * @param variables
298          * @throws InterruptedException 
299          */
300         private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) throws InterruptedException {
301                 VariableMapImpl variableMap = new VariableMapImpl();
302
303                 Map<String, Object> variableValueType = new HashMap<>();
304                 for (String key : variables.keySet()) {
305                         buildVariable(key, variables.get(key), variableValueType);
306                 }
307                 buildVariable("mso-service-request-timeout","600", variableValueType);
308                 variableMap.put("variables", variableValueType);
309                 
310                 workflowResource.setProcessEngineServices4junit(processEngineServices);
311                 workflowResource.startProcessInstanceByKey(processKey, variableMap);
312         }
313         
314         /**
315          * Helper class which executes workflow in a thread
316          *
317          */
318         static class ProcessThread extends Thread {
319                 
320                 public WorkflowResponse workflowResponse = null;
321                 public String processKey;
322                 public boolean started;
323                 public ProcessEngineServices processEngineServices;
324                 public Map<String,String> variables;
325                 
326                 public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map<String,String> variables) {
327                         this.processKey = processKey;
328                         this.processEngineServices = processEngineServices;
329                         this.variables = variables;
330                 }
331                 
332                 public void run() {
333                         started = true;
334                         /*doAnswer(new Answer<Void>() {
335                             public Void answer(InvocationOnMock invocation) {
336                               Response response = (Response) invocation.getArguments()[0];
337                               try {
338                               workflowResponse = (WorkflowResponse) response.getEntity();
339                               } catch (ClassCastException e) {
340                                   String workflowResponseString = (String)response.getEntity();
341                                   workflowResponse = new WorkflowResponse();
342                                   workflowResponse.setResponse(workflowResponseString);
343                                   workflowResponse.setMessageCode(200);
344                               }
345                               return null;
346                             }
347                         }).when(asyncResponse).setResponse(any(Response.class));
348                         */
349                         try {
350                                 executeAsyncFlow(processEngineServices, processKey, variables);
351                         } catch (InterruptedException e) {
352                                 // TODO Auto-generated catch block
353                                 e.printStackTrace();
354                         }
355                 }
356         }
357 }