6621300210080519f630f8d117432b3e2c6a2c8a
[so.git] / bpmn / MSOCommonBPMN / src / test / java / org / openecomp / mso / bpmn / common / BPMNUtil.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
6  * ================================================================================\r
7  * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * you may not use this file except in compliance with the License.\r
9  * You may obtain a copy of the License at\r
10  *\r
11  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  *\r
13  * Unless required by applicable law or agreed to in writing, software\r
14  * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * See the License for the specific language governing permissions and\r
17  * limitations under the License.\r
18  * ============LICENSE_END=========================================================\r
19  */\r
20 \r
21 package org.openecomp.mso.bpmn.common;\r
22 \r
23 import static org.junit.Assert.assertEquals;\r
24 import static org.junit.Assert.assertNotNull;\r
25 import static org.junit.Assert.assertNull;\r
26 import static org.junit.Assert.assertTrue;\r
27 import static org.junit.Assert.fail;\r
28 import static org.mockito.Matchers.any;\r
29 import static org.mockito.Mockito.doAnswer;\r
30 import static org.mockito.Mockito.spy;\r
31 \r
32 import java.util.HashMap;\r
33 import java.util.List;\r
34 import java.util.Map;\r
35 \r
36 import javax.ws.rs.core.Response;\r
37 \r
38 import org.camunda.bpm.engine.ProcessEngineServices;\r
39 import org.camunda.bpm.engine.history.HistoricProcessInstance;\r
40 import org.camunda.bpm.engine.history.HistoricVariableInstance;\r
41 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;\r
42 import org.jboss.resteasy.spi.AsynchronousResponse;\r
43 import org.mockito.invocation.InvocationOnMock;\r
44 import org.mockito.stubbing.Answer;\r
45 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource;\r
46 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource;\r
47 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse;\r
48 \r
49 /**\r
50  * Set of utility methods used for Unit testing\r
51  */\r
52 public class BPMNUtil {\r
53 \r
54     public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {\r
55         String pID = getProcessInstanceId(processEngineServices,\r
56                 processDefinitionID);\r
57         assertProcessInstanceFinished(processEngineServices, pID);\r
58         HistoricVariableInstance responseData = processEngineServices.getHistoryService()\r
59                 .createHistoricVariableInstanceQuery().processInstanceId(pID)\r
60                 .variableName(name)\r
61                 .singleResult();\r
62 \r
63         if (responseData != null) {\r
64             return (responseData.getValue() != null ? responseData.getValue().toString() : null);\r
65         }\r
66         return null;\r
67     }\r
68 \r
69     @SuppressWarnings("unchecked")\r
70     public static <T> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {\r
71         String pID = getProcessInstanceId(processEngineServices,\r
72                 processDefinitionID);\r
73         assertProcessInstanceFinished(processEngineServices, pID);\r
74         Object responseData = processEngineServices.getHistoryService()\r
75                 .createHistoricVariableInstanceQuery().processInstanceId(pID)\r
76                 .variableName(name)\r
77                 .singleResult()\r
78                 .getValue();\r
79         return (T) responseData;\r
80     }\r
81 \r
82 \r
83     public static void assertAnyProcessInstanceFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
84         String pID = getProcessInstanceId(processEngineServices,\r
85                 processDefinitionID);\r
86         assertNotNull(pID);\r
87         assertTrue(processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count() > 0);\r
88     }\r
89 \r
90     public static void assertNoProcessInstance(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
91         assertNull(getProcessInstanceId(processEngineServices, processDefinitionID));\r
92     }\r
93 \r
94     public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {\r
95         assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());\r
96     }\r
97 \r
98     public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
99         String pID = getProcessInstanceId(processEngineServices,\r
100                 processDefinitionID);\r
101         assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count());\r
102     }\r
103 \r
104     private static String getProcessInstanceId(\r
105             ProcessEngineServices processEngineServices, String processDefinitionID) {\r
106         List<HistoricProcessInstance> historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();\r
107         String pID = null;\r
108         for (HistoricProcessInstance hInstance : historyList) {\r
109             if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {\r
110                 pID = hInstance.getId();\r
111                 break;\r
112             }\r
113         }\r
114         return pID;\r
115     }\r
116 \r
117     public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {\r
118         return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true : false;\r
119     }\r
120 \r
121 \r
122     private static void buildVariable(String key, String value, Map<String, Object> variableValueType) {\r
123         Map<String, Object> host = new HashMap<>();\r
124         host.put("value", value);\r
125         host.put("type", "String");\r
126         variableValueType.put(key, host);\r
127     }\r
128 \r
129     public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map<String, String> variables) {\r
130         WorkflowResource workflowResource = new WorkflowResource();\r
131         VariableMapImpl variableMap = new VariableMapImpl();\r
132 \r
133         Map<String, Object> variableValueType = new HashMap<>();\r
134         for (String key : variables.keySet()) {\r
135             buildVariable(key, variables.get(key), variableValueType);\r
136         }\r
137         buildVariable("mso-service-request-timeout", "600", variableValueType);\r
138         variableMap.put("variables", variableValueType);\r
139 \r
140         workflowResource.setProcessEngineServices4junit(processEngineServices);\r
141         Response response = workflowResource.startProcessInstanceByKey(\r
142                 processKey, variableMap);\r
143         WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();\r
144         return workflowResponse;\r
145     }\r
146 \r
147     //Check the runtime service to see whether the process is completed\r
148     public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException {\r
149         // Don't wait forever\r
150         long waitTime = 120000;\r
151         long endTime = System.currentTimeMillis() + waitTime;\r
152 \r
153         while (true) {\r
154             if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {\r
155                 break;\r
156             }\r
157 \r
158             if (System.currentTimeMillis() >= endTime) {\r
159                 fail("Process " + pid + " did not finish in " + waitTime + "ms");\r
160             }\r
161 \r
162             Thread.sleep(200);\r
163         }\r
164     }\r
165 \r
166     /**\r
167      * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object\r
168      *\r
169      * @param processEngineServices\r
170      * @param processKey\r
171      * @param variables\r
172      * @return\r
173      * @throws InterruptedException\r
174      */\r
175     public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map<String, String> variables) throws InterruptedException {\r
176         ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables);\r
177         pthread.start();\r
178         BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey);\r
179         String pid = getProcessInstanceId(processEngineServices, processKey);\r
180         //Caution: If there is a problem with workflow, this may wait for ever\r
181         while (true) {\r
182             pid = getProcessInstanceId(processEngineServices, processKey);\r
183             if (!isProcessInstanceFinished(processEngineServices, pid)) {\r
184                 Thread.sleep(200);\r
185             } else {\r
186                 break;\r
187             }\r
188         }\r
189         //need to retrieve for second time ?\r
190         pid = getProcessInstanceId(processEngineServices, processKey);\r
191         waitForWorkflowToFinish(processEngineServices, pid);\r
192         return pthread.workflowResponse;\r
193     }\r
194 \r
195     /**\r
196      * Execute workflow using async resource\r
197      *\r
198      * @param processEngineServices\r
199      * @param processKey\r
200      * @param asyncResponse\r
201      * @param variables\r
202      */\r
203     private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, AsynchronousResponse asyncResponse, Map<String, String> variables) {\r
204         WorkflowAsyncResource workflowResource = new WorkflowAsyncResource();\r
205         VariableMapImpl variableMap = new VariableMapImpl();\r
206 \r
207         Map<String, Object> variableValueType = new HashMap<>();\r
208         for (String key : variables.keySet()) {\r
209             buildVariable(key, variables.get(key), variableValueType);\r
210         }\r
211         buildVariable("mso-service-request-timeout", "600", variableValueType);\r
212         variableMap.put("variables", variableValueType);\r
213 \r
214         workflowResource.setProcessEngineServices4junit(processEngineServices);\r
215         workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMap);\r
216     }\r
217 \r
218     /**\r
219      * Helper class which executes workflow in a thread\r
220      */\r
221     static class ProcessThread extends Thread {\r
222 \r
223         public WorkflowResponse workflowResponse = null;\r
224         public String processKey;\r
225         public AsynchronousResponse asyncResponse = spy(AsynchronousResponse.class);\r
226         public boolean started;\r
227         public ProcessEngineServices processEngineServices;\r
228         public Map<String, String> variables;\r
229 \r
230         public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map<String, String> variables) {\r
231             this.processKey = processKey;\r
232             this.processEngineServices = processEngineServices;\r
233             this.variables = variables;\r
234         }\r
235 \r
236         public void run() {\r
237             started = true;\r
238             doAnswer(new Answer<Void>() {\r
239                 public Void answer(InvocationOnMock invocation) {\r
240                     Response response = (Response) invocation.getArguments()[0];\r
241                     workflowResponse = (WorkflowResponse) response.getEntity();\r
242                     return null;\r
243                 }\r
244             }).when(asyncResponse).setResponse(any(Response.class));\r
245             executeAsyncFlow(processEngineServices, processKey, asyncResponse, variables);\r
246         }\r
247     }\r
248 }\r