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