Merge "Add junit test coverage and fix bugs in VCPE"
[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.WorkflowAsyncCommonResource;\r
46 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource;\r
47 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource;\r
48 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse;\r
49 \r
50 /**\r
51  * Set of utility methods used for Unit testing\r
52  *\r
53  */\r
54 public class BPMNUtil {\r
55 \r
56         public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {\r
57                 String pID = getProcessInstanceId(processEngineServices,\r
58                                 processDefinitionID);\r
59                 assertProcessInstanceFinished(processEngineServices, pID);\r
60                 HistoricVariableInstance responseData = processEngineServices.getHistoryService()\r
61                             .createHistoricVariableInstanceQuery().processInstanceId(pID)\r
62                             .variableName(name)\r
63                             .singleResult();\r
64                 \r
65                 if (responseData != null) {\r
66                         return (responseData.getValue() != null ? responseData.getValue().toString(): null); \r
67                 }\r
68                 return null;\r
69         }\r
70 \r
71         @SuppressWarnings("unchecked")\r
72         public static <T extends Object> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {\r
73                 String pID = getProcessInstanceId(processEngineServices,\r
74                                 processDefinitionID);\r
75                 assertProcessInstanceFinished(processEngineServices, pID);\r
76                 Object responseData = processEngineServices.getHistoryService()\r
77                             .createHistoricVariableInstanceQuery().processInstanceId(pID)\r
78                             .variableName(name)\r
79                             .singleResult()\r
80                             .getValue();\r
81                 return (T) responseData;\r
82         }\r
83 \r
84         \r
85         public static void assertAnyProcessInstanceFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
86                 String pID = getProcessInstanceId(processEngineServices,\r
87                                 processDefinitionID);\r
88                 assertNotNull(pID);\r
89             assertTrue(processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count() > 0);\r
90         }\r
91         \r
92         public static void assertNoProcessInstance(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
93                 assertNull(getProcessInstanceId(processEngineServices, processDefinitionID));\r
94         }\r
95         \r
96         public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {\r
97             assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());\r
98         }\r
99         \r
100         public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
101                 String pID = getProcessInstanceId(processEngineServices,\r
102                                 processDefinitionID);           \r
103             assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count());\r
104         }\r
105 \r
106         private static String getProcessInstanceId(\r
107                         ProcessEngineServices processEngineServices, String processDefinitionID) {\r
108                 List<HistoricProcessInstance> historyList =  processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();\r
109                 String pID = null;\r
110                 for (HistoricProcessInstance hInstance: historyList) {\r
111                         if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {\r
112                                 pID = hInstance.getId();\r
113                                 break;\r
114                         }\r
115                 }\r
116                 return pID;\r
117         }\r
118 \r
119         public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {\r
120             return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false;\r
121         }\r
122 \r
123         \r
124         private static void buildVariable(String key, String value, Map<String,Object> variableValueType) {\r
125                 Map<String, Object> host = new HashMap<String, Object>();\r
126                 host.put("value", value);\r
127                 host.put("type", "String");\r
128                 variableValueType.put(key, host);\r
129         }\r
130         \r
131         public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) {\r
132                 WorkflowResource workflowResource = new WorkflowResource();\r
133                 VariableMapImpl variableMap = new VariableMapImpl();\r
134 \r
135                 Map<String, Object> variableValueType = new HashMap<String, Object>();\r
136                 for (String key : variables.keySet()) {\r
137                         buildVariable(key, variables.get(key), variableValueType);\r
138                 }\r
139                 buildVariable("mso-service-request-timeout","600", variableValueType);\r
140                 variableMap.put("variables", variableValueType);\r
141                 \r
142                 workflowResource.setProcessEngineServices4junit(processEngineServices);\r
143                 Response response = workflowResource.startProcessInstanceByKey(\r
144                                         processKey, variableMap);\r
145                 WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();\r
146                 return workflowResponse;\r
147         }\r
148 \r
149         //Check the runtime service to see whether the process is completed\r
150         public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException {\r
151                 // Don't wait forever\r
152                 long waitTime = 120000;\r
153                 long endTime = System.currentTimeMillis() + waitTime;\r
154 \r
155                 while (true) {\r
156                         if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {\r
157                                 break;\r
158                         }\r
159 \r
160                         if (System.currentTimeMillis() >= endTime) {\r
161                                 fail("Process " + pid + " did not finish in " + waitTime + "ms");\r
162                         }\r
163 \r
164                         Thread.sleep(200);\r
165                 }\r
166         }\r
167         \r
168         /**\r
169          * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object\r
170          * @param processEngineServices\r
171          * @param processKey\r
172          * @param variables\r
173          * @return\r
174          * @throws InterruptedException\r
175          */\r
176         public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) throws InterruptedException {\r
177                 ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables);\r
178                 pthread.start();\r
179                 BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey);\r
180                 String pid = getProcessInstanceId(processEngineServices, processKey);\r
181                 //Caution: If there is a problem with workflow, this may wait for ever\r
182                 while (true) {\r
183                         pid = getProcessInstanceId(processEngineServices, processKey);\r
184                         if (!isProcessInstanceFinished(processEngineServices,pid)) {\r
185                                 Thread.sleep(200);\r
186                         } else{\r
187                                 break;\r
188                         }\r
189                 }\r
190                 //need to retrieve for second time ?\r
191                 pid = getProcessInstanceId(processEngineServices, processKey);\r
192                 waitForWorkflowToFinish(processEngineServices, pid);\r
193                 return pthread.workflowResponse;\r
194         }\r
195 \r
196         /**\r
197          * Execute workflow using async resource\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 WorkflowAsyncCommonResource();\r
205                 VariableMapImpl variableMap = new VariableMapImpl();\r
206 \r
207                 Map<String, Object> variableValueType = new HashMap<String, Object>();\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          */\r
222         static class ProcessThread extends Thread {\r
223                 \r
224                 public WorkflowResponse workflowResponse = null;\r
225                 public String processKey;\r
226                 public AsynchronousResponse asyncResponse = spy(AsynchronousResponse.class);\r
227                 public boolean started;\r
228                 public ProcessEngineServices processEngineServices;\r
229                 public Map<String,String> variables;\r
230                 \r
231                 public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map<String,String> variables) {\r
232                         this.processKey = processKey;\r
233                         this.processEngineServices = processEngineServices;\r
234                         this.variables = variables;\r
235                 }\r
236                 \r
237                 public void run() {\r
238                         started = true;\r
239                         doAnswer(new Answer<Void>() {\r
240                             public Void answer(InvocationOnMock invocation) {\r
241                               Response response = (Response) invocation.getArguments()[0];\r
242                               workflowResponse = (WorkflowResponse) response.getEntity();\r
243                               return null;\r
244                             }\r
245                         }).when(asyncResponse).setResponse(any(Response.class));                \r
246                         executeAsyncFlow(processEngineServices, processKey, asyncResponse, variables);\r
247                 }\r
248         }\r
249 }\r