Clean up Process Engine selection logic
[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  */\r
53 public class BPMNUtil {\r
54 \r
55         public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {\r
56                 String pID = getProcessInstanceId(processEngineServices,\r
57                                 processDefinitionID);\r
58                 assertProcessInstanceFinished(processEngineServices, pID);\r
59                 HistoricVariableInstance responseData = processEngineServices.getHistoryService()\r
60                             .createHistoricVariableInstanceQuery().processInstanceId(pID)\r
61                             .variableName(name)\r
62                             .singleResult();\r
63                 \r
64                 if (responseData != null) {\r
65                         return (responseData.getValue() != null ? responseData.getValue().toString(): null); \r
66                 }\r
67                 return null;\r
68         }\r
69 \r
70         @SuppressWarnings("unchecked")\r
71         public static <T extends Object> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) {\r
72                 String pID = getProcessInstanceId(processEngineServices,\r
73                                 processDefinitionID);\r
74                 assertProcessInstanceFinished(processEngineServices, pID);\r
75                 Object responseData = processEngineServices.getHistoryService()\r
76                             .createHistoricVariableInstanceQuery().processInstanceId(pID)\r
77                             .variableName(name)\r
78                             .singleResult()\r
79                             .getValue();\r
80                 return (T) responseData;\r
81         }\r
82 \r
83         \r
84         public static void assertAnyProcessInstanceFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
85                 String pID = getProcessInstanceId(processEngineServices,\r
86                                 processDefinitionID);\r
87                 assertNotNull(pID);\r
88             assertTrue(processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count() > 0);\r
89         }\r
90         \r
91         public static void assertNoProcessInstance(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
92                 assertNull(getProcessInstanceId(processEngineServices, processDefinitionID));\r
93         }\r
94         \r
95         public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {\r
96             assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count());\r
97         }\r
98         \r
99         public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) {\r
100                 String pID = getProcessInstanceId(processEngineServices,\r
101                                 processDefinitionID);           \r
102             assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count());\r
103         }\r
104 \r
105         private static String getProcessInstanceId(\r
106                         ProcessEngineServices processEngineServices, String processDefinitionID) {\r
107                 List<HistoricProcessInstance> historyList =  processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list();\r
108                 String pID = null;\r
109                 for (HistoricProcessInstance hInstance: historyList) {\r
110                         if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) {\r
111                                 pID = hInstance.getId();\r
112                                 break;\r
113                         }\r
114                 }\r
115                 return pID;\r
116         }\r
117 \r
118         public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) {\r
119             return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false;\r
120         }\r
121 \r
122         \r
123         private static void buildVariable(String key, String value, Map<String,Object> variableValueType) {\r
124                 Map<String, Object> host = new HashMap<String, Object>();\r
125                 host.put("value", value);\r
126                 host.put("type", "String");\r
127                 variableValueType.put(key, host);\r
128         }\r
129         \r
130         public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) {\r
131                 WorkflowResource workflowResource = new WorkflowResource();\r
132                 VariableMapImpl variableMap = new VariableMapImpl();\r
133 \r
134                 Map<String, Object> variableValueType = new HashMap<String, Object>();\r
135                 for (String key : variables.keySet()) {\r
136                         buildVariable(key, variables.get(key), variableValueType);\r
137                 }\r
138                 buildVariable("mso-service-request-timeout","600", variableValueType);\r
139                 variableMap.put("variables", variableValueType);\r
140                 \r
141                 workflowResource.setProcessEngineServices4junit(processEngineServices);\r
142                 Response response = workflowResource.startProcessInstanceByKey(\r
143                                         processKey, variableMap);\r
144                 WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity();\r
145                 return workflowResponse;\r
146         }\r
147 \r
148         //Check the runtime service to see whether the process is completed\r
149         public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException {\r
150                 // Don't wait forever\r
151                 long waitTime = 120000;\r
152                 long endTime = System.currentTimeMillis() + waitTime;\r
153 \r
154                 while (true) {\r
155                         if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) {\r
156                                 break;\r
157                         }\r
158 \r
159                         if (System.currentTimeMillis() >= endTime) {\r
160                                 fail("Process " + pid + " did not finish in " + waitTime + "ms");\r
161                         }\r
162 \r
163                         Thread.sleep(200);\r
164                 }\r
165         }\r
166         \r
167         /**\r
168          * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object\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          * @param processEngineServices\r
198          * @param processKey\r
199          * @param asyncResponse\r
200          * @param variables\r
201          */\r
202         private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, AsynchronousResponse asyncResponse, Map<String,String> variables) {\r
203                 WorkflowAsyncResource workflowResource = new WorkflowAsyncResource();\r
204                 VariableMapImpl variableMap = new VariableMapImpl();\r
205 \r
206                 Map<String, Object> variableValueType = new HashMap<String, Object>();\r
207                 for (String key : variables.keySet()) {\r
208                         buildVariable(key, variables.get(key), variableValueType);\r
209                 }\r
210                 buildVariable("mso-service-request-timeout","600", variableValueType);\r
211                 variableMap.put("variables", variableValueType);\r
212                 \r
213                 workflowResource.setProcessEngineServices4junit(processEngineServices);\r
214                 workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMap);\r
215         }\r
216         \r
217         /**\r
218          * Helper class which executes workflow in a thread\r
219          *\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