5a6696d80765fbb58791c80f3e5ab385d2db0e7e
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka;
24
25 import com.salesforce.kafka.test.junit4.SharedKafkaTestResource;
26 import java.time.Duration;
27 import java.util.Arrays;
28 import java.util.Properties;
29 import lombok.Getter;
30 import org.apache.kafka.clients.consumer.ConsumerRecord;
31 import org.apache.kafka.clients.consumer.ConsumerRecords;
32 import org.apache.kafka.clients.consumer.KafkaConsumer;
33 import org.apache.kafka.common.serialization.StringDeserializer;
34 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
35 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The Class KafkaEventSubscriber.
41  *
42  * @author Liam Fallon (liam.fallon@ericsson.com)
43  */
44 public class KafkaEventSubscriber implements Runnable {
45     // Get a reference to the logger
46     private static final Logger LOGGER = LoggerFactory.getLogger(KafkaEventSubscriber.class);
47
48     private static final Duration POLL_DURATION = Duration.ofMillis(100);
49
50     private final String topic;
51     @Getter
52     private long eventsReceivedCount = 0;
53
54     KafkaConsumer<String, String> consumer;
55
56     private final Thread subscriberThread;
57
58     /**
59      * Instantiates a new kafka event subscriber.
60      *
61      * @param topic the topic
62      * @param sharedKafkaTestResource the kafka server address
63      * @throws MessagingException the messaging exception
64      */
65     public KafkaEventSubscriber(final String topic,
66         final SharedKafkaTestResource sharedKafkaTestResource) throws MessagingException {
67         this.topic = topic;
68
69         final Properties consumerProperties = new Properties();
70         consumerProperties.put("group.id", "test");
71
72         consumer = sharedKafkaTestResource.getKafkaTestUtils().getKafkaConsumer(StringDeserializer.class,
73             StringDeserializer.class, consumerProperties);
74         consumer.subscribe(Arrays.asList(topic));
75
76         subscriberThread = new Thread(this);
77         subscriberThread.start();
78     }
79
80     /**
81      * {@inheritDoc}.
82      */
83     @Override
84     public void run() {
85         LOGGER.debug("{}: receiving events from Kafka server  on topic {}", KafkaEventSubscriber.class.getName(),
86             topic);
87
88         while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) {
89             try {
90                 final ConsumerRecords<String, String> records = consumer.poll(POLL_DURATION);
91                 for (final ConsumerRecord<String, String> record : records) {
92                     eventsReceivedCount++;
93                     LOGGER.debug("****** Received event No. {} ******\noffset={}\nkey={}\n{}", eventsReceivedCount,
94                         record.offset(), record.key(), record.value());
95                 }
96             } catch (final Exception e) {
97                 // Thread interrupted
98                 break;
99             }
100         }
101
102         LOGGER.debug("{}: event reception completed", KafkaEventSubscriber.class.getName());
103     }
104
105     /**
106      * Shutdown.
107      */
108     public void shutdown() {
109         subscriberThread.interrupt();
110
111         while (subscriberThread.isAlive()) {
112             ThreadUtilities.sleep(10);
113         }
114
115         consumer.close();
116         LOGGER.debug("{} : stopped", KafkaEventSubscriber.class.getName());
117     }
118
119     public boolean isAlive() {
120         return subscriberThread.isAlive();
121     }
122 }