68ca879531757a15edf89704b8df843720ffff3c
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / adapt / kafka / KafkaEventSubscriber.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka;
23
24 import com.salesforce.kafka.test.junit4.SharedKafkaTestResource;
25
26 import java.time.Duration;
27 import java.util.Arrays;
28 import java.util.Properties;
29
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     private long eventsReceivedCount = 0;
52
53     KafkaConsumer<String, String> consumer;
54
55     private final Thread subscriberThread;
56
57     /**
58      * Instantiates a new kafka event subscriber.
59      *
60      * @param topic the topic
61      * @param sharedKafkaTestResource the kafka server address
62      * @throws MessagingException the messaging exception
63      */
64     public KafkaEventSubscriber(final String topic,
65         final SharedKafkaTestResource sharedKafkaTestResource) throws MessagingException {
66         this.topic = topic;
67
68         final Properties consumerProperties = new Properties();
69         consumerProperties.put("group.id", "test");
70
71         consumer = sharedKafkaTestResource.getKafkaTestUtils().getKafkaConsumer(StringDeserializer.class,
72             StringDeserializer.class, consumerProperties);
73         consumer.subscribe(Arrays.asList(topic));
74
75         subscriberThread = new Thread(this);
76         subscriberThread.start();
77     }
78
79     /**
80      * {@inheritDoc}.
81      */
82     @Override
83     public void run() {
84         LOGGER.debug("{}: receiving events from Kafka server  on topic {}", KafkaEventSubscriber.class.getName(),
85             topic);
86
87         while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) {
88             try {
89                 final ConsumerRecords<String, String> records = consumer.poll(POLL_DURATION);
90                 for (final ConsumerRecord<String, String> record : records) {
91                     eventsReceivedCount++;
92                     LOGGER.debug("****** Received event No. {} ******\noffset={}\nkey={}\n{}", eventsReceivedCount,
93                         record.offset(), record.key(), record.value());
94                 }
95             } catch (final Exception e) {
96                 // Thread interrupted
97                 break;
98             }
99         }
100
101         LOGGER.debug("{}: event reception completed", KafkaEventSubscriber.class.getName());
102     }
103
104     /**
105      * Gets the events received count.
106      *
107      * @return the events received count
108      */
109     public long getEventsReceivedCount() {
110         return eventsReceivedCount;
111     }
112
113     /**
114      * Shutdown.
115      */
116     public void shutdown() {
117         subscriberThread.interrupt();
118
119         while (subscriberThread.isAlive()) {
120             ThreadUtilities.sleep(10);
121         }
122
123         consumer.close();
124         LOGGER.debug("{} : stopped", KafkaEventSubscriber.class.getName());
125     }
126
127     public boolean isAlive() {
128         return subscriberThread.isAlive();
129     }
130 }