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