Possible fix for NoClassDefFoundError
[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-2018 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.messaging.dmaap.impl;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.att.nsa.mr.client.MRBatchingPublisher;
29 import com.att.nsa.mr.client.MRClientFactory;
30 import java.io.IOException;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashSet;
34 import java.util.Properties;
35 import java.util.Set;
36 import java.util.UUID;
37 import java.util.concurrent.TimeUnit;
38 import org.apache.commons.lang3.StringUtils;
39 import org.onap.appc.adapter.message.Producer;
40 import org.onap.appc.adapter.messaging.dmaap.utils.DmaapUtil;
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     public DmaapProducerImpl(Collection<String> urls, String topicName, String user, String password) {
69         this(urls, (Set<String>) null, user, password);
70         this.topics = new HashSet<>();
71         if (topicName != null) {
72             Collections.addAll(topics, topicName.split(","));
73         }
74     }
75
76     public DmaapProducerImpl(Collection<String> urls, Set<String> topicNames, String user, String password) {
77         topics = topicNames;
78         if (urls == null) {
79             throw new IllegalArgumentException("Mandaory argument is null: urls");
80         }
81         this.props = new Properties();
82         String urlsStr = StringUtils.join(urls, ',');
83         props.setProperty("host", urlsStr);
84         props.setProperty("id", UUID.randomUUID().toString());
85         if (user != null && password != null) {
86             props.setProperty("username", user);
87             props.setProperty("password", password);
88         } else {
89             props.setProperty("TransportType", "HTTPNOAUTH");
90         }
91     }
92
93     private void initMetric() {
94         LOG.debug("Metric getting initialized");
95         MetricService metricService = getMetricservice();
96         if (metricService != null) {
97             metricRegistry = metricService.createRegistry("APPC");
98
99             DmaapRequestCounterMetric dmaapKpiMetric = metricRegistry.metricBuilderFactory()
100                     .dmaapRequestCounterBuilder().withName("DMAAP_KPI").withType(MetricType.COUNTER)
101                     .withRecievedMessage(0).withPublishedMessage(0).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().withPublishers(logPublishers).withMetrics(metrics).build();
111
112                 LOG.debug("Policy getting initialized");
113                 manuallyScheduledPublishingPolicy.init();
114                 LOG.debug("Metric initialized");
115             }
116         }
117     }
118
119     private Set<MRBatchingPublisher> getClients() {
120         Set<MRBatchingPublisher> out = new HashSet<>();
121         for (String topic : topics) {
122             try {
123                 String topicProducerPropFileName = DmaapUtil.createProducerPropFile(topic, props);
124                 final MRBatchingPublisher client = MRClientFactory.createBatchingPublisher(topicProducerPropFileName);
125                 out.add(client);
126             } catch (Exception e) {
127                 LOG.error(e.getMessage(), e);
128             }
129         }
130         return out;
131     }
132
133     @Override
134     public synchronized void updateCredentials(String key, String secret) {
135         LOG.info(String.format("Setting auth to %s for %s", key, this.toString()));
136         props.setProperty("username", String.valueOf(key));
137         props.setProperty("password", String.valueOf(secret));
138         clients = null;
139     }
140
141     @Override
142     public boolean post(String partition, String data) {
143         LOG.debug("In DmaapProducerImpl.post()");
144         boolean success = true;
145         Properties properties = configuration.getProperties();
146         if (properties != null && properties.getProperty("metric.enabled") != null) {
147             isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled"));
148         }
149         if (isMetricEnabled) {
150             initMetric();
151         }
152
153         // Create clients once and reuse them on subsequent posts. This is
154         // to support failover to other servers in the Dmaap cluster.
155         if ((clients == null) || (clients.isEmpty())) {
156             LOG.info("Getting CambriaBatchingPublisher Clients ...");
157             clients = getClients();
158         }
159         LOG.debug("In DmaapProducerImpl.post()::: before sending to clients");
160         for (MRBatchingPublisher client : clients) {
161             try {
162                 LOG.debug(String.format("Posting %s to %s", data, client));
163                 client.send(partition, data);
164             } catch (IOException e) {
165                 LOG.error(e.getMessage(), e);
166                 success = false;
167             }
168         }
169         incrementPublishedMessage();
170         return success;
171     }
172
173     private void incrementPublishedMessage() {
174         if (isMetricEnabled && metricRegistry != null) {
175             ((DmaapRequestCounterMetric) metricRegistry.metric("DMAAP_KPI")).incrementPublishedMessage();
176         }
177     }
178
179     /**
180      * Close producer Dmaap client.
181      */
182     @Override
183     public void close() {
184         if ((clients == null) || (clients.isEmpty())) {
185             return;
186         }
187         LOG.debug("Closing Dmaap producer clients....");
188         for (MRBatchingPublisher client : clients) {
189             try {
190                 client.close(1, TimeUnit.SECONDS);
191             } catch (IOException | InterruptedException e) {
192                 LOG.warn(String.format("Failed to cleanly close Dmaap connection for [%s]", client), e);
193             }
194         }
195     }
196
197     @Override
198     public void useHttps(boolean yes) {
199         useHttps = yes;
200     }
201
202     private MetricService getMetricservice() {
203         BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
204         ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
205         if (sref != null) {
206             LOG.info("Metric Service from bundlecontext");
207             return (MetricService) bctx.getService(sref);
208         } else {
209             LOG.info("Metric Service error from bundlecontext");
210             LOG.warn("Cannot find service reference for org.onap.appc.metricservice.MetricService");
211             return null;
212         }
213     }
214
215     public Properties getProperties() {
216         return props;
217     }
218
219     public boolean isHttps() {
220         return useHttps;
221     }
222 }