AT&T 1712 and 1802 release code
[so.git] / bpmn / MSOCommonBPMN / src / test / java / org / openecomp / mso / bpmn / mock / VnfAdapterAsyncTransformer.java
1 /*- 
2  * ============LICENSE_START======================================================= 
3  * ONAP - SO 
4  * ================================================================================ 
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. 
6  * ================================================================================ 
7  * Licensed under the Apache License, Version 2.0 (the "License"); 
8  * you may not use this file except in compliance with the License. 
9  * You may obtain a copy of the License at 
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0 
12  * 
13  * Unless required by applicable law or agreed to in writing, software 
14  * distributed under the License is distributed on an "AS IS" BASIS, 
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
16  * See the License for the specific language governing permissions and 
17  * limitations under the License. 
18  * ============LICENSE_END========================================================= 
19  */ 
20
21 package org.openecomp.mso.bpmn.mock;
22
23 import org.jboss.resteasy.client.ClientRequest;
24 import org.jboss.resteasy.client.ClientResponse;
25
26 import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
27 import com.github.tomakehurst.wiremock.common.BinaryFile;
28 import com.github.tomakehurst.wiremock.common.FileSource;
29 import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
30 import com.github.tomakehurst.wiremock.http.Request;
31 import com.github.tomakehurst.wiremock.http.ResponseDefinition;
32
33 /**
34  * 
35  * Simulates VNF Adapter Asynch Callback response.
36  * This should work for any of the operations.
37  * 
38  * This transformer uses the mapped message as the asynchronous response.
39  * By definition, the async API sends a 202 (with no body) in the sync response.
40  *
41  */
42 public class VnfAdapterAsyncTransformer extends ResponseTransformer {
43
44         public VnfAdapterAsyncTransformer() {
45         }
46
47         public String name() {
48                 return "vnf-adapter-async";
49         }
50
51         /**
52          * Grab the incoming request, extract properties to be copied to the response
53          * (request id, vnf id, vf module ID, message ID).  Then fetch the actual response
54          * body from its FileSource, make the replacements.
55          * 
56          * The sync response is an empty 202 response.
57          * The transformed mapped response file is sent asynchronously after a delay.
58          * 
59          * Mock Resource can be used to add dynamic properties. If vnf_delay is not in the list by
60          * default waits for 5s before the callback response is sent
61          */
62         @Override
63         public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition,
64                         FileSource fileSource) {
65                 
66                 String requestBody = request.getBodyAsString();
67                 
68                 // Note: Should recognize both XML and JSON.  But current BPMN uses XML.
69                 String notificationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>"));
70                 
71                 String vnfId = requestBody.substring(requestBody.indexOf("<vnfId>")+7, requestBody.indexOf("</vnfId>"));
72                 String vfModuleId = requestBody.substring(requestBody.indexOf("<vfModuleId>")+12, requestBody.indexOf("</vfModuleId>"));
73                 String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>"));
74                 String requestId = requestBody.substring(requestBody.indexOf("<requestId>")+11, requestBody.indexOf("</requestId>"));
75
76                 System.out.println("responseDefinition: " + responseDefinition);
77
78                 // For this mock, the mapped response body is the Async callback (since the sync response is generic for all requests)
79                 String vnfResponse = responseDefinition.getBody();
80                 System.out.println("VNF Response:" + vnfResponse);
81
82                 if (vnfResponse == null) {
83                         // Body wasn't specified.  Check for a body file
84                         String bodyFileName = responseDefinition.getBodyFileName();
85                         System.out.println("bodyFileName" + bodyFileName);
86                         if (bodyFileName != null) {
87                                 System.out.println("fileSource Class: " + fileSource.getClass().getName());
88                                 BinaryFile bodyFile = fileSource.getBinaryFileNamed(bodyFileName);
89                                 byte[] responseFile = bodyFile.readContents();
90                                 vnfResponse = new String(responseFile);
91                                 System.out.println("vnfResponse(2):" + vnfResponse);
92                         }
93                 }
94                 
95                 // Transform the SDNC response to escape < and >
96                 vnfResponse = vnfResponse.replaceAll ("VNF_ID", vnfId);
97                 vnfResponse = vnfResponse.replaceAll ("VF_MODULE_ID", vfModuleId);
98                 vnfResponse = vnfResponse.replaceAll ("REQUEST_ID", requestId);
99                 vnfResponse = vnfResponse.replaceAll ("MESSAGE_ID", messageId);
100                 
101                 Object vnfDelay = MockResource.getMockProperties().get("vnf_delay");
102                 int delay = 5000;
103                 if (vnfDelay != null) {
104                         delay = Integer.parseInt(vnfDelay.toString());
105                 }
106                 
107                 //Kick off callback thread
108                 System.out.println("notification Url:" + notificationUrl + ":delay:" + delay);
109                 CallbackResponseThread calbackResponseThread = new CallbackResponseThread(notificationUrl,vnfResponse, delay);
110                 calbackResponseThread.start();
111                 
112                 //return 200 OK with empty body
113                 return ResponseDefinitionBuilder
114                 .like(responseDefinition).but()
115                 .withStatus(202).withBody("").withHeader("Content-Type", "text/xml")
116                 .build();
117         }
118
119         @Override
120         public boolean applyGlobally() {
121             return false;
122         }
123         
124         /**
125          * 
126          * Callback response thread which sends the callback response asynchronously
127          *
128          */
129         private class CallbackResponseThread extends Thread {
130                 
131                 private String callbackUrl;
132                 private String payLoad;
133                 private int delay;
134                 
135                 public CallbackResponseThread(String callbackUrl, String payLoad, int delay) {
136                         this.callbackUrl = callbackUrl;
137                         this.payLoad = payLoad;
138                         this.delay = delay;
139                 }
140                 
141                 public void run () {
142                         try {
143                                 //Delay sending callback response
144                                 sleep(delay);
145                         } catch (InterruptedException e1) {
146                                 // TODO Auto-generated catch block
147                                 e1.printStackTrace();
148                         }
149                         System.out.println("Sending callback response:" + callbackUrl);
150                         ClientRequest request = new ClientRequest(callbackUrl);
151                         request.body("text/xml", payLoad);
152                         System.err.println(payLoad);
153                         try {
154                                 ClientResponse result = request.post();
155                                 //System.err.println("Successfully posted callback:" + result.getStatus());
156                         } catch (Exception e) {
157                                 // TODO Auto-generated catch block
158                                 e.printStackTrace();
159                         }
160                 }
161                 
162         }
163 }