Refactor ErrorLogHelper
[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  * Modifications Copyright (C) 2023 Deutsche Telekom SA.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *    http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.restclient;
23
24 import static org.junit.Assert.assertNotNull;
25 import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
26 import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
27 import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
28 import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
29
30 import com.google.gson.JsonArray;
31 import com.google.gson.JsonObject;
32 import com.google.gson.JsonParser;
33
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.nio.charset.StandardCharsets;
37 import java.util.Collections;
38 import java.util.Map;
39
40 import org.apache.commons.io.IOUtils;
41 import org.springframework.boot.web.client.RestTemplateBuilder;
42 import org.springframework.boot.web.client.RestTemplateCustomizer;
43 import org.springframework.core.io.Resource;
44 import org.springframework.http.HttpEntity;
45 import org.springframework.http.HttpHeaders;
46 import org.springframework.http.HttpMethod;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.MediaType;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
51 import org.springframework.stereotype.Component;
52 import org.springframework.test.web.client.ExpectedCount;
53 import org.springframework.test.web.client.MockRestServiceServer;
54 import org.springframework.util.MultiValueMap;
55 import org.springframework.web.client.RestTemplate;
56
57 @Component
58 public class MockRestClient extends RestClient {
59
60     private final RestTemplate restTemplate;
61     private final MockRestServiceServer mockRestServiceServer;
62
63     public MockRestClient(String fileName) {
64         // When jackson-dataformat-xml is on the classpath, the default Content-Type changes
65         // from application/json to application/xml
66         RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(new RestTemplateCustomizer() {
67             @Override
68             public void customize(RestTemplate restTemplate) {
69                 restTemplate.getMessageConverters()
70                     .removeIf(converter -> MappingJackson2XmlHttpMessageConverter.class.isAssignableFrom(converter.getClass()));
71             }
72         });
73         restTemplate = restTemplateBuilder.build();
74         mockRestServiceServer = MockRestServiceServer.createServer(restTemplate);
75
76         JsonObject payload = null;
77         try {
78             payload = getPayload(fileName + ".json");
79         } catch (IOException e) {
80             e.printStackTrace();
81         }
82         JsonArray mockUris = payload.getAsJsonArray("mock-uri");
83         
84         String url = "https://localhost:8447/aai/v14";
85
86         for (int i = 0; i < mockUris.size(); i++) {
87             registerRequestStub(mockUris, url, i);
88         }
89     }
90
91     private void registerRequestStub(JsonArray mockUris, String url, int i) {
92         JsonObject jsonObject = mockUris.get(i).getAsJsonObject();
93         String responseFile = jsonObject.get("response-file").getAsString();
94         String contentTypeValue = jsonObject.get("content").getAsString();
95         String uri = jsonObject.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     public MockRestClient() {
112         this("mockrequests");
113     }
114
115     public JsonObject getTestDetails(String fileName) throws IOException {
116
117         JsonObject payload = getPayload(fileName);
118
119         return payload;
120     }
121
122     public JsonObject getPayload(String filename) throws IOException {
123         InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename);
124
125         String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
126         String message = String.format("Unable to find the %s in src/test/resources", filename);
127         assertNotNull(message, inputStream);
128
129         JsonObject payload = JsonParser.parseString(result).getAsJsonObject();
130         return payload;
131     }
132
133     @Override
134     public ResponseEntity<String> execute(String uri, HttpMethod method, Map<String, String> headers, String body) {
135
136         String url = "https://localhost:8447/aai/v14/" + uri;
137
138         HttpHeaders headersMap = new HttpHeaders();
139
140         headersMap.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
141         headersMap.setContentType(MediaType.APPLICATION_JSON);
142         headersMap.add("Real-Time", "true");
143         headersMap.add("X-FromAppId", "JUNIT");
144         headersMap.add("X-TransactionId", "JUNIT");
145
146         HttpEntity<String> httpEntity = new HttpEntity(headers);
147
148         ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
149
150         return responseEntity;
151     }
152
153     @Override
154     public ResponseEntity<Resource> executeResource(String uri, HttpMethod method, Map<String, String> headers,
155             String body) {
156
157         String url = "https://localhost:8447/aai/v14/" + uri;
158
159         HttpHeaders headersMap = new HttpHeaders();
160
161         headersMap.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
162         headersMap.setContentType(MediaType.APPLICATION_JSON);
163         headersMap.add("Real-Time", "true");
164         headersMap.add("X-FromAppId", "JUNIT");
165         headersMap.add("X-TransactionId", "JUNIT");
166
167         HttpEntity<String> httpEntity = new HttpEntity(headers);
168
169         ResponseEntity<Resource> responseEntity =
170                 restTemplate.exchange(url, HttpMethod.GET, httpEntity, Resource.class);
171
172         // mockRestServiceServer.verify();
173         return responseEntity;
174     }
175
176     @Override
177     public RestTemplate getRestTemplate() {
178         RestTemplate restTemplate = null;
179         return restTemplate;
180     }
181
182     public String getBaseUrl() {
183         return "";
184     }
185
186     protected MultiValueMap<String, String> getHeaders(Map<String, String> headers) {
187         return null;
188     }
189
190 }