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