Fix sonar issues in messagerouter/msgrtr
[dmaap/messagerouter/msgrtr.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 java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Properties;
29 import org.apache.kafka.clients.producer.KafkaProducer;
30 import org.apache.kafka.clients.producer.Producer;
31 import org.apache.kafka.clients.producer.ProducerRecord;
32 import org.json.JSONException;
33 import org.onap.dmaap.dmf.mr.backends.Publisher;
34 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
35 import org.onap.dmaap.dmf.mr.utils.Utils;
36 import org.springframework.beans.factory.annotation.Qualifier;
37 import org.springframework.util.StringUtils;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import com.att.nsa.drumlin.till.nv.rrNvReadable;
41 import kafka.common.FailedToSendMessageException;
42
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                 transferSetting( props, "sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='admin' password='"+Utils.getKafkaproperty()+"';");
73                 transferSetting( props, "security.protocol", "SASL_PLAINTEXT");
74                 transferSetting( props, "sasl.mechanism", "PLAIN");     
75             }
76                 transferSetting( props, "bootstrap.servers",kafkaConnUrl);
77                         
78                 transferSetting( props, "request.required.acks", "1");
79                 transferSetting( props, "message.send.max.retries", "5");
80                 transferSetting(props, "retry.backoff.ms", "150"); 
81
82                 
83                 
84                 props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
85                 props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
86
87                 
88                 
89                 fProducer = new KafkaProducer<>(props);
90         }
91
92         /**
93          * Send a message with a given topic and key.
94          * 
95          * @param msg
96          * @throws FailedToSendMessageException
97          * @throws JSONException
98          */
99         @Override
100         public void sendMessage(String topic, message msg) throws IOException{
101                 final List<message> msgs = new LinkedList<>();
102                 msgs.add(msg);
103                 sendMessages(topic, msgs);
104         }
105
106         /**  
107          * method publishing batch messages
108         * This method is commented from 0.8 to 0.11 upgrade
109          * @param topic
110          * @param kms
111          * throws IOException
112          *
113         public void sendBatchMessage(String topic, ArrayList<KeyedMessage<String, String>> kms) throws IOException {
114                 try {
115                         fProducer.send(kms);
116
117                 } catch (FailedToSendMessageException excp) { 
118                         log.error("Failed to send message(s) to topic [" + topic + "].", excp);
119                         throw new FailedToSendMessageException(excp.getMessage(), excp);
120                 }
121
122         } */
123
124
125         /*
126          * Kafka 11.0 Interface
127          * @see com.att.nsa.cambria.backends.Publisher#sendBatchMessageNew(java.lang.String, java.util.ArrayList)
128          */
129         public void sendBatchMessageNew(String topic, ArrayList <ProducerRecord<String,String>> kms) throws IOException {
130                 try {
131                         for (ProducerRecord<String,String> km : kms) {
132                                 fProducer.send(km);
133                         }
134
135                 } catch (Exception excp) { 
136                         log.error("Failed to send message(s) to topic [" + topic + "].", excp);
137                         throw new IOException(excp.getMessage(), excp);
138                 }
139
140         }
141         
142         /**
143          * Send a set of messages. Each must have a "key" string value.
144          * 
145          * @param topic
146          * @param msg
147          * @throws FailedToSendMessageException
148          * @throws JSONException
149          *
150         @Override
151         public void sendMessages(String topic, List<? extends message> msgs)
152                         throws IOException, FailedToSendMessageException {
153                 log.info("sending " + msgs.size() + " events to [" + topic + "]");
154
155                 final List<KeyedMessage<String, String>> kms = new ArrayList<KeyedMessage<String, String>>(msgs.size());
156                 for (message o : msgs) {
157                         final KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, o.getKey(), o.toString());
158                         kms.add(data);
159                 }
160                 try {
161                         fProducer.send(kms);
162
163                 } catch (FailedToSendMessageException excp) {
164                         log.error("Failed to send message(s) to topic [" + topic + "].", excp);
165                         throw new FailedToSendMessageException(excp.getMessage(), excp);
166                 }
167         } */
168         @Override
169     public void sendMessagesNew(String topic, List<? extends message> msgs) throws IOException {
170         log.info("sending " + msgs.size() + " events to [" + topic + "]");
171         try {
172             for (message o : msgs) {
173                 final ProducerRecord<String, String> data =
174                         new ProducerRecord<>(topic, o.getKey(), o.toString());
175                 fProducer.send(data);
176             }
177         } catch (Exception e) {
178             log.error("Failed to send message(s) to topic [" + topic + "].", e);
179         }
180     }
181
182         
183         private Producer<String, String> fProducer;
184
185   /**
186    * It sets the key value pair
187    * @param topic
188    * @param msg 
189    * @param key
190    * @param defVal
191    */
192         private void transferSetting(Properties props, String key, String defVal) {
193                 String kafkaProp= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,"kafka." + key);
194                 if (StringUtils.isEmpty(kafkaProp)) kafkaProp=defVal;
195                 props.put(key, kafkaProp);
196         }
197
198         private static final EELFLogger log = EELFManager.getInstance().getLogger(KafkaPublisher.class);
199
200         @Override
201         public void sendMessages(String topic, List<? extends message> msgs) throws IOException {
202                 // TODO Auto-generated method stub
203                 
204         }
205 }