Sonar fixes in "appc-dmaap-adapter-bundle"
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / onap / appc / adapter / messaging / dmaap / impl / DmaapProducerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.messaging.dmaap.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.nsa.mr.client.MRBatchingPublisher;
30 import com.att.nsa.mr.client.MRClientFactory;
31 import java.io.IOException;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashSet;
35 import java.util.Properties;
36 import java.util.Set;
37 import java.util.UUID;
38 import java.util.concurrent.TimeUnit;
39 import org.apache.commons.lang3.StringUtils;
40 import org.onap.appc.adapter.message.Producer;
41 import org.onap.appc.configuration.Configuration;
42 import org.onap.appc.configuration.ConfigurationFactory;
43 import org.onap.appc.metricservice.MetricRegistry;
44 import org.onap.appc.metricservice.MetricService;
45 import org.onap.appc.metricservice.metric.DmaapRequestCounterMetric;
46 import org.onap.appc.metricservice.metric.Metric;
47 import org.onap.appc.metricservice.metric.MetricType;
48 import org.onap.appc.metricservice.policy.PublishingPolicy;
49 import org.onap.appc.metricservice.publisher.LogPublisher;
50 import org.osgi.framework.BundleContext;
51 import org.osgi.framework.FrameworkUtil;
52 import org.osgi.framework.ServiceReference;
53
54 public class DmaapProducerImpl implements Producer {
55
56     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(DmaapProducerImpl.class);
57     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
58
59     private Set<String> topics;
60
61     private Properties props = null;
62     private MetricRegistry metricRegistry;
63     private boolean useHttps = false;
64     private boolean isMetricEnabled = false;
65     
66     private Set<MRBatchingPublisher> clients;
67
68     
69     public DmaapProducerImpl(Collection<String> urls, String topicName, String user, String password) {
70         this(urls, (Set<String>)null, user, password);
71         this.topics = new HashSet<>();
72         if (topicName != null) {
73             Collections.addAll(topics, topicName.split(","));
74         }
75     }
76
77     public DmaapProducerImpl(Collection<String> urls, Set<String> topicNames, String user, String password) {
78         topics = topicNames;
79         if (urls == null || user == null || password == null) {
80             throw new IllegalArgumentException("one of these mandaory argument is null: urls, user, password");
81         }
82         this.props = new Properties();
83         String urlsStr = StringUtils.join(urls, ',');
84         props.setProperty("host",urlsStr);
85         props.setProperty("id", UUID.randomUUID().toString());
86         props.setProperty("username",user);
87         props.setProperty("password",password);
88     }
89
90     private void initMetric() {
91         LOG.debug("Metric getting initialized");
92         MetricService metricService = getMetricservice();
93         if (metricService != null) {
94             metricRegistry = metricService.createRegistry("APPC");
95
96             DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
97                 .dmaapRequestCounterBuilder()
98                 .withName("DMAAP_KPI").withType(MetricType.COUNTER)
99                 .withRecievedMessage(0)
100                 .withPublishedMessage(0)
101                 .build();
102
103             if (metricRegistry.register(dmaapKpiMetric)) {
104                 Metric[] metrics = new Metric[]{dmaapKpiMetric};
105                 LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
106                 LogPublisher[] logPublishers = new LogPublisher[1];
107                 logPublishers[0] = logPublisher;
108
109                 PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
110                     .scheduledPolicyBuilder()
111                     .withPublishers(logPublishers)
112                     .withMetrics(metrics)
113                     .build();
114
115                 LOG.debug("Policy getting initialized");
116                 manuallyScheduledPublishingPolicy.init();
117                 LOG.debug("Metric initialized");
118             }
119         }
120     }
121
122     private Set<MRBatchingPublisher> getClients() {
123         Set<MRBatchingPublisher> out = new HashSet<>();
124         for (String topic : topics) {
125             try {
126                 String topicProducerPropFileName = DmaapUtil.createProducerPropFile(topic,props);
127                 final MRBatchingPublisher client = MRClientFactory.createBatchingPublisher(topicProducerPropFileName);
128                 out.add(client);
129             } catch (Exception e) {
130                 LOG.error(e.getMessage(), e);
131             }
132         }
133         return out;
134     }
135
136     @Override
137     public synchronized void updateCredentials(String key, String secret) {
138         LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
139         props.setProperty("user", String.valueOf(key));
140         props.setProperty("password", String.valueOf(secret));
141         clients = null;
142     }
143
144     @Override
145     public boolean post(String partition, String data) {
146         boolean success = true;
147         Properties properties = configuration.getProperties();
148         if (properties != null && properties.getProperty("metric.enabled") != null ) {
149             isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled"));
150         }
151         if (isMetricEnabled) {
152             initMetric();
153         }
154         
155         // Create clients once and reuse them on subsequent posts. This is 
156         // to support failover to other servers in the Dmaap cluster.
157         if ((clients == null) || (clients.isEmpty())) {
158             LOG.info("Getting CambriaBatchingPublisher Clients ...");
159             clients = getClients();
160         }
161         
162         for (MRBatchingPublisher client : clients) {
163             try {
164                 LOG.debug(String.format("Posting %s to %s", data, client));
165                 client.send(partition, data);
166             } catch (IOException e) {
167                 LOG.error(e.getMessage(), e);
168                 success = false;
169             }
170         }
171         incrementPublishedMessage();
172         return success;
173     }
174
175     private void incrementPublishedMessage() {
176         if (isMetricEnabled && metricRegistry != null) {
177             ((DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementPublishedMessage();
178         }
179     }
180
181     /**
182      * Close producer Dmaap client.
183      */
184     @Override
185     public void close() {
186         if ((clients == null) || (clients.isEmpty())) {
187             return;
188         }
189         LOG.debug("Closing Dmaap producer clients....");
190         for (MRBatchingPublisher client : clients) {
191             try {
192                 client.close(1, TimeUnit.SECONDS);
193             }  catch (IOException | InterruptedException e) {
194                 LOG.warn(String.format("Failed to cleanly close Dmaap connection for [%s]", client), e);
195             }
196         }
197     }
198
199     @Override
200     public void useHttps(boolean yes) {
201         useHttps = yes;
202     }
203
204     private MetricService getMetricservice() {
205         BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
206         ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
207         if (sref != null) {
208             LOG.info("Metric Service from bundlecontext");
209             return (MetricService) bctx.getService(sref);
210         } else {
211             LOG.info("Metric Service error from bundlecontext");
212             LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");
213             return null;
214         }
215     }
216
217 }