2 * ========================LICENSE_START=================================
5 * Copyright (C) 2021 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oran.dmaapadapter;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import com.google.gson.JsonParser;
29 import java.time.Duration;
30 import java.util.HashMap;
33 import org.apache.kafka.clients.producer.ProducerConfig;
34 import org.apache.kafka.clients.producer.ProducerRecord;
35 import org.apache.kafka.common.serialization.IntegerSerializer;
36 import org.apache.kafka.common.serialization.StringSerializer;
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.Job;
51 import org.oran.dmaapadapter.repository.Jobs;
52 import org.oran.dmaapadapter.tasks.KafkaJobDataConsumer;
53 import org.oran.dmaapadapter.tasks.KafkaTopicConsumers;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.boot.test.context.SpringBootTest;
58 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
59 import org.springframework.boot.test.context.TestConfiguration;
60 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
61 import org.springframework.boot.web.server.LocalServerPort;
62 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
63 import org.springframework.context.annotation.Bean;
64 import org.springframework.test.context.TestPropertySource;
65 import org.springframework.test.context.junit.jupiter.SpringExtension;
67 import reactor.core.publisher.Flux;
68 import reactor.kafka.sender.KafkaSender;
69 import reactor.kafka.sender.SenderOptions;
70 import reactor.kafka.sender.SenderRecord;
72 @SuppressWarnings("java:S3577") // Rename class
73 @ExtendWith(SpringExtension.class)
74 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
75 @TestPropertySource(properties = { //
76 "server.ssl.key-store=./config/keystore.jks", //
77 "app.webclient.trust-store=./config/truststore.jks", //
78 "app.configuration-filepath=./src/test/resources/test_application_configuration.json"//
80 class IntegrationWithKafka {
82 final String TYPE_ID = "KafkaInformationType";
85 private ApplicationConfig applicationConfig;
91 private InfoTypes types;
94 private ConsumerController consumerController;
97 private EcsSimulatorController ecsSimulatorController;
100 private KafkaTopicConsumers kafkaTopicConsumers;
102 private static com.google.gson.Gson gson = new com.google.gson.GsonBuilder().create();
104 private static final Logger logger = LoggerFactory.getLogger(IntegrationWithKafka.class);
107 int localServerHttpPort;
109 static class TestApplicationConfig extends ApplicationConfig {
111 public String getEcsBaseUrl() {
112 return thisProcessUrl();
116 public String getDmaapBaseUrl() {
117 return thisProcessUrl();
121 public String getSelfUrl() {
122 return thisProcessUrl();
125 private String thisProcessUrl() {
126 final String url = "https://localhost:" + getLocalServerHttpPort();
132 * Overrides the BeanFactory.
135 static class TestBeanFactory extends BeanFactory {
139 public ServletWebServerFactory servletContainer() {
140 return new TomcatServletWebServerFactory();
145 public ApplicationConfig getApplicationConfig() {
146 TestApplicationConfig cfg = new TestApplicationConfig();
153 this.consumerController.testResults.reset();
154 this.ecsSimulatorController.testResults.reset();
158 private AsyncRestClient restClient(boolean useTrustValidation) {
159 WebClientConfig config = this.applicationConfig.getWebClientConfig();
160 HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
161 .httpProxyHost("") //
164 config = ImmutableWebClientConfig.builder() //
165 .keyStoreType(config.keyStoreType()) //
166 .keyStorePassword(config.keyStorePassword()) //
167 .keyStore(config.keyStore()) //
168 .keyPassword(config.keyPassword()) //
169 .isTrustStoreUsed(useTrustValidation) //
170 .trustStore(config.trustStore()) //
171 .trustStorePassword(config.trustStorePassword()) //
172 .httpProxyConfig(httpProxyConfig).build();
174 AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
175 return restClientFactory.createRestClientNoHttpProxy(baseUrl());
178 private AsyncRestClient restClient() {
179 return restClient(false);
182 private String baseUrl() {
183 return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
186 private static Object jobParametersAsJsonObject(String filter, long maxTimeMiliseconds, int maxSize,
187 int maxConcurrency) {
188 Job.Parameters param =
189 new Job.Parameters(filter, new Job.BufferTimeout(maxSize, maxTimeMiliseconds), maxConcurrency);
190 String str = gson.toJson(param);
191 return jsonObject(str);
194 private static Object jsonObject(String json) {
196 return JsonParser.parseString(json).getAsJsonObject();
197 } catch (Exception e) {
198 throw new NullPointerException(e.toString());
202 ConsumerJobInfo consumerJobInfo(String filter, Duration maxTime, int maxSize, int maxConcurrency) {
204 String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
205 return new ConsumerJobInfo(TYPE_ID,
206 jobParametersAsJsonObject(filter, maxTime.toMillis(), maxSize, maxConcurrency), "owner", targetUri,
208 } catch (Exception e) {
213 private SenderOptions<Integer, String> senderOptions() {
214 String bootstrapServers = this.applicationConfig.getKafkaBootStrapServers();
216 Map<String, Object> props = new HashMap<>();
217 props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
218 props.put(ProducerConfig.CLIENT_ID_CONFIG, "sample-producer");
219 props.put(ProducerConfig.ACKS_CONFIG, "all");
220 props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
221 props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
222 return SenderOptions.create(props);
225 private SenderRecord<Integer, String, Integer> senderRecord(String data) {
226 final InfoType infoType = this.types.get(TYPE_ID);
228 int correlationMetadata = 2;
229 return SenderRecord.create(new ProducerRecord<>(infoType.getKafkaInputTopic(), key, data), correlationMetadata);
232 private void sendDataToStream(Flux<SenderRecord<Integer, String, Integer>> dataToSend) {
233 final KafkaSender<Integer, String> sender = KafkaSender.create(senderOptions());
235 sender.send(dataToSend) //
236 .doOnError(e -> logger.error("Send failed", e)) //
241 private void verifiedReceivedByConsumer(String... strings) {
242 ConsumerController.TestResults consumer = this.consumerController.testResults;
243 await().untilAsserted(() -> assertThat(consumer.receivedBodies.size()).isEqualTo(strings.length));
244 for (String s : strings) {
245 assertTrue(consumer.hasReceived(s));
250 void kafkaIntegrationTest() throws Exception {
251 final String JOB_ID1 = "ID1";
252 final String JOB_ID2 = "ID2";
254 // Register producer, Register types
255 await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
256 assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
258 // Create two jobs. One buffering and one with a filter
259 this.ecsSimulatorController.addJob(consumerJobInfo(null, Duration.ofMillis(400), 1000, 20), JOB_ID1,
261 this.ecsSimulatorController.addJob(consumerJobInfo("^Message_1$", Duration.ZERO, 0, 1), JOB_ID2, restClient());
263 await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(2));
265 var dataToSend = Flux.range(1, 3).map(i -> senderRecord("Message_" + i)); // Message_1, Message_2 etc.
266 sendDataToStream(dataToSend);
268 verifiedReceivedByConsumer("Message_1", "[\"Message_1\", \"Message_2\", \"Message_3\"]");
271 this.ecsSimulatorController.deleteJob(JOB_ID1, restClient());
272 this.ecsSimulatorController.deleteJob(JOB_ID2, restClient());
274 await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
275 await().untilAsserted(() -> assertThat(this.kafkaTopicConsumers.getConsumers().keySet()).isEmpty());
279 void kafkaIOverflow() throws InterruptedException {
280 final String JOB_ID1 = "ID1";
281 final String JOB_ID2 = "ID2";
283 // Register producer, Register types
284 await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
285 assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
288 this.ecsSimulatorController.addJob(consumerJobInfo(null, Duration.ofMillis(400), 1000, 1), JOB_ID1,
290 this.ecsSimulatorController.addJob(consumerJobInfo(null, Duration.ZERO, 0, 1), JOB_ID2, restClient());
292 await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(2));
294 var dataToSend = Flux.range(1, 1000000).map(i -> senderRecord("Message_" + i)); // Message_1, Message_2 etc.
295 sendDataToStream(dataToSend); // this should overflow
297 KafkaJobDataConsumer consumer = kafkaTopicConsumers.getConsumers().get(TYPE_ID).iterator().next();
298 await().untilAsserted(() -> assertThat(consumer.isRunning()).isFalse());
299 this.consumerController.testResults.reset();
301 this.ecsSimulatorController.deleteJob(JOB_ID2, restClient()); // Delete one job
302 kafkaTopicConsumers.restartNonRunningTasks();
303 Thread.sleep(1000); // Restarting the input seems to take some asynch time
305 dataToSend = Flux.just(senderRecord("Howdy\""));
306 sendDataToStream(dataToSend);
308 verifiedReceivedByConsumer("[\"Howdy\\\"\"]");
311 this.ecsSimulatorController.deleteJob(JOB_ID1, restClient());
312 this.ecsSimulatorController.deleteJob(JOB_ID2, restClient());
314 await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
315 await().untilAsserted(() -> assertThat(this.kafkaTopicConsumers.getConsumers().keySet()).isEmpty());