[KAFKA] Add docker-compose to sample project
[dmaap/kafka11aaf.git] / kafkaClient / src / main / java / org / onap / dmaap / kafka / OnapKafkaConsumer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * dmaap-kafka-client
4  * ================================================================================
5  * Copyright (C) 2023 Nordix Foundation. 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dmaap.kafka;
22
23 import java.time.Duration;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Properties;
27 import java.util.UUID;
28 import org.apache.kafka.clients.CommonClientConfigs;
29 import org.apache.kafka.clients.consumer.ConsumerConfig;
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.KafkaException;
34 import org.apache.kafka.common.config.SaslConfigs;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Utility class that provides a KafkaConsumer to communicate with a kafka cluster
40  */
41 public class OnapKafkaConsumer {
42
43     private final Logger log = LoggerFactory.getLogger(OnapKafkaConsumer.class);
44     private final KafkaConsumer<String, String> consumer;
45     private final int pollTimeout;
46     private final List<String> consumerTopics;
47
48     /**
49      *
50      * @param configuration The config provided to the client
51      */
52     public OnapKafkaConsumer(IKafkaConfig configuration) {
53         consumerTopics = configuration.getConsumerTopics();
54         log.debug("Instantiating kafka consumer for topics {}", consumerTopics);
55
56         Properties props = new Properties();
57         props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
58         props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,  "org.apache.kafka.common.serialization.StringDeserializer");
59         props.put(ConsumerConfig.CLIENT_ID_CONFIG, configuration.getConsumerID());
60         props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, configuration.getKafkaSecurityProtocolConfig());
61         props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, configuration.getKafkaBootstrapServers());
62         props.put(SaslConfigs.SASL_JAAS_CONFIG, configuration.getKafkaSaslJaasConfig());
63         props.put(SaslConfigs.SASL_MECHANISM, configuration.getKafkaSaslMechanism());
64         props.put(ConsumerConfig.GROUP_ID_CONFIG, configuration.getConsumerGroup());
65         props.put(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG, false);
66         props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
67         props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
68
69         consumer = new KafkaConsumer<>(props);
70
71         pollTimeout = configuration.getPollingTimeout();
72     }
73
74     /**
75      *  Poll specified topic for existing messages
76      *
77      * @return List of messages from a specific topic
78      */
79     List<String> poll(String topicName) throws KafkaException {
80         List<String> msgs = new ArrayList<>();
81         log.debug("Polling records for topic {}", topicName);
82         ConsumerRecords<String, String> consumerRecordsForSpecificTopic = consumer.poll(Duration.ofSeconds(pollTimeout));
83         for(ConsumerRecord<String, String> rec : consumerRecordsForSpecificTopic){
84             if (rec.topic().equals(topicName)) {
85                 msgs.add(rec.value());
86             }
87         }
88         return msgs;
89     }
90
91     /**
92      *  Poll topics for existing messages
93      *
94      * @return List of messages from all subscribed topic
95      */
96     List<String> poll() throws KafkaException {
97         List<String> msgs = new ArrayList<>();
98         log.debug("Polling all records");
99         ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(pollTimeout));
100         for(ConsumerRecord<String, String> rec : consumerRecords){
101             msgs.add(rec.value());
102         }
103         return msgs;
104     }
105
106     public void subscribeConsumerToTopics() {
107         try {
108             consumer.subscribe(consumerTopics);
109         }
110         catch (KafkaException e) {
111             log.error("Failed to subscribe to given topic(s) {} : {}", consumerTopics, e.getMessage());
112             throw e;
113         }
114     }
115 }