Containerization feature of SO
[so.git] / bpmn / MSOCommonBPMN / src / test / java / org / onap / so / 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.onap.so.bpmn.mock;
22
23 import javax.ws.rs.core.UriBuilder;
24
25 import org.onap.so.client.HttpClient;
26 import org.onap.so.utils.TargetEntity;
27
28 import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
29 import com.github.tomakehurst.wiremock.common.BinaryFile;
30 import com.github.tomakehurst.wiremock.common.FileSource;
31 import com.github.tomakehurst.wiremock.extension.Parameters;
32 import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;
33 import com.github.tomakehurst.wiremock.http.Request;
34 import com.github.tomakehurst.wiremock.http.ResponseDefinition;
35
36 /**
37  * 
38  * Simulates VNF Adapter Asynch Callback response.
39  * This should work for any of the operations.
40  * 
41  * This transformer uses the mapped message as the asynchronous response.
42  * By definition, the async API sends a 202 (with no body) in the sync response.
43  *
44  */
45 public class VnfAdapterAsyncTransformer extends ResponseDefinitionTransformer {
46
47         public VnfAdapterAsyncTransformer() {
48         }
49         
50         @Override
51         public String getName() {
52                 return "vnf-adapter-async";
53         }
54
55         /**
56          * Grab the incoming request, extract properties to be copied to the response
57          * (request id, vnf id, vf module ID, message ID).  Then fetch the actual response
58          * body from its FileSource, make the replacements.
59          * 
60          * The sync response is an empty 202 response.
61          * The transformed mapped response file is sent asynchronously after a delay.
62          * 
63          * Mock Resource can be used to add dynamic properties. If vnf_delay is not in the list by
64          * default waits for 5s before the callback response is sent
65          */
66         @Override
67         public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition,
68                         FileSource fileSource, Parameters parameters) {
69                 
70                 String requestBody = request.getBodyAsString();
71                 
72                 // Note: Should recognize both XML and JSON.  But current BPMN uses XML.
73                 String notificationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>"));
74                 
75                 String vnfId = requestBody.substring(requestBody.indexOf("<vnfId>")+7, requestBody.indexOf("</vnfId>"));
76                 String vfModuleId = requestBody.substring(requestBody.indexOf("<vfModuleId>")+12, requestBody.indexOf("</vfModuleId>"));
77                 String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>"));
78                 String requestId = requestBody.substring(requestBody.indexOf("<requestId>")+11, requestBody.indexOf("</requestId>"));
79
80                 System.out.println("responseDefinition: " + responseDefinition);
81
82                 // For this mock, the mapped response body is the Async callback (since the sync response is generic for all requests)
83                 String vnfResponse = responseDefinition.getBody();
84                 System.out.println("VNF Response:" + vnfResponse);
85
86                 if (vnfResponse == null) {
87                         // Body wasn't specified.  Check for a body file
88                         String bodyFileName = responseDefinition.getBodyFileName();
89                         System.out.println("bodyFileName" + bodyFileName);
90                         if (bodyFileName != null) {
91                                 System.out.println("fileSource Class: " + fileSource.getClass().getName());
92                                 BinaryFile bodyFile = fileSource.getBinaryFileNamed(bodyFileName);
93                                 byte[] responseFile = bodyFile.readContents();
94                                 vnfResponse = new String(responseFile);
95                                 System.out.println("vnfResponse(2):" + vnfResponse);
96                         }
97                 }
98                 
99                 // Transform the SDNC response to escape < and >
100                 vnfResponse = vnfResponse.replaceAll ("VNF_ID", vnfId);
101                 vnfResponse = vnfResponse.replaceAll ("VF_MODULE_ID", vfModuleId);
102                 vnfResponse = vnfResponse.replaceAll ("REQUEST_ID", requestId);
103                 vnfResponse = vnfResponse.replaceAll ("MESSAGE_ID", messageId);
104                 
105                 Object vnfDelay = MockResource.getMockProperties().get("vnf_delay");
106                 int delay = 5000;
107                 if (vnfDelay != null) {
108                         delay = Integer.parseInt(vnfDelay.toString());
109                 }
110                 
111                 //Kick off callback thread
112                 System.out.println("notification Url:" + notificationUrl + ":delay:" + delay);
113                 CallbackResponseThread calbackResponseThread = new CallbackResponseThread(notificationUrl,vnfResponse, delay);
114                 calbackResponseThread.start();
115                 
116                 //return 200 OK with empty body
117                 return ResponseDefinitionBuilder
118                 .like(responseDefinition).but()
119                 .withStatus(202).withBody("").withHeader("Content-Type", "text/xml")
120                 .build();
121         }
122
123         @Override
124         public boolean applyGlobally() {
125             return false;
126         }
127         
128         /**
129          * 
130          * Callback response thread which sends the callback response asynchronously
131          *
132          */
133         private class CallbackResponseThread extends Thread {
134                 
135                 private String callbackUrl;
136                 private String payLoad;
137                 private int delay;
138                 
139                 public CallbackResponseThread(String callbackUrl, String payLoad, int delay) {
140                         this.callbackUrl = callbackUrl;
141                         this.payLoad = payLoad;
142                         this.delay = delay;
143                 }
144                 
145                 public void run () {
146                         try {
147                                 //Delay sending callback response
148                                 sleep(delay);
149                         } catch (InterruptedException e1) {
150                                 // TODO Auto-generated catch block
151                                 e1.printStackTrace();
152                         }
153                         
154                         try {
155                                 HttpClient client = new HttpClient(UriBuilder.fromUri(callbackUrl).build().toURL(), "text/xml", TargetEntity.VNF_ADAPTER);
156                                 client.post(payLoad);
157                         } catch (Exception e) {
158                                 // TODO Auto-generated catch block
159                                 e.printStackTrace();
160                         }
161                 }
162                 
163         }
164 }