2 * ============LICENSE_START=======================================================
\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
11 * http://www.apache.org/licenses/LICENSE-2.0
\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
21 package org.openecomp.mso.bpmn.common;
\r
23 import static org.junit.Assert.assertEquals;
\r
24 import static org.junit.Assert.fail;
\r
26 import java.io.IOException;
\r
27 import java.io.StringReader;
\r
28 import java.lang.management.ManagementFactory;
\r
29 import java.lang.management.RuntimeMXBean;
\r
30 import java.lang.reflect.Field;
\r
31 import java.lang.reflect.Modifier;
\r
32 import java.util.ArrayList;
\r
33 import java.util.Collections;
\r
34 import java.util.Comparator;
\r
35 import java.util.HashMap;
\r
36 import java.util.Iterator;
\r
37 import java.util.List;
\r
38 import java.util.Map;
\r
39 import java.util.UUID;
\r
41 import javax.ws.rs.core.Response;
\r
42 import javax.xml.bind.JAXBException;
\r
43 import javax.xml.namespace.NamespaceContext;
\r
44 import javax.xml.namespace.QName;
\r
45 import javax.xml.parsers.DocumentBuilder;
\r
46 import javax.xml.parsers.DocumentBuilderFactory;
\r
47 import javax.xml.parsers.ParserConfigurationException;
\r
48 import javax.xml.xpath.XPath;
\r
49 import javax.xml.xpath.XPathConstants;
\r
50 import javax.xml.xpath.XPathExpression;
\r
51 import javax.xml.xpath.XPathExpressionException;
\r
52 import javax.xml.xpath.XPathFactory;
\r
54 import org.camunda.bpm.engine.RuntimeService;
\r
55 import org.camunda.bpm.engine.history.HistoricProcessInstance;
\r
56 import org.camunda.bpm.engine.history.HistoricVariableInstance;
\r
57 import org.camunda.bpm.engine.runtime.ProcessInstance;
\r
58 import org.camunda.bpm.engine.test.ProcessEngineRule;
\r
59 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
\r
60 import org.custommonkey.xmlunit.DetailedDiff;
\r
61 import org.custommonkey.xmlunit.XMLUnit;
\r
62 import org.jboss.resteasy.spi.AsynchronousResponse;
\r
63 import org.json.JSONArray;
\r
64 import org.junit.Before;
\r
65 import org.junit.Rule;
\r
66 import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader;
\r
67 import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest;
\r
68 import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse;
\r
69 import org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification;
\r
70 import org.openecomp.mso.bpmn.common.adapter.vnf.DeleteVnfNotification;
\r
71 import org.openecomp.mso.bpmn.common.adapter.vnf.MsoExceptionCategory;
\r
72 import org.openecomp.mso.bpmn.common.adapter.vnf.MsoRequest;
\r
73 import org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification;
\r
74 import org.openecomp.mso.bpmn.common.adapter.vnf.VnfRollback;
\r
75 import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl;
\r
76 import org.openecomp.mso.bpmn.common.workflow.service.VnfAdapterNotifyServiceImpl;
\r
77 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource;
\r
78 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource;
\r
79 import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse;
\r
80 import org.openecomp.mso.bpmn.core.utils.CamundaDBSetup;
\r
81 import org.openecomp.mso.bpmn.core.PropertyConfigurationSetup;
\r
82 import org.openecomp.mso.bpmn.core.domain.Resource;
\r
83 import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;
\r
85 import static org.openecomp.mso.bpmn.core.json.JsonUtils.*;
\r
86 import org.w3c.dom.Document;
\r
87 import org.w3c.dom.Element;
\r
88 import org.w3c.dom.Node;
\r
89 import org.w3c.dom.NodeList;
\r
90 import org.xml.sax.InputSource;
\r
91 import org.xml.sax.SAXException;
\r
93 import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
\r
94 import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
\r
95 import com.github.tomakehurst.wiremock.junit.WireMockRule;
\r
100 * A base class for Workflow tests.
\r
102 * WireMock response transformers may be specified by declaring public
\r
103 * static fields with the @WorkflowTestTransformer annotation. For example:
\r
105 * @WorkflowTestTransformer
\r
106 * public static final ResponseTransformer sdncAdapterMockTransformer =
\r
107 * new SDNCAdapterMockTransformer();
\r
110 public class WorkflowTest {
\r
112 public final ProcessEngineRule processEngineRule = new ProcessEngineRule();
\r
115 public final WireMockRule wireMockRule;
\r
118 * Content-Type for XML.
\r
120 protected static final String XML = "application/xml";
\r
123 * Content-Type for JSON.
\r
125 protected static final String JSON = "application/json; charset=UTF-8";
\r
131 public WorkflowTest() throws RuntimeException {
\r
132 // Process WorkflowTestTransformer annotations
\r
133 List<ResponseTransformer> transformerList = new ArrayList<ResponseTransformer>();
\r
135 for (Field field : getClass().getFields()) {
\r
136 WorkflowTestTransformer annotation = (WorkflowTestTransformer)
\r
137 field.getAnnotation(WorkflowTestTransformer.class);
\r
139 if (annotation == null) {
\r
143 if (!Modifier.isStatic(field.getModifiers())) {
\r
144 throw new RuntimeException(field.getDeclaringClass().getName()
\r
145 + "#" + field.getName() + " has a @WorkflowTestTransformer "
\r
146 + " annotation but it is not declared static");
\r
149 ResponseTransformer transformer;
\r
152 transformer = (ResponseTransformer) field.get(null);
\r
153 } catch (IllegalAccessException e) {
\r
154 throw new RuntimeException(field.getDeclaringClass().getName()
\r
155 + "#" + field.getName() + " is not accessible", e);
\r
156 } catch (ClassCastException e) {
\r
157 throw new RuntimeException(field.getDeclaringClass().getName()
\r
158 + "#" + field.getName() + " is not a ResponseTransformer", e);
\r
161 if (transformer == null) {
\r
165 transformerList.add(transformer);
\r
168 ResponseTransformer[] transformerArray =
\r
169 transformerList.toArray(new ResponseTransformer[transformerList.size()]);
\r
171 wireMockRule = new WireMockRule(WireMockConfiguration.wireMockConfig()
\r
172 .port(28090).extensions(transformerArray));
\r
176 public void testSetup() throws Exception {
\r
177 CamundaDBSetup.configure();
\r
178 PropertyConfigurationSetup.init();
\r
182 * The current request ID. Normally set when an "invoke" method is called.
\r
184 protected volatile String msoRequestId = null;
\r
187 * The current service instance ID. Normally set when an "invoke" method
\r
190 protected volatile String msoServiceInstanceId = null;
\r
193 * Logs a test start method.
\r
195 protected void logStart() {
\r
196 StackTraceElement[] st = Thread.currentThread().getStackTrace();
\r
197 String method = st[2].getMethodName();
\r
198 System.out.println("STARTED TEST: " + method);
\r
202 * Logs a test end method.
\r
204 protected void logEnd() {
\r
205 StackTraceElement[] st = Thread.currentThread().getStackTrace();
\r
206 String method = st[2].getMethodName();
\r
207 System.out.println("ENDED TEST: " + method);
\r
211 * Invokes a subprocess.
\r
212 * @param processKey the process key
\r
213 * @param businessKey a unique key that will identify the process instance
\r
214 * @param injectedVariables variables to inject into the process
\r
216 protected void invokeSubProcess(String processKey, String businessKey, Map<String, Object> injectedVariables) {
\r
217 RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
\r
218 List<String> arguments = runtimeMxBean.getInputArguments();
\r
219 System.out.println("JVM args = " + arguments);
\r
221 msoRequestId = (String) injectedVariables.get("mso-request-id");
\r
222 String requestId = (String) injectedVariables.get("msoRequestId");
\r
224 if (msoRequestId == null && requestId == null) {
\r
225 String msg = "mso-request-id variable was not provided";
\r
226 System.out.println(msg);
\r
230 // Note: some scenarios don't have a service-instance-id, may be null
\r
231 msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id");
\r
233 RuntimeService runtimeService = processEngineRule.getRuntimeService();
\r
234 runtimeService.startProcessInstanceByKey(processKey, businessKey, injectedVariables);
\r
238 * Invokes an asynchronous process.
\r
239 * Errors are handled with junit assertions and will cause the test to fail.
\r
240 * @param processKey the process key
\r
241 * @param schemaVersion the API schema version, e.g. "v1"
\r
242 * @param businessKey a unique key that will identify the process instance
\r
243 * @param request the request
\r
244 * @return a TestAsyncResponse object associated with the test
\r
246 protected TestAsyncResponse invokeAsyncProcess(String processKey,
\r
247 String schemaVersion, String businessKey, String request) {
\r
248 return invokeAsyncProcess(processKey, schemaVersion, businessKey, request, null);
\r
252 * Invokes an asynchronous process.
\r
253 * Errors are handled with junit assertions and will cause the test to fail.
\r
254 * @param processKey the process key
\r
255 * @param schemaVersion the API schema version, e.g. "v1"
\r
256 * @param businessKey a unique key that will identify the process instance
\r
257 * @param request the request
\r
258 * @param injectedVariables optional variables to inject into the process
\r
259 * @return a TestAsyncResponse object associated with the test
\r
261 protected TestAsyncResponse invokeAsyncProcess(String processKey,
\r
262 String schemaVersion, String businessKey, String request,
\r
263 Map<String, Object> injectedVariables) {
\r
265 RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
\r
266 List<String> arguments = runtimeMxBean.getInputArguments();
\r
267 System.out.println("JVM args = " + arguments);
\r
269 Map<String, Object> variables = createVariables(schemaVersion, businessKey,
\r
270 request, injectedVariables, false);
\r
271 VariableMapImpl variableMapImpl = createVariableMapImpl(variables);
\r
273 System.out.println("Sending " + request + " to " + processKey + " process");
\r
274 WorkflowAsyncResource workflowResource = new WorkflowAsyncResource();
\r
275 workflowResource.setProcessEngineServices4junit(processEngineRule);
\r
277 TestAsyncResponse asyncResponse = new TestAsyncResponse();
\r
278 workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl);
\r
279 return asyncResponse;
\r
283 * Invokes an asynchronous process.
\r
284 * Errors are handled with junit assertions and will cause the test to fail.
\r
285 * @param processKey the process key
\r
286 * @param schemaVersion the API schema version, e.g. "v1"
\r
287 * @param businessKey a unique key that will identify the process instance
\r
288 * @param request the request
\r
289 * @param injectedVariables optional variables to inject into the process
\r
290 * @param serviceInstantiationModel indicates whether this method is being
\r
291 * invoked for a flow that is designed using the service instantiation model
\r
292 * @return a TestAsyncResponse object associated with the test
\r
294 protected TestAsyncResponse invokeAsyncProcess(String processKey,
\r
295 String schemaVersion, String businessKey, String request,
\r
296 Map<String, Object> injectedVariables, boolean serviceInstantiationModel) {
\r
298 RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
\r
299 List<String> arguments = runtimeMxBean.getInputArguments();
\r
300 System.out.println("JVM args = " + arguments);
\r
302 Map<String, Object> variables = createVariables(schemaVersion, businessKey,
\r
303 request, injectedVariables, serviceInstantiationModel);
\r
304 VariableMapImpl variableMapImpl = createVariableMapImpl(variables);
\r
306 System.out.println("Sending " + request + " to " + processKey + " process");
\r
307 WorkflowAsyncResource workflowResource = new WorkflowAsyncResource();
\r
308 workflowResource.setProcessEngineServices4junit(processEngineRule);
\r
310 TestAsyncResponse asyncResponse = new TestAsyncResponse();
\r
311 workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl);
\r
312 return asyncResponse;
\r
316 * Private helper method that creates a variable map for a request.
\r
317 * Errors are handled with junit assertions and will cause the test to fail.
\r
318 * @param schemaVersion the API schema version, e.g. "v1"
\r
319 * @param businessKey a unique key that will identify the process instance
\r
320 * @param request the request
\r
321 * @param injectedVariables optional variables to inject into the process
\r
322 * @param serviceInstantiationModel indicates whether this method is being
\r
323 * invoked for a flow that is designed using the service instantiation model
\r
324 * @return a variable map
\r
326 private Map<String, Object> createVariables(String schemaVersion,
\r
327 String businessKey, String request, Map<String, Object> injectedVariables,
\r
328 boolean serviceInstantiationModel) {
\r
330 Map<String, Object> variables = new HashMap<>();
\r
332 // These variables may be overridded by injected variables.
\r
333 variables.put("mso-service-request-timeout", "180");
\r
334 variables.put("isDebugLogEnabled", "true");
\r
336 // These variables may not be overridded by injected variables.
\r
337 String[] notAllowed = new String[] {
\r
338 "mso-schema-version",
\r
339 "mso-business-key",
\r
342 "mso-service-instance-id"
\r
345 if (injectedVariables != null) {
\r
346 for (String key : injectedVariables.keySet()) {
\r
347 for (String var : notAllowed) {
\r
348 if (var.equals(key)) {
\r
349 String msg = "Cannot specify " + var + " in injected variables";
\r
350 System.out.println(msg);
\r
355 variables.put(key, injectedVariables.get(key));
\r
359 variables.put("mso-schema-version", schemaVersion);
\r
360 variables.put("mso-business-key", businessKey);
\r
361 variables.put("bpmnRequest", request);
\r
363 if (serviceInstantiationModel) {
\r
366 * The request ID and the service instance ID are generated for flows
\r
367 * that follow the service instantiation model unless "requestId" and
\r
368 * "serviceInstanceId" are injected variables.
\r
372 msoRequestId = (String) injectedVariables.get("requestId");
\r
373 variables.put("mso-request-id", msoRequestId);
\r
374 msoServiceInstanceId = (String) injectedVariables.get("serviceInstanceId");
\r
375 variables.put("mso-service-instance-id", msoServiceInstanceId);
\r
377 catch(Exception e) {
\r
379 if (msoRequestId == null || msoRequestId.trim().equals("")) {
\r
380 System.out.println("No requestId element in injectedVariables");
\r
381 variables.put("mso-request-id", UUID.randomUUID().toString());
\r
383 if (msoServiceInstanceId == null || msoServiceInstanceId.trim().equals("")) {
\r
384 System.out.println("No seviceInstanceId element in injectedVariables");
\r
385 variables.put("mso-service-instance-id", UUID.randomUUID().toString());
\r
389 msoRequestId = getXMLTextElement(request, "request-id");
\r
391 if (msoRequestId == null) {
\r
392 //check in injected variables
\r
394 msoRequestId = (String) injectedVariables.get("requestId");
\r
396 catch(Exception e) {
\r
398 if (msoRequestId == null || msoRequestId.trim().equals("")) {
\r
399 String msg = "No request-id element in " + request;
\r
400 System.out.println(msg);
\r
405 variables.put("mso-request-id", msoRequestId);
\r
407 // Note: some request types don't have a service-instance-id
\r
408 msoServiceInstanceId = getXMLTextElement(request, "service-instance-id");
\r
410 if (msoServiceInstanceId != null) {
\r
411 variables.put("mso-service-instance-id", msoServiceInstanceId);
\r
419 * Private helper method that creates a camunda VariableMapImpl from a simple
\r
421 * @param variables the simple variable map
\r
422 * @return a VariableMap
\r
424 private VariableMapImpl createVariableMapImpl(Map<String, Object> variables) {
\r
425 Map<String, Object> wrappedVariables = new HashMap<>();
\r
427 for (String key : variables.keySet()) {
\r
428 Object value = variables.get(key);
\r
429 wrappedVariables.put(key, wrapVariableValue(value));
\r
432 VariableMapImpl variableMapImpl = new VariableMapImpl();
\r
433 variableMapImpl.put("variables", wrappedVariables);
\r
434 return variableMapImpl;
\r
438 * Private helper method that wraps a variable value for inclusion in a
\r
439 * camunda VariableMapImpl.
\r
440 * @param value the variable value
\r
441 * @return the wrapped variable
\r
443 private Map<String, Object> wrapVariableValue(Object value) {
\r
444 HashMap<String, Object> valueMap = new HashMap<>();
\r
445 valueMap.put("value", value);
\r
450 * Receives a response from an asynchronous process.
\r
451 * Errors are handled with junit assertions and will cause the test to fail.
\r
452 * @param businessKey the process business key
\r
453 * @param asyncResponse the TestAsyncResponse object associated with the test
\r
454 * @param timeout the timeout in milliseconds
\r
455 * @return the WorkflowResponse
\r
457 protected WorkflowResponse receiveResponse(String businessKey,
\r
458 TestAsyncResponse asyncResponse, long timeout) {
\r
459 System.out.println("Waiting " + timeout + "ms for process with business key " + businessKey
\r
460 + " to send a response");
\r
462 long now = System.currentTimeMillis() + timeout;
\r
463 long endTime = now + timeout;
\r
465 while (now <= endTime) {
\r
466 Response response = asyncResponse.getResponse();
\r
468 if (response != null) {
\r
469 System.out.println("Received a response from process with business key " + businessKey);
\r
471 Object entity = response.getEntity();
\r
473 if (!(entity instanceof WorkflowResponse)) {
\r
474 String msg = "Response entity is " +
\r
475 (entity == null ? "null" : entity.getClass().getName()) +
\r
476 ", expected WorkflowResponse";
\r
477 System.out.println(msg);
\r
479 return null; // unreachable
\r
482 return (WorkflowResponse) entity;
\r
487 } catch (InterruptedException e) {
\r
488 String msg = "Interrupted waiting for a response from process with business key " +
\r
490 System.out.println(msg);
\r
492 return null; // unreachable
\r
495 now = System.currentTimeMillis();
\r
498 String msg = "No response received from process with business key " + businessKey +
\r
499 " within " + timeout + "ms";
\r
500 System.out.println(msg);
\r
501 fail("Process with business key " + businessKey + " did not end within 10000ms");
\r
502 return null; // unreachable
\r
506 * Runs a program to inject SDNC callback data into the test environment.
\r
507 * A program is essentially just a list of keys that identify callback data
\r
508 * to be injected, in sequence. An example program:
\r
510 * reserve, assign, delete:ERR
\r
512 * Errors are handled with junit assertions and will cause the test to fail.
\r
513 * @param callbacks an object containing callback data for the program
\r
514 * @param program the program to execute
\r
516 protected void injectSDNCRestCallbacks(CallbackSet callbacks, String program) {
\r
518 String[] cmds = program.replaceAll("\\s+", "").split(",");
\r
520 for (String cmd : cmds) {
\r
521 String action = cmd;
\r
522 String modifier = "STD";
\r
524 if (cmd.contains(":")) {
\r
525 String[] parts = cmd.split(":");
\r
527 modifier = parts[1];
\r
530 String content = null;
\r
531 String contentType = null;
\r
533 if ("STD".equals(modifier)) {
\r
534 CallbackData callbackData = callbacks.get(action);
\r
536 if (callbackData == null) {
\r
537 String msg = "No callback defined for '" + action + "' SDNC request";
\r
538 System.out.println(msg);
\r
542 content = callbackData.getContent();
\r
543 contentType = callbackData.getContentType();
\r
544 } else if ("ERR".equals(modifier)) {
\r
545 content = "{\"SDNCServiceError\":{\"sdncRequestId\":\"((REQUEST-ID))\",\"responseCode\":\"500\",\"responseMessage\":\"SIMULATED ERROR FROM SDNC ADAPTER\",\"ackFinalIndicator\":\"Y\"}}";
\r
546 contentType = JSON;
\r
548 String msg = "Invalid SDNC program modifier: '" + modifier + "'";
\r
549 System.out.println(msg);
\r
553 if (contentType == null) {
\r
554 // Default for backward compatibility with existing tests.
\r
555 contentType = JSON;
\r
558 if (!injectSDNCRestCallback(contentType, content, 10000)) {
\r
559 fail("Failed to inject SDNC '" + action + "' callback");
\r
563 Thread.sleep(1000);
\r
564 } catch (InterruptedException e) {
\r
565 fail("Interrupted after injection of SDNC '" + action + "' callback");
\r
571 * Runs a program to inject SDNC events into the test environment.
\r
572 * A program is essentially just a list of keys that identify event data
\r
573 * to be injected, in sequence. An example program:
\r
577 * NOTE: Each callback must have a message type associated with it, e.g.
\r
579 * Errors are handled with junit assertions and will cause the test to fail.
\r
580 * @param callbacks an object containing event data for the program
\r
581 * @param program the program to execute
\r
583 protected void injectSDNCEvents(CallbackSet callbacks, String program) {
\r
584 injectWorkflowMessages(callbacks, program);
\r
588 * Runs a program to inject SDNC callback data into the test environment.
\r
589 * A program is essentially just a list of keys that identify callback data
\r
590 * to be injected, in sequence. An example program:
\r
592 * reserve, assign, delete:ERR
\r
594 * Errors are handled with junit assertions and will cause the test to fail.
\r
595 * @param callbacks an object containing callback data for the program
\r
596 * @param program the program to execute
\r
598 protected void injectSDNCCallbacks(CallbackSet callbacks, String program) {
\r
600 String[] cmds = program.replaceAll("\\s+", "").split(",");
\r
602 for (String cmd : cmds) {
\r
603 String action = cmd;
\r
604 String modifier = "STD";
\r
606 if (cmd.contains(":")) {
\r
607 String[] parts = cmd.split(":");
\r
609 modifier = parts[1];
\r
612 String content = null;
\r
613 int respCode = 200;
\r
614 String respMsg = "OK";
\r
616 if ("STD".equals(modifier)) {
\r
617 CallbackData callbackData = callbacks.get(action);
\r
619 if (callbackData == null) {
\r
620 String msg = "No callback defined for '" + action + "' SDNC request";
\r
621 System.out.println(msg);
\r
625 content = callbackData.getContent();
\r
628 } else if ("CREATED".equals(modifier)) {
\r
629 CallbackData callbackData = callbacks.get(action);
\r
631 if (callbackData == null) {
\r
632 String msg = "No callback defined for '" + action + "' SDNC request";
\r
633 System.out.println(msg);
\r
637 content = callbackData.getContent();
\r
639 respMsg = "Created";
\r
640 } else if ("ERR".equals(modifier)) {
\r
641 content = "<svc-request-id>((REQUEST-ID))</svc-request-id><response-code>500</response-code><response-message>SIMULATED ERROR FROM SDNC ADAPTER</response-message>";
\r
643 respMsg = "SERVER ERROR";
\r
645 String msg = "Invalid SDNC program modifier: '" + modifier + "'";
\r
646 System.out.println(msg);
\r
650 if (!injectSDNCCallback(respCode, respMsg, content, 10000)) {
\r
651 fail("Failed to inject SDNC '" + action + "' callback");
\r
655 Thread.sleep(1000);
\r
656 } catch (InterruptedException e) {
\r
657 fail("Interrupted after injection of SDNC '" + action + "' callback");
\r
663 * Runs a program to inject VNF adapter REST callback data into the test environment.
\r
664 * A program is essentially just a list of keys that identify callback data
\r
665 * to be injected, in sequence. An example program:
\r
669 * Errors are handled with junit assertions and will cause the test to fail.
\r
670 * @param callbacks an object containing callback data for the program
\r
671 * @param program the program to execute
\r
673 protected void injectVNFRestCallbacks(CallbackSet callbacks, String program) {
\r
675 String[] cmds = program.replaceAll("\\s+", "").split(",");
\r
677 for (String cmd : cmds) {
\r
678 String action = cmd;
\r
679 String modifier = "STD";
\r
681 if (cmd.contains(":")) {
\r
682 String[] parts = cmd.split(":");
\r
684 modifier = parts[1];
\r
687 String content = null;
\r
688 String contentType = null;
\r
690 if ("STD".equals(modifier)) {
\r
691 CallbackData callbackData = callbacks.get(action);
\r
693 if (callbackData == null) {
\r
694 String msg = "No callback defined for '" + action + "' VNF REST request";
\r
695 System.out.println(msg);
\r
699 content = callbackData.getContent();
\r
700 contentType = callbackData.getContentType();
\r
701 } else if ("ERR".equals(modifier)) {
\r
702 content = "SIMULATED ERROR FROM VNF ADAPTER";
\r
703 contentType = "text/plain";
\r
705 String msg = "Invalid VNF REST program modifier: '" + modifier + "'";
\r
706 System.out.println(msg);
\r
710 if (contentType == null) {
\r
711 // Default for backward compatibility with existing tests.
\r
715 if (!injectVnfAdapterRestCallback(contentType, content, 10000)) {
\r
716 fail("Failed to inject VNF REST '" + action + "' callback");
\r
720 Thread.sleep(1000);
\r
721 } catch (InterruptedException e) {
\r
722 fail("Interrupted after injection of VNF REST '" + action + "' callback");
\r
728 * Runs a program to inject VNF callback data into the test environment.
\r
729 * A program is essentially just a list of keys that identify callback data
\r
730 * to be injected, in sequence. An example program:
\r
732 * createVnf, deleteVnf
\r
734 * Errors are handled with junit assertions and will cause the test to fail.
\r
735 * @param callbacks an object containing callback data for the program
\r
736 * @param program the program to execute
\r
738 protected void injectVNFCallbacks(CallbackSet callbacks, String program) {
\r
740 String[] cmds = program.replaceAll("\\s+", "").split(",");
\r
742 for (String cmd : cmds) {
\r
743 String action = cmd;
\r
744 String modifier = "STD";
\r
746 if (cmd.contains(":")) {
\r
747 String[] parts = cmd.split(":");
\r
749 modifier = parts[1];
\r
752 String content = null;
\r
754 if ("STD".equals(modifier)) {
\r
755 CallbackData callbackData = callbacks.get(action);
\r
757 if (callbackData == null) {
\r
758 String msg = "No callback defined for '" + action + "' VNF request";
\r
759 System.out.println(msg);
\r
763 content = callbackData.getContent();
\r
764 } else if ("ERR".equals(modifier)) {
\r
765 String msg = "Currently unsupported VNF program modifier: '" + modifier + "'";
\r
766 System.out.println(msg);
\r
769 String msg = "Invalid VNF program modifier: '" + modifier + "'";
\r
770 System.out.println(msg);
\r
774 boolean injected = false;
\r
776 if (content.contains("createVnfNotification")) {
\r
777 injected = injectCreateVNFCallback(content, 10000);
\r
778 } else if (content.contains("deleteVnfNotification")) {
\r
779 injected = injectDeleteVNFCallback(content, 10000);
\r
780 } else if (content.contains("updateVnfNotification")) {
\r
781 injected = injectUpdateVNFCallback(content, 10000);
\r
785 String msg = "Failed to inject VNF '" + action + "' callback";
\r
786 System.out.println(msg);
\r
791 Thread.sleep(1000);
\r
792 } catch (InterruptedException e) {
\r
793 fail("Interrupted after injection of VNF '" + action + "' callback");
\r
799 * Waits for the number of running processes with the specified process
\r
800 * definition key to equal a particular count.
\r
801 * @param processKey the process definition key
\r
802 * @param count the desired count
\r
803 * @param timeout the timeout in milliseconds
\r
805 protected void waitForRunningProcessCount(String processKey, int count, long timeout) {
\r
806 System.out.println("Waiting " + timeout + "ms for there to be " + count + " "
\r
807 + processKey + " instances");
\r
809 long now = System.currentTimeMillis() + timeout;
\r
810 long endTime = now + timeout;
\r
813 while (now <= endTime) {
\r
814 int actual = processEngineRule.getRuntimeService()
\r
815 .createProcessInstanceQuery()
\r
816 .processDefinitionKey(processKey)
\r
819 if (actual != last) {
\r
820 System.out.println("There are now " + actual + " "
\r
821 + processKey + " instances");
\r
825 if (actual == count) {
\r
831 } catch (InterruptedException e) {
\r
832 String msg = "Interrupted waiting for there to be " + count + " "
\r
833 + processKey + " instances";
\r
834 System.out.println(msg);
\r
838 now = System.currentTimeMillis();
\r
841 String msg = "Timed out waiting for there to be " + count + " "
\r
842 + processKey + " instances";
\r
843 System.out.println(msg);
\r
848 * Waits for the specified process variable to be set.
\r
849 * @param processKey the process definition key
\r
850 * @param variable the variable name
\r
851 * @param timeout the timeout in milliseconds
\r
852 * @return the variable value, or null if it cannot be obtained
\r
853 * in the specified time
\r
855 protected Object getProcessVariable(String processKey, String variable,
\r
858 System.out.println("Waiting " + timeout + "ms for "
\r
859 + processKey + "." + variable + " to be set");
\r
861 long now = System.currentTimeMillis() + timeout;
\r
862 long endTime = now + timeout;
\r
864 ProcessInstance processInstance = null;
\r
865 Object value = null;
\r
867 while (value == null) {
\r
868 if (now > endTime) {
\r
869 if (processInstance == null) {
\r
870 System.out.println("Timed out waiting for "
\r
871 + processKey + " to start");
\r
873 System.out.println("Timed out waiting for "
\r
874 + processKey + "[" + processInstance.getId()
\r
875 + "]." + variable + " to be set");
\r
881 if (processInstance == null) {
\r
882 processInstance = processEngineRule.getRuntimeService()
\r
883 .createProcessInstanceQuery()
\r
884 .processDefinitionKey(processKey)
\r
888 if (processInstance != null) {
\r
889 value = processEngineRule.getRuntimeService()
\r
890 .getVariable(processInstance.getId(), variable);
\r
895 } catch (InterruptedException e) {
\r
896 System.out.println("Interrupted waiting for "
\r
897 + processKey + "." + variable + " to be set");
\r
901 now = System.currentTimeMillis();
\r
904 System.out.println(processKey + "["
\r
905 + processInstance.getId() + "]." + variable + "="
\r
912 * Injects a single SDNC adapter callback request. The specified callback data
\r
913 * may contain the placeholder string ((REQUEST-ID)) which is replaced with
\r
914 * the actual SDNC request ID. Note: this is not the requestId in the original
\r
916 * @param contentType the HTTP content type for the callback
\r
917 * @param content the content of the callback
\r
918 * @param timeout the timeout in milliseconds
\r
919 * @return true if the callback could be injected, false otherwise
\r
921 protected boolean injectSDNCRestCallback(String contentType, String content, long timeout) {
\r
922 String sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV1",
\r
923 "SDNCAResponse_CORRELATOR", timeout);
\r
925 if (sdncRequestId == null) {
\r
929 content = content.replace("((REQUEST-ID))", sdncRequestId);
\r
930 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
931 content = content.replace("{{REQUEST-ID}}", sdncRequestId);
\r
933 System.out.println("Injecting SDNC adapter callback");
\r
934 WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource();
\r
935 workflowMessageResource.setProcessEngineServices4junit(processEngineRule);
\r
936 Response response = workflowMessageResource.deliver(contentType, "SDNCAResponse", sdncRequestId, content);
\r
937 System.out.println("Workflow response to SDNC adapter callback: " + response);
\r
942 * Injects a single SDNC adapter callback request. The specified callback data
\r
943 * may contain the placeholder string ((REQUEST-ID)) which is replaced with
\r
944 * the actual SDNC request ID. Note: this is not the requestId in the original
\r
946 * @param content the content of the callback
\r
947 * @param respCode the response code (normally 200)
\r
948 * @param respMsg the response message (normally "OK")
\r
949 * @param timeout the timeout in milliseconds
\r
950 * @return true if the callback could be injected, false otherwise
\r
952 protected boolean injectSDNCCallback(int respCode, String respMsg,
\r
953 String content, long timeout) {
\r
955 String sdncRequestId = (String) getProcessVariable("sdncAdapter",
\r
956 "SDNCA_requestId", timeout);
\r
958 if (sdncRequestId == null) {
\r
962 content = content.replace("((REQUEST-ID))", sdncRequestId);
\r
963 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
964 content = content.replace("{{REQUEST-ID}}", sdncRequestId);
\r
966 System.out.println("Injecting SDNC adapter callback");
\r
967 CallbackHeader callbackHeader = new CallbackHeader();
\r
968 callbackHeader.setRequestId(sdncRequestId);
\r
969 callbackHeader.setResponseCode(String.valueOf(respCode));
\r
970 callbackHeader.setResponseMessage(respMsg);
\r
971 SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest();
\r
972 sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader);
\r
973 sdncAdapterCallbackRequest.setRequestData(content);
\r
974 SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl();
\r
975 callbackService.setProcessEngineServices4junit(processEngineRule);
\r
976 SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest);
\r
977 System.out.println("Workflow response to SDNC adapter callback: " + sdncAdapterResponse);
\r
983 * Injects a single VNF adapter callback request. The specified callback data
\r
984 * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
\r
985 * the actual message ID. Note: this is not the requestId in the original
\r
987 * @param contentType the HTTP content type for the callback
\r
988 * @param content the content of the callback
\r
989 * @param timeout the timeout in milliseconds
\r
990 * @return true if the callback could be injected, false otherwise
\r
992 protected boolean injectVnfAdapterRestCallback(String contentType, String content, long timeout) {
\r
993 String messageId = (String) getProcessVariable("vnfAdapterRestV1",
\r
994 "VNFAResponse_CORRELATOR", timeout);
\r
996 if (messageId == null) {
\r
1000 content = content.replace("((MESSAGE-ID))", messageId);
\r
1001 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
1002 content = content.replace("{{MESSAGE-ID}}", messageId);
\r
1004 System.out.println("Injecting VNF adapter callback");
\r
1005 WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource();
\r
1006 workflowMessageResource.setProcessEngineServices4junit(processEngineRule);
\r
1007 Response response = workflowMessageResource.deliver(contentType, "VNFAResponse", messageId, content);
\r
1008 System.out.println("Workflow response to VNF adapter callback: " + response);
\r
1013 * Injects a Create VNF adapter callback request. The specified callback data
\r
1014 * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
\r
1015 * the actual message ID. It may also contain the placeholder string
\r
1016 * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
\r
1017 * @param content the content of the callback
\r
1018 * @param timeout the timeout in milliseconds
\r
1019 * @return true if the callback could be injected, false otherwise
\r
1020 * @throws JAXBException if the content does not adhere to the schema
\r
1022 protected boolean injectCreateVNFCallback(String content, long timeout) {
\r
1024 String messageId = (String) getProcessVariable("vnfAdapterCreateV1",
\r
1025 "VNFC_messageId", timeout);
\r
1027 if (messageId == null) {
\r
1031 content = content.replace("((MESSAGE-ID))", messageId);
\r
1032 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
1033 content = content.replace("{{MESSAGE-ID}}", messageId);
\r
1035 if(content.contains("((REQUEST-ID))")){
\r
1036 content = content.replace("((REQUEST-ID))", msoRequestId);
\r
1037 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
1038 content = content.replace("{{REQUEST-ID}}", msoRequestId);
\r
1041 System.out.println("Injecting VNF adapter callback");
\r
1043 // Is it possible to unmarshal this with JAXB? I couldn't.
\r
1045 CreateVnfNotification createVnfNotification = new CreateVnfNotification();
\r
1046 XPathTool xpathTool = new VnfNotifyXPathTool();
\r
1047 xpathTool.setXML(content);
\r
1050 String completed = xpathTool.evaluate(
\r
1051 "/tns:createVnfNotification/tns:completed/text()");
\r
1052 createVnfNotification.setCompleted("true".equals(completed));
\r
1054 String vnfId = xpathTool.evaluate(
\r
1055 "/tns:createVnfNotification/tns:vnfId/text()");
\r
1056 createVnfNotification.setVnfId(vnfId);
\r
1058 NodeList entries = (NodeList) xpathTool.evaluate(
\r
1059 "/tns:createVnfNotification/tns:outputs/tns:entry",
\r
1060 XPathConstants.NODESET);
\r
1062 CreateVnfNotificationOutputs outputs = new CreateVnfNotificationOutputs();
\r
1064 for (int i = 0; i < entries.getLength(); i++) {
\r
1065 Node node = entries.item(i);
\r
1067 if (node.getNodeType() == Node.ELEMENT_NODE) {
\r
1068 Element entry = (Element) node;
\r
1069 String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent();
\r
1070 String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent();
\r
1071 outputs.add(key, value);
\r
1075 createVnfNotification.setOutputs(outputs);
\r
1077 VnfRollback rollback = new VnfRollback();
\r
1079 String cloudSiteId = xpathTool.evaluate(
\r
1080 "/tns:createVnfNotification/tns:rollback/tns:cloudSiteId/text()");
\r
1081 rollback.setCloudSiteId(cloudSiteId);
\r
1083 String requestId = xpathTool.evaluate(
\r
1084 "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()");
\r
1085 String serviceInstanceId = xpathTool.evaluate(
\r
1086 "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()");
\r
1088 if (requestId != null || serviceInstanceId != null) {
\r
1089 MsoRequest msoRequest = new MsoRequest();
\r
1090 msoRequest.setRequestId(requestId);
\r
1091 msoRequest.setServiceInstanceId(serviceInstanceId);
\r
1092 rollback.setMsoRequest(msoRequest);
\r
1095 String tenantCreated = xpathTool.evaluate(
\r
1096 "/tns:createVnfNotification/tns:rollback/tns:tenantCreated/text()");
\r
1097 rollback.setTenantCreated("true".equals(tenantCreated));
\r
1099 String tenantId = xpathTool.evaluate(
\r
1100 "/tns:createVnfNotification/tns:rollback/tns:tenantId/text()");
\r
1101 rollback.setTenantId(tenantId);
\r
1103 String vnfCreated = xpathTool.evaluate(
\r
1104 "/tns:createVnfNotification/tns:rollback/tns:vnfCreated/text()");
\r
1105 rollback.setVnfCreated("true".equals(vnfCreated));
\r
1107 String rollbackVnfId = xpathTool.evaluate(
\r
1108 "/tns:createVnfNotification/tns:rollback/tns:vnfId/text()");
\r
1109 rollback.setVnfId(rollbackVnfId);
\r
1111 createVnfNotification.setRollback(rollback);
\r
1113 } catch (Exception e) {
\r
1114 System.out.println("Failed to unmarshal VNF callback content:");
\r
1115 System.out.println(content);
\r
1119 VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
\r
1120 notifyService.setProcessEngineServices4junit(processEngineRule);
\r
1122 notifyService.createVnfNotification(
\r
1124 createVnfNotification.isCompleted(),
\r
1125 createVnfNotification.getException(),
\r
1126 createVnfNotification.getErrorMessage(),
\r
1127 createVnfNotification.getVnfId(),
\r
1128 createVnfNotification.getOutputs(),
\r
1129 createVnfNotification.getRollback());
\r
1135 * Injects a Delete VNF adapter callback request. The specified callback data
\r
1136 * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
\r
1137 * the actual message ID. It may also contain the placeholder string
\r
1138 * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
\r
1139 * @param content the content of the callback
\r
1140 * @param timeout the timeout in milliseconds
\r
1141 * @return true if the callback could be injected, false otherwise
\r
1142 * @throws JAXBException if the content does not adhere to the schema
\r
1144 protected boolean injectDeleteVNFCallback(String content, long timeout) {
\r
1146 String messageId = (String) getProcessVariable("vnfAdapterDeleteV1",
\r
1147 "VNFDEL_uuid", timeout);
\r
1149 if (messageId == null) {
\r
1153 content = content.replace("((MESSAGE-ID))", messageId);
\r
1154 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
1155 content = content.replace("{{MESSAGE-ID}}", messageId);
\r
1157 System.out.println("Injecting VNF adapter delete callback");
\r
1159 // Is it possible to unmarshal this with JAXB? I couldn't.
\r
1161 DeleteVnfNotification deleteVnfNotification = new DeleteVnfNotification();
\r
1162 XPathTool xpathTool = new VnfNotifyXPathTool();
\r
1163 xpathTool.setXML(content);
\r
1166 String completed = xpathTool.evaluate(
\r
1167 "/tns:deleteVnfNotification/tns:completed/text()");
\r
1168 deleteVnfNotification.setCompleted("true".equals(completed));
\r
1169 // if notification failure, set the exception and error message
\r
1170 if (deleteVnfNotification.isCompleted() == false) {
\r
1171 deleteVnfNotification.setException(MsoExceptionCategory.INTERNAL);
\r
1172 deleteVnfNotification.setErrorMessage(xpathTool.evaluate(
\r
1173 "/tns:deleteVnfNotification/tns:errorMessage/text()")) ;
\r
1176 } catch (Exception e) {
\r
1177 System.out.println("Failed to unmarshal VNF Delete callback content:");
\r
1178 System.out.println(content);
\r
1182 VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
\r
1183 notifyService.setProcessEngineServices4junit(processEngineRule);
\r
1185 notifyService.deleteVnfNotification(
\r
1187 deleteVnfNotification.isCompleted(),
\r
1188 deleteVnfNotification.getException(),
\r
1189 deleteVnfNotification.getErrorMessage());
\r
1195 * Injects a Update VNF adapter callback request. The specified callback data
\r
1196 * may contain the placeholder string ((MESSAGE-ID)) which is replaced with
\r
1197 * the actual message ID. It may also contain the placeholder string
\r
1198 * ((REQUEST-ID)) which is replaced request ID of the original MSO request.
\r
1199 * @param content the content of the callback
\r
1200 * @param timeout the timeout in milliseconds
\r
1201 * @return true if the callback could be injected, false otherwise
\r
1202 * @throws JAXBException if the content does not adhere to the schema
\r
1204 protected boolean injectUpdateVNFCallback(String content, long timeout) {
\r
1206 String messageId = (String) getProcessVariable("vnfAdapterUpdate",
\r
1207 "VNFU_messageId", timeout);
\r
1209 if (messageId == null) {
\r
1213 content = content.replace("((MESSAGE-ID))", messageId);
\r
1214 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
1215 content = content.replace("{{MESSAGE-ID}}", messageId);
\r
1217 content = content.replace("((REQUEST-ID))", msoRequestId);
\r
1218 // Deprecated usage. All test code should switch to the (( ... )) syntax.
\r
1219 content = content.replace("{{REQUEST-ID}}", msoRequestId);
\r
1221 System.out.println("Injecting VNF adapter callback");
\r
1223 // Is it possible to unmarshal this with JAXB? I couldn't.
\r
1225 UpdateVnfNotification updateVnfNotification = new UpdateVnfNotification();
\r
1226 XPathTool xpathTool = new VnfNotifyXPathTool();
\r
1227 xpathTool.setXML(content);
\r
1230 String completed = xpathTool.evaluate(
\r
1231 "/tns:updateVnfNotification/tns:completed/text()");
\r
1232 updateVnfNotification.setCompleted("true".equals(completed));
\r
1234 NodeList entries = (NodeList) xpathTool.evaluate(
\r
1235 "/tns:updateVnfNotification/tns:outputs/tns:entry",
\r
1236 XPathConstants.NODESET);
\r
1238 UpdateVnfNotificationOutputs outputs = new UpdateVnfNotificationOutputs();
\r
1240 for (int i = 0; i < entries.getLength(); i++) {
\r
1241 Node node = entries.item(i);
\r
1243 if (node.getNodeType() == Node.ELEMENT_NODE) {
\r
1244 Element entry = (Element) node;
\r
1245 String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent();
\r
1246 String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent();
\r
1247 outputs.add(key, value);
\r
1251 updateVnfNotification.setOutputs(outputs);
\r
1253 VnfRollback rollback = new VnfRollback();
\r
1255 String cloudSiteId = xpathTool.evaluate(
\r
1256 "/tns:updateVnfNotification/tns:rollback/tns:cloudSiteId/text()");
\r
1257 rollback.setCloudSiteId(cloudSiteId);
\r
1259 String requestId = xpathTool.evaluate(
\r
1260 "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()");
\r
1261 String serviceInstanceId = xpathTool.evaluate(
\r
1262 "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()");
\r
1264 if (requestId != null || serviceInstanceId != null) {
\r
1265 MsoRequest msoRequest = new MsoRequest();
\r
1266 msoRequest.setRequestId(requestId);
\r
1267 msoRequest.setServiceInstanceId(serviceInstanceId);
\r
1268 rollback.setMsoRequest(msoRequest);
\r
1271 String tenantCreated = xpathTool.evaluate(
\r
1272 "/tns:updateVnfNotification/tns:rollback/tns:tenantCreated/text()");
\r
1273 rollback.setTenantCreated("true".equals(tenantCreated));
\r
1275 String tenantId = xpathTool.evaluate(
\r
1276 "/tns:updateVnfNotification/tns:rollback/tns:tenantId/text()");
\r
1277 rollback.setTenantId(tenantId);
\r
1279 String vnfCreated = xpathTool.evaluate(
\r
1280 "/tns:updateVnfNotification/tns:rollback/tns:vnfCreated/text()");
\r
1281 rollback.setVnfCreated("true".equals(vnfCreated));
\r
1283 String rollbackVnfId = xpathTool.evaluate(
\r
1284 "/tns:updateVnfNotification/tns:rollback/tns:vnfId/text()");
\r
1285 rollback.setVnfId(rollbackVnfId);
\r
1287 updateVnfNotification.setRollback(rollback);
\r
1289 } catch (Exception e) {
\r
1290 System.out.println("Failed to unmarshal VNF callback content:");
\r
1291 System.out.println(content);
\r
1295 VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl();
\r
1296 notifyService.setProcessEngineServices4junit(processEngineRule);
\r
1298 notifyService.updateVnfNotification(
\r
1300 updateVnfNotification.isCompleted(),
\r
1301 updateVnfNotification.getException(),
\r
1302 updateVnfNotification.getErrorMessage(),
\r
1303 updateVnfNotification.getOutputs(),
\r
1304 updateVnfNotification.getRollback());
\r
1310 * Runs a program to inject workflow messages into the test environment.
\r
1311 * A program is essentially just a list of keys that identify event data
\r
1312 * to be injected, in sequence. An example program:
\r
1316 * Errors are handled with junit assertions and will cause the test to fail.
\r
1317 * NOTE: Each callback must have a workflow message type associated with it.
\r
1318 * @param callbacks an object containing event data for the program
\r
1319 * @param program the program to execute
\r
1321 protected void injectWorkflowMessages(CallbackSet callbacks, String program) {
\r
1323 String[] cmds = program.replaceAll("\\s+", "").split(",");
\r
1325 for (String cmd : cmds) {
\r
1326 String action = cmd;
\r
1327 String modifier = "STD";
\r
1329 if (cmd.contains(":")) {
\r
1330 String[] parts = cmd.split(":");
\r
1331 action = parts[0];
\r
1332 modifier = parts[1];
\r
1335 String messageType = null;
\r
1336 String content = null;
\r
1337 String contentType = null;
\r
1339 if ("STD".equals(modifier)) {
\r
1340 CallbackData callbackData = callbacks.get(action);
\r
1342 if (callbackData == null) {
\r
1343 String msg = "No '" + action + "' workflow message callback is defined";
\r
1344 System.out.println(msg);
\r
1348 messageType = callbackData.getMessageType();
\r
1350 if (messageType == null || messageType.trim().equals("")) {
\r
1351 String msg = "No workflow message type is defined in the '" + action + "' callback";
\r
1352 System.out.println(msg);
\r
1356 content = callbackData.getContent();
\r
1357 contentType = callbackData.getContentType();
\r
1359 String msg = "Invalid workflow message program modifier: '" + modifier + "'";
\r
1360 System.out.println(msg);
\r
1364 if (!injectWorkflowMessage(contentType, messageType, content, 10000)) {
\r
1365 fail("Failed to inject '" + action + "' workflow message");
\r
1369 Thread.sleep(1000);
\r
1370 } catch (InterruptedException e) {
\r
1371 fail("Interrupted after injection of '" + action + "' workflow message");
\r
1377 * Injects a workflow message. The specified callback data may contain the
\r
1378 * placeholder string ((CORRELATOR)) which is replaced with the actual
\r
1379 * correlator value.
\r
1380 * @param contentType the HTTP contentType for the message (possibly null)
\r
1381 * @param messageType the message type
\r
1382 * @param content the message content (possibly null)
\r
1383 * @param timeout the timeout in milliseconds
\r
1384 * @return true if the message could be injected, false otherwise
\r
1386 protected boolean injectWorkflowMessage(String contentType, String messageType, String content, long timeout) {
\r
1387 String correlator = (String) getProcessVariable("ReceiveWorkflowMessage",
\r
1388 messageType + "_CORRELATOR", timeout);
\r
1390 if (correlator == null) {
\r
1394 if (content != null) {
\r
1395 content = content.replace("((CORRELATOR))", correlator);
\r
1398 System.out.println("Injecting " + messageType + " message");
\r
1399 WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource();
\r
1400 workflowMessageResource.setProcessEngineServices4junit(processEngineRule);
\r
1401 Response response = workflowMessageResource.deliver(contentType, messageType, correlator, content);
\r
1402 System.out.println("Workflow response to " + messageType + " message: " + response);
\r
1407 * Runs a program to inject sniro workflow messages into the test environment.
\r
1408 * A program is essentially just a list of keys that identify event data
\r
1409 * to be injected, in sequence. For more details, see
\r
1410 * injectSNIROCallbacks(String contentType, String messageType, String content, long timeout)
\r
1412 * Errors are handled with junit assertions and will cause the test to fail.
\r
1413 * NOTE: Each callback must have a workflow message type associated with it.
\r
1415 * @param callbacks an object containing event data for the program
\r
1416 * @param program the program to execute
\r
1418 protected void injectSNIROCallbacks(CallbackSet callbacks, String program) {
\r
1420 String[] cmds = program.replaceAll("\\s+", "").split(",");
\r
1422 for (String cmd : cmds) {
\r
1423 String action = cmd;
\r
1424 String modifier = "STD";
\r
1426 if (cmd.contains(":")) {
\r
1427 String[] parts = cmd.split(":");
\r
1428 action = parts[0];
\r
1429 modifier = parts[1];
\r
1432 String messageType = null;
\r
1433 String content = null;
\r
1434 String contentType = null;
\r
1436 if ("STD".equals(modifier)) {
\r
1437 CallbackData callbackData = callbacks.get(action);
\r
1439 if (callbackData == null) {
\r
1440 String msg = "No '" + action + "' workflow message callback is defined";
\r
1441 System.out.println(msg);
\r
1445 messageType = callbackData.getMessageType();
\r
1447 if (messageType == null || messageType.trim().equals("")) {
\r
1448 String msg = "No workflow message type is defined in the '" + action + "' callback";
\r
1449 System.out.println(msg);
\r
1453 content = callbackData.getContent();
\r
1454 contentType = callbackData.getContentType();
\r
1456 String msg = "Invalid workflow message program modifier: '" + modifier + "'";
\r
1457 System.out.println(msg);
\r
1461 if (!injectSNIROCallbacks(contentType, messageType, content, 10000)) {
\r
1462 fail("Failed to inject '" + action + "' workflow message");
\r
1466 Thread.sleep(1000);
\r
1467 } catch (InterruptedException e) {
\r
1468 fail("Interrupted after injection of '" + action + "' workflow message");
\r
1474 * Injects a sniro workflow message. The specified callback response may
\r
1475 * contain the placeholder strings ((CORRELATOR)) and ((SERVICE_RESOURCE_ID))
\r
1476 * The ((CORRELATOR)) is replaced with the actual correlator value from the
\r
1477 * request. The ((SERVICE_RESOURCE_ID)) is replaced with the actual serviceResourceId
\r
1478 * value from the sniro request. Currently this only works with sniro request
\r
1479 * that contain only 1 resource.
\r
1481 * @param contentType the HTTP contentType for the message (possibly null)
\r
1482 * @param messageType the message type
\r
1483 * @param content the message content (possibly null)
\r
1484 * @param timeout the timeout in milliseconds
\r
1485 * @return true if the message could be injected, false otherwise
\r
1487 protected boolean injectSNIROCallbacks(String contentType, String messageType, String content, long timeout) {
\r
1488 String correlator = (String) getProcessVariable("ReceiveWorkflowMessage",
\r
1489 messageType + "_CORRELATOR", timeout);
\r
1491 if (correlator == null) {
\r
1494 if (content != null) {
\r
1495 content = content.replace("((CORRELATOR))", correlator);
\r
1496 if(messageType.equalsIgnoreCase("SNIROResponse")){
\r
1497 //TODO figure out a solution for when there is more than 1 resource being homed (i.e. more than 1 reason in the placement list)
\r
1498 ServiceDecomposition decomp = (ServiceDecomposition) getProcessVariable("Homing", "serviceDecomposition", timeout);
\r
1499 List<Resource> resourceList = decomp.getServiceResources();
\r
1500 if(resourceList.size() == 1){
\r
1501 String resourceId = "";
\r
1502 for(Resource resource:resourceList){
\r
1503 resourceId = resource.getResourceId();
\r
1505 String homingList = getJsonValue(content, "solutionInfo.placement");
\r
1506 JSONArray placementArr = new JSONArray(homingList);
\r
1507 if(placementArr.length() == 1){
\r
1508 content = content.replace("((SERVICE_RESOURCE_ID))", resourceId);
\r
1510 String licenseInfoList = getJsonValue(content, "solutionInfo.licenseInfo");
\r
1511 JSONArray licenseArr = new JSONArray(licenseInfoList);
\r
1512 if(licenseArr.length() == 1){
\r
1513 content = content.replace("((SERVICE_RESOURCE_ID))", resourceId);
\r
1518 System.out.println("Injecting " + messageType + " message");
\r
1519 WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource();
\r
1520 workflowMessageResource.setProcessEngineServices4junit(processEngineRule);
\r
1521 Response response = workflowMessageResource.deliver(contentType, messageType, correlator, content);
\r
1522 System.out.println("Workflow response to " + messageType + " message: " + response);
\r
1528 * Wait for the process to end.
\r
1529 * @param businessKey the process business key
\r
1530 * @param timeout the amount of time to wait, in milliseconds
\r
1532 protected void waitForProcessEnd(String businessKey, long timeout) {
\r
1533 System.out.println("Waiting " + timeout + "ms for process with business key " +
\r
1534 businessKey + " to end");
\r
1536 long now = System.currentTimeMillis() + timeout;
\r
1537 long endTime = now + timeout;
\r
1539 while (now <= endTime) {
\r
1540 if (isProcessEnded(businessKey)) {
\r
1541 System.out.println("Process with business key " + businessKey + " has ended");
\r
1546 Thread.sleep(200);
\r
1547 } catch (InterruptedException e) {
\r
1548 String msg = "Interrupted waiting for process with business key " +
\r
1549 businessKey + " to end";
\r
1550 System.out.println(msg);
\r
1554 now = System.currentTimeMillis();
\r
1557 String msg = "Process with business key " + businessKey +
\r
1558 " did not end within " + timeout + "ms";
\r
1559 System.out.println(msg);
\r
1564 * Verifies that the specified historic process variable has the specified value.
\r
1565 * If the variable does not have the specified value, the test is failed.
\r
1566 * @param businessKey the process business key
\r
1567 * @param variable the variable name
\r
1568 * @param value the expected variable value
\r
1570 protected void checkVariable(String businessKey, String variable, Object value) {
\r
1571 if (!isProcessEnded(businessKey)) {
\r
1572 fail("Cannot get historic variable " + variable + " because process with business key " +
\r
1573 businessKey + " has not ended");
\r
1576 Object variableValue = getVariableFromHistory(businessKey, variable);
\r
1577 assertEquals(value, variableValue);
\r
1581 * Checks to see if the specified process is ended.
\r
1582 * @param businessKey the process business Key
\r
1583 * @return true if the process is ended
\r
1585 protected boolean isProcessEnded(String businessKey) {
\r
1586 HistoricProcessInstance processInstance = processEngineRule.getHistoryService()
\r
1587 .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
\r
1588 return processInstance != null && processInstance.getEndTime() != null;
\r
1592 * Gets a variable value from a historical process instance.
\r
1593 * @param businessKey the process business key
\r
1594 * @param variableName the variable name
\r
1595 * @return the variable value, or null if the variable could not be
\r
1598 protected Object getVariableFromHistory(String businessKey, String variableName) {
\r
1600 HistoricProcessInstance processInstance = processEngineRule.getHistoryService()
\r
1601 .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
\r
1603 if (processInstance == null) {
\r
1607 HistoricVariableInstance v = processEngineRule.getHistoryService()
\r
1608 .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
\r
1609 .variableName(variableName).singleResult();
\r
1610 return v == null ? null : v.getValue();
\r
1611 } catch (Exception e) {
\r
1612 System.out.println("Error retrieving variable " + variableName +
\r
1613 " from historical process with business key " + businessKey + ": " + e);
\r
1619 * Gets the value of a subflow variable from the specified subflow's
\r
1620 * historical process instance.
\r
1622 * @param subflowName - the name of the subflow that contains the variable
\r
1623 * @param variableName the variable name
\r
1625 * @return the variable value, or null if the variable could not be obtained
\r
1628 protected Object getVariableFromSubflowHistory(String subflowName, String variableName) {
\r
1630 List<HistoricProcessInstance> processInstanceList = processEngineRule.getHistoryService()
\r
1631 .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list();
\r
1633 if (processInstanceList == null) {
\r
1637 processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
\r
1639 HistoricProcessInstance processInstance = processInstanceList.get(0);
\r
1641 HistoricVariableInstance v = processEngineRule.getHistoryService()
\r
1642 .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
\r
1643 .variableName(variableName).singleResult();
\r
1644 return v == null ? null : v.getValue();
\r
1645 } catch (Exception e) {
\r
1646 System.out.println("Error retrieving variable " + variableName +
\r
1647 " from sub flow: " + subflowName + ", Exception is: " + e);
\r
1653 * Gets the value of a subflow variable from the subflow's
\r
1654 * historical process x instance.
\r
1656 * @param subflowName - the name of the subflow that contains the variable
\r
1657 * @param variableName the variable name
\r
1658 * @param subflowInstanceIndex - the instance of the subflow (use when same subflow is called more than once from mainflow)
\r
1660 * @return the variable value, or null if the variable could not be obtained
\r
1662 protected Object getVariableFromSubflowHistory(int subflowInstanceIndex, String subflowName, String variableName) {
\r
1664 List<HistoricProcessInstance> processInstanceList = processEngineRule.getHistoryService()
\r
1665 .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list();
\r
1667 if (processInstanceList == null) {
\r
1671 processInstanceList.sort((m1, m2) -> m1.getStartTime().compareTo(m2.getStartTime()));
\r
1673 HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex);
\r
1675 HistoricVariableInstance v = processEngineRule.getHistoryService()
\r
1676 .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId())
\r
1677 .variableName(variableName).singleResult();
\r
1678 return v == null ? null : v.getValue();
\r
1679 } catch (Exception e) {
\r
1680 System.out.println("Error retrieving variable " + variableName +
\r
1681 " from " + subflowInstanceIndex + " instance index of sub flow: " + subflowName + ", Exception is: " + e);
\r
1688 * Extracts text from an XML element. This method is not namespace aware
\r
1689 * (namespaces are ignored). The first matching element is selected.
\r
1690 * @param xml the XML document or fragment
\r
1691 * @param tag the desired element, e.g. "<name>"
\r
1692 * @return the element text, or null if the element was not found
\r
1694 protected String getXMLTextElement(String xml, String tag) {
\r
1695 xml = removeXMLNamespaces(xml);
\r
1697 if (!tag.startsWith("<")) {
\r
1698 tag = "<" + tag + ">";
\r
1701 int start = xml.indexOf(tag);
\r
1703 if (start == -1) {
\r
1707 int end = xml.indexOf('<', start + tag.length());
\r
1713 return xml.substring(start + tag.length(), end);
\r
1717 * Removes namespace definitions and prefixes from XML, if any.
\r
1719 private String removeXMLNamespaces(String xml) {
\r
1720 // remove xmlns declaration
\r
1721 xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
\r
1723 // remove opening tag prefix
\r
1724 xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
\r
1726 // remove closing tags prefix
\r
1727 xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
\r
1729 // remove extra spaces left when xmlns declarations are removed
\r
1730 xml = xml.replaceAll("\\s+>", ">");
\r
1736 * Asserts that two XML documents are semantically equivalent. Differences
\r
1737 * in whitespace or in namespace usage do not affect the comparison.
\r
1738 * @param expected the expected XML
\r
1739 * @param actual the XML to test
\r
1740 * @throws SAXException
\r
1741 * @throws IOException
\r
1743 public static void assertXMLEquals(String expected, String actual)
\r
1744 throws SAXException, IOException {
\r
1745 XMLUnit.setIgnoreWhitespace(true);
\r
1746 XMLUnit.setIgnoreAttributeOrder(true);
\r
1747 DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual));
\r
1748 List<?> allDifferences = diff.getAllDifferences();
\r
1749 assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size());
\r
1753 * A test implementation of AsynchronousResponse.
\r
1755 public class TestAsyncResponse implements AsynchronousResponse {
\r
1756 Response response = null;
\r
1762 public synchronized void setResponse(Response response) {
\r
1763 this.response = response;
\r
1767 * Gets the response.
\r
1768 * @return the response, or null if none has been produced yet
\r
1770 public synchronized Response getResponse() {
\r
1776 * An object that contains callback data for a "program".
\r
1778 public class CallbackSet {
\r
1779 private final Map<String, CallbackData> map = new HashMap<>();
\r
1782 * Add untyped callback data to the set.
\r
1783 * @param action the action with which the data is associated
\r
1784 * @param content the callback data
\r
1786 public void put(String action, String content) {
\r
1787 map.put(action, new CallbackData(null, null, content));
\r
1791 * Add callback data to the set.
\r
1792 * @param action the action with which the data is associated
\r
1793 * @param messageType the callback message type
\r
1794 * @param content the callback data
\r
1796 public void put(String action, String messageType, String content) {
\r
1797 map.put(action, new CallbackData(null, messageType, content));
\r
1801 * Add callback data to the set.
\r
1802 * @param action the action with which the data is associated
\r
1803 * @param contentType the callback HTTP content type
\r
1804 * @param messageType the callback message type
\r
1805 * @param content the callback data
\r
1807 public void put(String action, String contentType, String messageType, String content) {
\r
1808 map.put(action, new CallbackData(contentType, messageType, content));
\r
1812 * Retrieve callback data from the set.
\r
1813 * @param action the action with which the data is associated
\r
1814 * @return the callback data, or null if there is none for the specified operation
\r
1816 public CallbackData get(String action) {
\r
1817 return map.get(action);
\r
1822 * Represents a callback data item.
\r
1824 public class CallbackData {
\r
1825 private final String contentType;
\r
1826 private final String messageType;
\r
1827 private final String content;
\r
1831 * @param contentType the HTTP content type (optional)
\r
1832 * @param type the callback message type (optional)
\r
1833 * @param content the content
\r
1835 public CallbackData(String contentType, String messageType, String content) {
\r
1836 this.contentType = contentType;
\r
1837 this.messageType = messageType;
\r
1838 this.content = content;
\r
1842 * Gets the callback HTTP content type, possibly null.
\r
1844 public String getContentType() {
\r
1845 return contentType;
\r
1849 * Gets the callback message type, possibly null.
\r
1851 public String getMessageType() {
\r
1852 return messageType;
\r
1856 * Gets the callback content.
\r
1858 public String getContent() {
\r
1864 * A tool for evaluating XPath expressions.
\r
1866 protected class XPathTool {
\r
1867 private final DocumentBuilderFactory factory;
\r
1868 private final SimpleNamespaceContext context = new SimpleNamespaceContext();
\r
1869 private final XPath xpath = XPathFactory.newInstance().newXPath();
\r
1870 private String xml = null;
\r
1871 private Document doc = null;
\r
1876 public XPathTool() {
\r
1877 factory = DocumentBuilderFactory.newInstance();
\r
1878 factory.setNamespaceAware(true);
\r
1879 xpath.setNamespaceContext(context);
\r
1883 * Adds a namespace.
\r
1884 * @param prefix the namespace prefix
\r
1885 * @param uri the namespace uri
\r
1887 public synchronized void addNamespace(String prefix, String uri) {
\r
1888 context.add(prefix, uri);
\r
1892 * Sets the XML content to be operated on.
\r
1893 * @param xml the XML content
\r
1895 public synchronized void setXML(String xml) {
\r
1901 * Returns the document object.
\r
1902 * @return the document object, or null if XML has not been set
\r
1903 * @throws SAXException
\r
1904 * @throws IOException
\r
1905 * @throws ParserConfigurationException
\r
1907 public synchronized Document getDocument()
\r
1908 throws ParserConfigurationException, IOException, SAXException {
\r
1909 if (xml == null) {
\r
1918 * Evaluates the specified XPath expression and returns a string result.
\r
1919 * This method throws exceptions on error.
\r
1920 * @param expression the expression
\r
1921 * @return the result object
\r
1922 * @throws ParserConfigurationException
\r
1923 * @throws IOException
\r
1924 * @throws SAXException
\r
1925 * @throws XPathExpressionException on error
\r
1927 public synchronized String evaluate(String expression)
\r
1928 throws ParserConfigurationException, SAXException,
\r
1929 IOException, XPathExpressionException {
\r
1930 return (String) evaluate(expression, XPathConstants.STRING);
\r
1934 * Evaluates the specified XPath expression.
\r
1935 * This method throws exceptions on error.
\r
1936 * @param expression the expression
\r
1937 * @param returnType the return type
\r
1938 * @return the result object
\r
1939 * @throws ParserConfigurationException
\r
1940 * @throws IOException
\r
1941 * @throws SAXException
\r
1942 * @throws XPathExpressionException on error
\r
1944 public synchronized Object evaluate(String expression, QName returnType)
\r
1945 throws ParserConfigurationException, SAXException,
\r
1946 IOException, XPathExpressionException {
\r
1949 XPathExpression expr = xpath.compile(expression);
\r
1950 return expr.evaluate(doc, returnType);
\r
1954 * Private helper method that builds the document object.
\r
1955 * Assumes the calling method is synchronized.
\r
1956 * @throws ParserConfigurationException
\r
1957 * @throws IOException
\r
1958 * @throws SAXException
\r
1960 private void buildDocument() throws ParserConfigurationException,
\r
1961 IOException, SAXException {
\r
1962 if (doc == null) {
\r
1963 if (xml == null) {
\r
1964 throw new IOException("XML input is null");
\r
1967 DocumentBuilder builder = factory.newDocumentBuilder();
\r
1968 InputSource source = new InputSource(new StringReader(xml));
\r
1969 doc = builder.parse(source);
\r
1975 * A NamespaceContext class based on a Map.
\r
1977 private class SimpleNamespaceContext implements NamespaceContext {
\r
1978 private Map<String, String> prefixMap = new HashMap<>();
\r
1979 private Map<String, String> uriMap = new HashMap<>();
\r
1981 public synchronized void add(String prefix, String uri) {
\r
1982 prefixMap.put(prefix, uri);
\r
1983 uriMap.put(uri, prefix);
\r
1987 public synchronized String getNamespaceURI(String prefix) {
\r
1988 return prefixMap.get(prefix);
\r
1992 public Iterator<String> getPrefixes(String uri) {
\r
1993 List<String> list = new ArrayList<>();
\r
1994 String prefix = uriMap.get(uri);
\r
1995 if (prefix != null) {
\r
1998 return list.iterator();
\r
2002 public String getPrefix(String uri) {
\r
2003 return uriMap.get(uri);
\r
2008 * A VnfNotify XPathTool.
\r
2010 protected class VnfNotifyXPathTool extends XPathTool {
\r
2011 public VnfNotifyXPathTool() {
\r
2012 addNamespace("tns", "http://org.openecomp.mso/vnfNotify");
\r
2017 * Helper class to make it easier to create this type.
\r
2019 private static class CreateVnfNotificationOutputs
\r
2020 extends CreateVnfNotification.Outputs {
\r
2021 public void add(String key, String value) {
\r
2022 Entry entry = new Entry();
\r
2023 entry.setKey(key);
\r
2024 entry.setValue(value);
\r
2025 getEntry().add(entry);
\r
2030 * Helper class to make it easier to create this type.
\r
2032 private static class UpdateVnfNotificationOutputs
\r
2033 extends UpdateVnfNotification.Outputs {
\r
2034 public void add(String key, String value) {
\r
2035 Entry entry = new Entry();
\r
2036 entry.setKey(key);
\r
2037 entry.setValue(value);
\r
2038 getEntry().add(entry);
\r