NONRTRIC - Implement DMaaP mediator producer service in Java
[nonrtric.git] / dmaap-adaptor-java / src / test / java / org / oran / dmaapadapter / IntegrationWithEcs.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 org.junit.jupiter.api.AfterEach;
31 import org.junit.jupiter.api.Test;
32 import org.junit.jupiter.api.extension.ExtendWith;
33 import org.oran.dmaapadapter.clients.AsyncRestClient;
34 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
35 import org.oran.dmaapadapter.configuration.ApplicationConfig;
36 import org.oran.dmaapadapter.configuration.ImmutableHttpProxyConfig;
37 import org.oran.dmaapadapter.configuration.ImmutableWebClientConfig;
38 import org.oran.dmaapadapter.configuration.WebClientConfig;
39 import org.oran.dmaapadapter.configuration.WebClientConfig.HttpProxyConfig;
40 import org.oran.dmaapadapter.r1.ConsumerJobInfo;
41 import org.oran.dmaapadapter.repository.InfoType;
42 import org.oran.dmaapadapter.repository.InfoTypes;
43 import org.oran.dmaapadapter.repository.Jobs;
44 import org.oran.dmaapadapter.tasks.ProducerRegstrationTask;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.boot.test.context.SpringBootTest;
47 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
48 import org.springframework.boot.test.context.TestConfiguration;
49 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
50 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
51 import org.springframework.context.annotation.Bean;
52 import org.springframework.test.context.TestPropertySource;
53 import org.springframework.test.context.junit.jupiter.SpringExtension;
54
55 @SuppressWarnings("java:S3577") // Rename class
56 @ExtendWith(SpringExtension.class)
57 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
58 @TestPropertySource(properties = { //
59         "server.ssl.key-store=./config/keystore.jks", //
60         "app.webclient.trust-store=./config/truststore.jks", //
61         "app.configuration-filepath=./src/test/resources/test_application_configuration.json", //
62         "app.ecs-base-url=https://localhost:8434" //
63 })
64 class IntegrationWithEcs {
65
66     private static final String EI_JOB_ID = "EI_JOB_ID";
67
68     @Autowired
69     private ApplicationConfig applicationConfig;
70
71     @Autowired
72     private ProducerRegstrationTask producerRegstrationTask;
73
74     @Autowired
75     private Jobs jobs;
76
77     @Autowired
78     private InfoTypes types;
79
80     @Autowired
81     private ConsumerController consumerController;
82
83     private static Gson gson = new GsonBuilder().create();
84
85     static class TestApplicationConfig extends ApplicationConfig {
86
87         @Override
88         public String getEcsBaseUrl() {
89             return "https://localhost:8434";
90         }
91
92         @Override
93         public String getDmaapBaseUrl() {
94             return thisProcessUrl();
95         }
96
97         @Override
98         public String getSelfUrl() {
99             return thisProcessUrl();
100         }
101
102         private String thisProcessUrl() {
103             final String url = "https://localhost:" + getLocalServerHttpPort();
104             return url;
105         }
106     }
107
108     /**
109      * Overrides the BeanFactory.
110      */
111     @TestConfiguration
112     static class TestBeanFactory extends BeanFactory {
113
114         @Override
115         @Bean
116         public ServletWebServerFactory servletContainer() {
117             return new TomcatServletWebServerFactory();
118         }
119
120         @Override
121         @Bean
122         public ApplicationConfig getApplicationConfig() {
123             TestApplicationConfig cfg = new TestApplicationConfig();
124             return cfg;
125         }
126     }
127
128     @AfterEach
129     void reset() {
130         this.consumerController.testResults.reset();
131         this.jobs.clear();
132         this.types.clear();
133     }
134
135     private AsyncRestClient restClient(boolean useTrustValidation) {
136         WebClientConfig config = this.applicationConfig.getWebClientConfig();
137         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
138                 .httpProxyHost("") //
139                 .httpProxyPort(0) //
140                 .build();
141         config = ImmutableWebClientConfig.builder() //
142                 .keyStoreType(config.keyStoreType()) //
143                 .keyStorePassword(config.keyStorePassword()) //
144                 .keyStore(config.keyStore()) //
145                 .keyPassword(config.keyPassword()) //
146                 .isTrustStoreUsed(useTrustValidation) //
147                 .trustStore(config.trustStore()) //
148                 .trustStorePassword(config.trustStorePassword()) //
149                 .httpProxyConfig(httpProxyConfig).build();
150
151         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
152         return restClientFactory.createRestClientNoHttpProxy(selfBaseUrl());
153     }
154
155     private AsyncRestClient restClient() {
156         return restClient(false);
157     }
158
159     private String selfBaseUrl() {
160         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
161     }
162
163     private String ecsBaseUrl() {
164         return applicationConfig.getEcsBaseUrl();
165     }
166
167     private String jobUrl(String jobId) {
168         return ecsBaseUrl() + "/data-consumer/v1/info-jobs/" + jobId;
169     }
170
171     private void createInformationJobInEcs(String jobId) {
172         String body = gson.toJson(consumerJobInfo());
173         try {
174             // Delete the job if it already exists
175             deleteInformationJobInEcs(jobId);
176         } catch (Exception e) {
177         }
178         restClient().putForEntity(jobUrl(jobId), body).block();
179     }
180
181     private void deleteInformationJobInEcs(String jobId) {
182         restClient().delete(jobUrl(jobId)).block();
183     }
184
185     private ConsumerJobInfo consumerJobInfo() {
186         InfoType type = this.types.getAll().iterator().next();
187         return consumerJobInfo(type.getId(), EI_JOB_ID);
188     }
189
190     private Object jsonObject() {
191         return jsonObject("{}");
192     }
193
194     private Object jsonObject(String json) {
195         try {
196             return JsonParser.parseString(json).getAsJsonObject();
197         } catch (Exception e) {
198             throw new NullPointerException(e.toString());
199         }
200     }
201
202     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
203         try {
204             String targetUri = selfBaseUrl() + ConsumerController.CONSUMER_TARGET_URL;
205             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
206         } catch (Exception e) {
207             return null;
208         }
209     }
210
211     @Test
212     void testWholeChain() throws Exception {
213         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInEcs()).isTrue());
214
215         createInformationJobInEcs(EI_JOB_ID);
216
217         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
218
219         DmaapSimulatorController.dmaapResponses.add("DmaapResponse1");
220         DmaapSimulatorController.dmaapResponses.add("DmaapResponse2");
221
222         ConsumerController.TestResults results = this.consumerController.testResults;
223         await().untilAsserted(() -> assertThat(results.receivedBodies.size()).isEqualTo(2));
224         assertThat(results.receivedBodies.get(0)).isEqualTo("DmaapResponse1");
225
226         deleteInformationJobInEcs(EI_JOB_ID);
227
228         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
229
230         synchronized (this) {
231             // logger.warn("**************** Keeping server alive! " +
232             // this.applicationConfig.getLocalServerHttpPort());
233             // this.wait();
234         }
235     }
236
237 }