[MR] Add support for configuring jaas.sasl.config at runtime
[dmaap/messagerouter/messageservice.git] / src / main / java / org / onap / dmaap / dmf / mr / backends / kafka / KafkaPublisher.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 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  *        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  *  ============LICENSE_END=========================================================
18  *
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *
21  *******************************************************************************/
22 package org.onap.dmaap.dmf.mr.backends.kafka;
23
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.att.nsa.drumlin.till.nv.rrNvReadable;
27 import org.apache.kafka.clients.admin.AdminClientConfig;
28 import org.apache.kafka.clients.producer.KafkaProducer;
29 import org.apache.kafka.clients.producer.Producer;
30 import org.apache.kafka.clients.producer.ProducerRecord;
31 import org.json.JSONException;
32 import org.onap.dmaap.dmf.mr.backends.Publisher;
33 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
34 import org.onap.dmaap.dmf.mr.utils.Utils;
35 import org.springframework.beans.factory.annotation.Qualifier;
36 import org.springframework.util.StringUtils;
37
38 import java.io.IOException;
39 import java.util.ArrayList;
40 import java.util.LinkedList;
41 import java.util.List;
42 import java.util.Properties;
43
44
45 /**
46  * Sends raw JSON objects into Kafka.
47  *
48  * Could improve space: BSON rather than JSON?
49  *
50  * @author peter
51  *
52  */
53
54 public class KafkaPublisher implements Publisher {
55         /**
56          * constructor initializing
57          *
58          * @param settings
59          * @throws rrNvReadable.missingReqdSetting
60          */
61         public KafkaPublisher(@Qualifier("propertyReader") rrNvReadable settings) throws rrNvReadable.missingReqdSetting {
62
63                 final Properties props = new Properties();
64                 String kafkaConnUrl= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,"kafka.metadata.broker.list");
65                 if(StringUtils.isEmpty(kafkaConnUrl)){
66
67                         kafkaConnUrl="localhost:9092";
68                 }
69
70
71                 if(Utils.isCadiEnabled()){
72                         props.putAll(Utils.addSaslProps());
73                 }
74                 transferSetting( props, "bootstrap.servers",kafkaConnUrl);
75
76                 transferSetting( props, "request.required.acks", "1");
77                 transferSetting( props, "message.send.max.retries", "5");
78                 transferSetting(props, "retry.backoff.ms", "150");
79
80
81
82                 props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
83                 props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
84
85
86
87                 fProducer = new KafkaProducer<>(props);
88         }
89
90         /**
91          * Send a message with a given topic and key.
92          *
93          * @param msg
94          * @throws FailedToSendMessageException
95          * @throws JSONException
96          */
97         @Override
98         public void sendMessage(String topic, message msg) throws IOException{
99                 final List<message> msgs = new LinkedList<>();
100                 msgs.add(msg);
101                 sendMessages(topic, msgs);
102         }
103
104         /**
105          * method publishing batch messages
106          * This method is commented from 0.8 to 0.11 upgrade
107          * @param topic
108          * @param kms
109          * throws IOException
110          *
111         public void sendBatchMessage(String topic, ArrayList<KeyedMessage<String, String>> kms) throws IOException {
112         try {
113         fProducer.send(kms);
114
115         } catch (FailedToSendMessageException excp) {
116         log.error("Failed to send message(s) to topic [" + topic + "].", excp);
117         throw new FailedToSendMessageException(excp.getMessage(), excp);
118         }
119
120         } */
121
122
123         /*
124          * Kafka 11.0 Interface
125          * @see com.att.nsa.cambria.backends.Publisher#sendBatchMessageNew(java.lang.String, java.util.ArrayList)
126          */
127         public void sendBatchMessageNew(String topic, ArrayList <ProducerRecord<String,String>> kms) throws IOException {
128                 try {
129                         for (ProducerRecord<String,String> km : kms) {
130                                 fProducer.send(km);
131                         }
132
133                 } catch (Exception excp) {
134                         log.error("Failed to send message(s) to topic [" + topic + "].", excp);
135                         throw new IOException(excp.getMessage(), excp);
136                 }
137
138         }
139
140         /**
141          * Send a set of messages. Each must have a "key" string value.
142          *
143          * @param topic
144          * @param msg
145          * @throws FailedToSendMessageException
146          * @throws JSONException
147          *
148          @Override
149          public void sendMessages(String topic, List<? extends message> msgs)
150          throws IOException, FailedToSendMessageException {
151          log.info("sending " + msgs.size() + " events to [" + topic + "]");
152
153          final List<KeyedMessage<String, String>> kms = new ArrayList<KeyedMessage<String, String>>(msgs.size());
154          for (message o : msgs) {
155          final KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, o.getKey(), o.toString());
156          kms.add(data);
157          }
158          try {
159          fProducer.send(kms);
160
161          } catch (FailedToSendMessageException excp) {
162          log.error("Failed to send message(s) to topic [" + topic + "].", excp);
163          throw new FailedToSendMessageException(excp.getMessage(), excp);
164          }
165          } */
166         @Override
167         public void sendMessagesNew(String topic, List<? extends message> msgs) throws IOException {
168                 log.info("sending " + msgs.size() + " events to [" + topic + "]");
169                 try {
170                         for (message o : msgs) {
171                                 final ProducerRecord<String, String> data =
172                                                 new ProducerRecord<>(topic, o.getKey(), o.toString());
173                                 fProducer.send(data);
174                         }
175                 } catch (Exception e) {
176                         log.error("Failed to send message(s) to topic [" + topic + "].", e);
177                 }
178         }
179
180
181         private Producer<String, String> fProducer;
182
183         /**
184          * It sets the key value pair
185          * @param topic
186          * @param msg
187          * @param key
188          * @param defVal
189          */
190         private void transferSetting(Properties props, String key, String defVal) {
191                 String kafkaProp= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,"kafka." + key);
192                 if (StringUtils.isEmpty(kafkaProp)) kafkaProp=defVal;
193                 props.put(key, kafkaProp);
194         }
195
196         private static final EELFLogger log = EELFManager.getInstance().getLogger(KafkaPublisher.class);
197
198         @Override
199         public void sendMessages(String topic, List<? extends message> msgs) throws IOException {
200                 // TODO Auto-generated method stub
201
202         }
203 }