sonar minor issue for unused import
[dmaap/messagerouter/msgrtr.git] / src / main / java / com / att / nsa / apiServer / metrics / cambria / DMaaPMetricsSender.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.nsa.apiServer.metrics.cambria;
23
24 import java.io.IOException;
25 import java.net.InetAddress;
26 import java.net.UnknownHostException;
27 import java.text.SimpleDateFormat;
28 import java.util.Date;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
32
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 //import org.slf4j.Logger;
36 //import org.slf4j.LoggerFactory;
37
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import com.att.nsa.cambria.constants.CambriaConstants;
41 import com.att.nsa.cambria.metrics.publisher.CambriaPublisher;
42 import com.att.nsa.cambria.metrics.publisher.DMaaPCambriaClientFactory;
43
44 import com.att.nsa.metrics.CdmMetricsRegistry;
45 import com.att.nsa.metrics.impl.CdmConstant;
46
47 /**
48  * MetricsSender will send the given metrics registry content as an event on the
49  * Cambria event broker to the given topic.
50  * 
51  * @author author
52  *
53  */
54 public class DMaaPMetricsSender implements Runnable {
55         public static final String kSetting_CambriaEnabled = "metrics.send.cambria.enabled";
56         public static final String kSetting_CambriaBaseUrl = "metrics.send.cambria.baseUrl";
57         public static final String kSetting_CambriaTopic = "metrics.send.cambria.topic";
58         public static final String kSetting_CambriaSendFreqSecs = "metrics.send.cambria.sendEverySeconds";
59
60         /**
61          * Schedule a periodic send of the given metrics registry using the given
62          * settings container for the Cambria location, topic, and send frequency.
63          * <br/>
64          * <br/>
65          * If the enabled flag is false, this method returns null.
66          * 
67          * @param scheduler
68          * @param metrics
69          * @param settings
70          * @param defaultTopic
71          * @return a handle to the scheduled task
72          */
73         public static ScheduledFuture<?> sendPeriodically(ScheduledExecutorService scheduler, CdmMetricsRegistry metrics,
74                          String defaultTopic) {
75                 log.info("Inside : DMaaPMetricsSender : sendPeriodically");
76         String  cambriaSetting= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaEnabled);
77         boolean setEnable=true;
78         if (cambriaSetting!=null && cambriaSetting.equals("false") )
79         setEnable= false;
80         //System.out.println(setEnable+"XXXXXXXXXXXXXXXX");
81                 if (setEnable) {
82                         String Setting_CambriaBaseUrl=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaEnabled);
83                         
84                         Setting_CambriaBaseUrl=Setting_CambriaBaseUrl==null?"localhost":Setting_CambriaBaseUrl;
85                         
86                         String Setting_CambriaTopic=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaTopic);
87                         if(Setting_CambriaTopic==null) {
88                                 Setting_CambriaTopic = "msgrtr.apinode.metrics.dmaap";   
89                                 }
90                         
91                         
92                         String Setting_CambriaSendFreqSecs=com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,kSetting_CambriaSendFreqSecs);
93                         
94                         int _CambriaSendFreqSecs =30;
95                         if(Setting_CambriaSendFreqSecs!=null){
96                                  _CambriaSendFreqSecs = Integer.parseInt(Setting_CambriaSendFreqSecs);
97                         }
98                         
99
100                         return DMaaPMetricsSender.sendPeriodically(scheduler, metrics,
101                                         Setting_CambriaBaseUrl,Setting_CambriaTopic,_CambriaSendFreqSecs
102                                 );
103                         /*return DMaaPMetricsSender.sendPeriodically(scheduler, metrics,
104                                         settings.getString(kSetting_CambriaBaseUrl, "localhost"),
105                                         settings.getString(kSetting_CambriaTopic, defaultTopic),
106                                         settings.getInt(kSetting_CambriaSendFreqSecs, 30));*/
107                 } else {
108                         return null;
109                 }
110         }
111
112         /**
113          * Schedule a periodic send of the metrics registry to the given Cambria
114          * broker and topic.
115          * 
116          * @param scheduler
117          * @param metrics
118          *            the registry to send
119          * @param cambriaBaseUrl
120          *            the base URL for Cambria
121          * @param topic
122          *            the topic to publish on
123          * @param everySeconds
124          *            how frequently to publish
125          * @return a handle to the scheduled task
126          */
127         public static ScheduledFuture<?> sendPeriodically(ScheduledExecutorService scheduler, CdmMetricsRegistry metrics,
128                         String cambriaBaseUrl, String topic, int everySeconds) {
129                 return scheduler.scheduleAtFixedRate(new DMaaPMetricsSender(metrics, cambriaBaseUrl, topic), everySeconds,
130                                 everySeconds, TimeUnit.SECONDS);
131         }
132
133         /**
134          * Create a metrics sender.
135          * 
136          * @param metrics
137          * @param cambriaBaseUrl
138          * @param topic
139          */
140         public DMaaPMetricsSender(CdmMetricsRegistry metrics, String cambriaBaseUrl, String topic) {
141                 try {
142                         fMetrics = metrics;
143                         fHostname = InetAddress.getLocalHost().getHostName();
144
145                         // setup a "simple" publisher that will send metrics immediately
146                         fCambria = DMaaPCambriaClientFactory.createSimplePublisher(cambriaBaseUrl, topic);
147                 } catch (UnknownHostException e) {
148                         log.warn("Unable to get localhost address in MetricsSender constructor.", e);
149                         throw new IllegalArgumentException(e);
150                 }
151         }
152
153         /**
154          * Send on demand.
155          */
156         public void send() {
157                 try {
158                         final JSONObject o = fMetrics.toJson();
159                         o.put("hostname", fHostname);
160                         o.put("now", System.currentTimeMillis());
161                         o.put("metricsSendTime", addTimeStamp());
162                         o.put("transactionEnabled", false);
163                         fCambria.send(fHostname, o.toString());
164                 } catch (JSONException e) {
165                         log.error("Error posting metrics to Cambria at send(): " + e);
166                 } catch (IOException e) {
167                         log.error("Error posting metrics to Cambria at send(): " + e );
168                 }
169         }
170
171         /**
172          * Run() calls send(). It's meant for use in a background-scheduled task.
173          */
174         @Override
175         public void run() {
176                 send();
177         }
178
179         private final CdmMetricsRegistry fMetrics;
180         private final CambriaPublisher fCambria;
181         private final String fHostname;
182
183         //private static final Logger log = LoggerFactory.getLogger(MetricsSender.class);
184
185         private static final EELFLogger log = EELFManager.getInstance().getLogger(MetricsSender.class);
186         /**
187          * method creates and returnd CdmConstant object using current timestamp
188          * 
189          * @return
190          */
191         public CdmConstant addTimeStamp() {
192                 // Add the timestamp with every metrics send
193                 final long metricsSendTime = System.currentTimeMillis();
194                 final Date d = new Date(metricsSendTime);
195                 final String text = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").format(d);
196                 return new CdmConstant(metricsSendTime / 1000, "Metrics Send Time (epoch); " + text);
197         }
198 }