52e6364bc7a87f5472f60ddd7a4de46e9b9d54d8
[aai/aai-common.git] / aai-schema-ingest / src / test / java / org / onap / aai / restclient / MockRestClient.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 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.aai.restclient;
22
23 import static org.junit.Assert.assertNotNull;
24 import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
25 import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.google.gson.JsonArray;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonParser;
31
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.nio.charset.StandardCharsets;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.List;
38 import java.util.Map;
39
40 import org.apache.commons.io.IOUtils;
41 import org.springframework.core.io.Resource;
42 import org.springframework.http.*;
43 import org.springframework.stereotype.Component;
44 import org.springframework.test.web.client.ExpectedCount;
45 import org.springframework.test.web.client.MockRestServiceServer;
46 import org.springframework.util.MultiValueMap;
47 import org.springframework.web.client.RestTemplate;
48
49 @Component
50 public class MockRestClient extends RestClient {
51
52     private RestTemplate restTemplate;
53     private MockRestServiceServer mockRestServiceServer;
54
55     String fileName = "mockrequests";
56
57     public MockRestClient(String fileName) {
58         /*
59          * List<MockRestServiceServer> mockedAAIRequests = new ArrayList<>(aaiRequests.size());
60          */
61         List<MockRestServiceServer> mockedAAIRequests = new ArrayList<>();
62
63         restTemplate = new RestTemplate();
64         /*
65          * MockRestServiceServer server = MockRestServiceServer
66          * .bindTo(restClientFactory.getRestClient(ClientType.SchemaService).getRestTemplate())
67          * .build();
68          * server.expect(MockRestRequestMatchers.requestTo(url))
69          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
70          */
71
72         // RestTemplateBuilder mockBuilder = mock(RestTemplateBuilder.class);
73         // when(mockBuilder.build()).thenReturn(restTemplate);
74
75         JsonObject payload = null;
76         try {
77             payload = getPayload(fileName + ".json");
78         } catch (IOException e) {
79             e.printStackTrace();
80         }
81
82         JsonArray mockUris = payload.getAsJsonArray("mock-uri");
83
84         mockRestServiceServer = MockRestServiceServer.createServer(restTemplate);
85         String url = "https://localhost:8447/aai/v14";
86         /*
87          * mockRestServiceServer.expect(requestTo(url))
88          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
89          */
90
91         for (int i = 0; i < mockUris.size(); i++) {
92             String responseFile = mockUris.get(i).getAsJsonObject().get("response-file").getAsString();
93             String contentTypeValue = mockUris.get(i).getAsJsonObject().get("content").getAsString();
94
95             String uri = mockUris.get(i).getAsJsonObject().get("aai-uri").getAsString();
96
97             InputStream inputStream = getClass().getClassLoader().getResourceAsStream(responseFile);
98             String responseBody = null;
99             try {
100                 responseBody = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
101             } catch (IOException e) {
102                 e.printStackTrace();
103             }
104
105             mockRestServiceServer.expect(ExpectedCount.manyTimes(), requestTo(url + uri))
106                     .andExpect(method(HttpMethod.GET)).andExpect(content().contentType(contentTypeValue))
107                     .andRespond(withStatus(HttpStatus.OK).body(responseBody.toString())
108                             .contentType(MediaType.valueOf(contentTypeValue)));
109
110         }
111     }
112
113     public MockRestClient() {
114
115         restTemplate = new RestTemplate();
116         /*
117          * MockRestServiceServer server = MockRestServiceServer
118          * .bindTo(restClientFactory.getRestClient(ClientType.SchemaService).getRestTemplate())
119          * .build();
120          * server.expect(MockRestRequestMatchers.requestTo(url))
121          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
122          */
123
124         // RestTemplateBuilder mockBuilder = mock(RestTemplateBuilder.class);
125         // when(mockBuilder.build()).thenReturn(restTemplate);
126
127         JsonObject payload = null;
128         try {
129             payload = getPayload(fileName + ".json");
130         } catch (IOException e) {
131             e.printStackTrace();
132         }
133
134         JsonArray mockUris = payload.getAsJsonArray("mock-uri");
135
136         mockRestServiceServer = MockRestServiceServer.createServer(restTemplate);
137         String url = "https://localhost:8447/aai/v14";
138         /*
139          * mockRestServiceServer.expect(requestTo(url))
140          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
141          */
142
143         for (int i = 0; i < mockUris.size(); i++) {
144             String responseFile = mockUris.get(i).getAsJsonObject().get("response-file").getAsString();
145             String contentTypeValue = mockUris.get(i).getAsJsonObject().get("content").getAsString();
146
147             String uri = mockUris.get(i).getAsJsonObject().get("aai-uri").getAsString();
148
149             InputStream inputStream = getClass().getClassLoader().getResourceAsStream(responseFile);
150             String responseBody = null;
151             try {
152                 responseBody = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
153             } catch (IOException e) {
154                 e.printStackTrace();
155             }
156
157             mockRestServiceServer.expect(ExpectedCount.manyTimes(), requestTo(url + uri))
158                     .andExpect(method(HttpMethod.GET)).andExpect(content().contentType(contentTypeValue))
159                     .andRespond(withStatus(HttpStatus.OK).body(responseBody.toString())
160                             .contentType(MediaType.valueOf(contentTypeValue)));
161
162         }
163
164     }
165
166     public JsonObject getTestDetails(String fileName) throws IOException {
167
168         JsonObject payload = getPayload(fileName);
169
170         return payload;
171     }
172
173     public JsonObject getPayload(String filename) throws IOException {
174         InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename);
175
176         // InputStream inputStream = new FileInputStream(filename);
177
178         String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
179         String message = String.format("Unable to find the %s in src/test/resources", filename);
180         assertNotNull(message, inputStream);
181
182         JsonParser parser = new JsonParser();
183         JsonObject payload = parser.parse(result).getAsJsonObject();
184         return payload;
185     }
186
187     @Override
188     public ResponseEntity execute(String uri, HttpMethod method, Map<String, String> headers, String body) {
189
190         String url = "https://localhost:8447/aai/v14/" + uri;
191
192         /*
193          * MockRestServiceServer server = MockRestServiceServer
194          * .bindTo(restClientFactory.getRestClient(ClientType.SchemaService).getRestTemplate())
195          * .build();
196          * server.expect(MockRestRequestMatchers.requestTo(url))
197          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
198          */
199
200         // RestTemplateBuilder mockBuilder = mock(RestTemplateBuilder.class);
201         // when(mockBuilder.build()).thenReturn(restTemplate);
202
203         /*
204          * MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
205          * server.expect(requestTo(url))
206          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
207          * return new ResponseEntity("blah", HttpStatus.OK);
208          * server.expect(ExpectedCount.manyTimes(), requestTo(Matchers.startsWith(aaiBaseUrl +
209          * aaiRequests.get(i).get("aai-uri").asText())))
210          * .andExpect(method(HttpMethod.GET))
211          * .andExpect(content().contentType(MediaType.APPLICATION_JSON))
212          * .andRespond(withStatus(HttpStatus.OK).body(aaiResponses.get(i).toString()).contentType(MediaType.
213          * APPLICATION_JSON));
214          */
215
216         HttpHeaders headersMap = new HttpHeaders();
217
218         headersMap.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
219         headersMap.setContentType(MediaType.APPLICATION_JSON);
220         headersMap.add("Real-Time", "true");
221         headersMap.add("X-FromAppId", "JUNIT");
222         headersMap.add("X-TransactionId", "JUNIT");
223
224         HttpEntity httpEntity = new HttpEntity(headers);
225
226         ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
227
228         // mockRestServiceServer.verify();
229         return responseEntity;
230     }
231
232     @Override
233     public ResponseEntity executeResource(String uri, HttpMethod method, Map<String, String> headers, String body) {
234
235         String url = "https://localhost:8447/aai/v14/" + uri;
236
237         /*
238          * MockRestServiceServer server = MockRestServiceServer
239          * .bindTo(restClientFactory.getRestClient(ClientType.SchemaService).getRestTemplate())
240          * .build();
241          * server.expect(MockRestRequestMatchers.requestTo(url))
242          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
243          */
244
245         // RestTemplateBuilder mockBuilder = mock(RestTemplateBuilder.class);
246         // when(mockBuilder.build()).thenReturn(restTemplate);
247
248         /*
249          * MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
250          * server.expect(requestTo(url))
251          * .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
252          * return new ResponseEntity("blah", HttpStatus.OK);
253          * server.expect(ExpectedCount.manyTimes(), requestTo(Matchers.startsWith(aaiBaseUrl +
254          * aaiRequests.get(i).get("aai-uri").asText())))
255          * .andExpect(method(HttpMethod.GET))
256          * .andExpect(content().contentType(MediaType.APPLICATION_JSON))
257          * .andRespond(withStatus(HttpStatus.OK).body(aaiResponses.get(i).toString()).contentType(MediaType.
258          * APPLICATION_JSON));
259          */
260
261         HttpHeaders headersMap = new HttpHeaders();
262
263         headersMap.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
264         headersMap.setContentType(MediaType.APPLICATION_JSON);
265         headersMap.add("Real-Time", "true");
266         headersMap.add("X-FromAppId", "JUNIT");
267         headersMap.add("X-TransactionId", "JUNIT");
268
269         HttpEntity httpEntity = new HttpEntity(headers);
270
271         ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Resource.class);
272
273         // mockRestServiceServer.verify();
274         return responseEntity;
275     }
276
277     @Override
278     public RestTemplate getRestTemplate() {
279         RestTemplate restTemplate = null;
280         return restTemplate;
281     }
282
283     public String getBaseUrl() {
284         return "";
285     }
286
287     protected MultiValueMap<String, String> getHeaders(Map<String, String> headers) {
288         return null;
289     }
290
291     protected EELFLogger getLogger() {
292         return null;
293     }
294
295 }