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