NONRTRIC - Implement DMaaP mediator producer service in Java
[nonrtric.git] / dmaap-adaptor-java / src / test / java / org / oran / dmaapadapter / ApplicationTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 Nordix Foundation
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.oran.dmaapadapter;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.JsonParser;
29
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.PrintStream;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35
36 import org.json.JSONObject;
37 import org.junit.jupiter.api.AfterEach;
38 import org.junit.jupiter.api.Test;
39 import org.junit.jupiter.api.extension.ExtendWith;
40 import org.oran.dmaapadapter.clients.AsyncRestClient;
41 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
42 import org.oran.dmaapadapter.configuration.ApplicationConfig;
43 import org.oran.dmaapadapter.configuration.ImmutableHttpProxyConfig;
44 import org.oran.dmaapadapter.configuration.ImmutableWebClientConfig;
45 import org.oran.dmaapadapter.configuration.WebClientConfig;
46 import org.oran.dmaapadapter.configuration.WebClientConfig.HttpProxyConfig;
47 import org.oran.dmaapadapter.r1.ConsumerJobInfo;
48 import org.oran.dmaapadapter.repository.InfoType;
49 import org.oran.dmaapadapter.repository.InfoTypes;
50 import org.oran.dmaapadapter.repository.Jobs;
51 import org.oran.dmaapadapter.tasks.ProducerRegstrationTask;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.boot.test.context.SpringBootTest;
56 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
57 import org.springframework.boot.test.context.TestConfiguration;
58 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
59 import org.springframework.boot.web.server.LocalServerPort;
60 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
61 import org.springframework.context.annotation.Bean;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.http.ResponseEntity;
64 import org.springframework.test.context.TestPropertySource;
65 import org.springframework.test.context.junit.jupiter.SpringExtension;
66
67 @ExtendWith(SpringExtension.class)
68 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
69 @TestPropertySource(properties = { //
70         "server.ssl.key-store=./config/keystore.jks", //
71         "app.webclient.trust-store=./config/truststore.jks", //
72         "app.vardata-directory=./target", //
73         "app.configuration-filepath=./src/test/resources/test_application_configuration.json"//
74 })
75 class ApplicationTest {
76     private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
77
78     @Autowired
79     private ApplicationConfig applicationConfig;
80
81     @Autowired
82     private ProducerRegstrationTask producerRegstrationTask;
83
84     @Autowired
85     private Jobs jobs;
86
87     @Autowired
88     private InfoTypes types;
89
90     @Autowired
91     private ConsumerController consumerController;
92
93     @Autowired
94     private EcsSimulatorController ecsSimulatorController;
95
96     @LocalServerPort
97     int localServerHttpPort;
98
99     private static Gson gson = new GsonBuilder().create();
100
101     static class TestApplicationConfig extends ApplicationConfig {
102         @Override
103         public String getEcsBaseUrl() {
104             return thisProcessUrl();
105         }
106
107         @Override
108         public String getDmaapBaseUrl() {
109             return thisProcessUrl();
110         }
111
112         @Override
113         public String getSelfUrl() {
114             return thisProcessUrl();
115         }
116
117         private String thisProcessUrl() {
118             final String url = "https://localhost:" + getLocalServerHttpPort();
119             return url;
120         }
121     }
122
123     /**
124      * Overrides the BeanFactory.
125      */
126     @TestConfiguration
127     static class TestBeanFactory extends BeanFactory {
128
129         @Override
130         @Bean
131         public ServletWebServerFactory servletContainer() {
132             return new TomcatServletWebServerFactory();
133         }
134
135         @Override
136         @Bean
137         public ApplicationConfig getApplicationConfig() {
138             TestApplicationConfig cfg = new TestApplicationConfig();
139             return cfg;
140         }
141     }
142
143     @AfterEach
144     void reset() {
145         this.consumerController.testResults.reset();
146         this.ecsSimulatorController.testResults.reset();
147         this.jobs.clear();
148         this.types.clear();
149     }
150
151     private AsyncRestClient restClient(boolean useTrustValidation) {
152         WebClientConfig config = this.applicationConfig.getWebClientConfig();
153         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
154                 .httpProxyHost("") //
155                 .httpProxyPort(0) //
156                 .build();
157         config = ImmutableWebClientConfig.builder() //
158                 .keyStoreType(config.keyStoreType()) //
159                 .keyStorePassword(config.keyStorePassword()) //
160                 .keyStore(config.keyStore()) //
161                 .keyPassword(config.keyPassword()) //
162                 .isTrustStoreUsed(useTrustValidation) //
163                 .trustStore(config.trustStore()) //
164                 .trustStorePassword(config.trustStorePassword()) //
165                 .httpProxyConfig(httpProxyConfig).build();
166
167         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
168         return restClientFactory.createRestClientNoHttpProxy(baseUrl());
169     }
170
171     private AsyncRestClient restClient() {
172         return restClient(false);
173     }
174
175     private String baseUrl() {
176         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
177     }
178
179     private ConsumerJobInfo consumerJobInfo() {
180         InfoType type = this.types.getAll().iterator().next();
181         return consumerJobInfo(type.getId(), "EI_JOB_ID");
182     }
183
184     private Object jsonObject() {
185         return jsonObject("{}");
186     }
187
188     private Object jsonObject(String json) {
189         try {
190             return JsonParser.parseString(json).getAsJsonObject();
191         } catch (Exception e) {
192             throw new NullPointerException(e.toString());
193         }
194     }
195
196     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
197         try {
198             String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
199             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
200         } catch (Exception e) {
201             return null;
202         }
203     }
204
205     @Test
206     void generateApiDoc() throws IOException {
207         String url = "https://localhost:" + applicationConfig.getLocalServerHttpPort() + "/v3/api-docs";
208         ResponseEntity<String> resp = restClient().getForEntity(url).block();
209         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
210         JSONObject jsonObj = new JSONObject(resp.getBody());
211         assertThat(jsonObj.remove("servers")).isNotNull();
212
213         String indented = (jsonObj).toString(4);
214         String docDir = "api/";
215         Files.createDirectories(Paths.get(docDir));
216         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "api.json"))) {
217             out.print(indented);
218         }
219     }
220
221     @Test
222     void testWholeChain() throws Exception {
223         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInEcs()).isTrue());
224
225         this.ecsSimulatorController.addJob(consumerJobInfo(), restClient());
226
227         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
228
229         DmaapSimulatorController.dmaapResponses.add("DmaapResponse1");
230         DmaapSimulatorController.dmaapResponses.add("DmaapResponse2");
231
232         ConsumerController.TestResults consumer = this.consumerController.testResults;
233         await().untilAsserted(() -> assertThat(consumer.receivedBodies.size()).isEqualTo(2));
234         assertThat(consumer.receivedBodies.get(0)).isEqualTo("DmaapResponse1");
235
236     }
237
238 }