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