update the package name
[dmaap/messagerouter/messageservice.git] / src / main / java / org / onap / dmaap / mmagent / MMAgentUtil.java
1 /**
2  * 
3  */
4 /*******************************************************************************
5  *  ============LICENSE_START=======================================================
6  *  org.onap.dmaap
7  *  ================================================================================
8  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
9  *  ================================================================================
10  *  Licensed under the Apache License, Version 2.0 (the "License");
11  *  you may not use this file except in compliance with the License.
12  *  You may obtain a copy of the License at
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  *  ============LICENSE_END=========================================================
21  *  
22  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
23  *  
24  *******************************************************************************/
25  package org.onap.dmaap.mmagent;
26
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.List;
32
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35 import javax.ws.rs.core.Context;
36
37 import org.apache.commons.io.IOUtils;
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.http.HttpStatus;
40 import org.json.JSONArray;
41 import org.json.JSONException;
42 import org.json.JSONObject;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.beans.factory.annotation.Qualifier;
45 import org.springframework.stereotype.Component;
46
47 import com.att.ajsc.filemonitor.AJSCPropertiesMap;
48 import  org.onap.dmaap.dmf.mr.CambriaApiException;
49 import  org.onap.dmaap.dmf.mr.beans.DMaaPContext;
50 import  org.onap.dmaap.dmf.mr.constants.CambriaConstants;
51 import  org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages;
52 import  org.onap.dmaap.dmf.mr.exception.DMaaPResponseCode;
53 import  org.onap.dmaap.dmf.mr.exception.ErrorResponse;
54 import  org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticator;
55 import  org.onap.dmaap.dmf.mr.security.DMaaPAAFAuthenticatorImpl;
56 import  org.onap.dmaap.dmf.mr.service.MMService;
57 import  org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
58 import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder;
59 import  org.onap.dmaap.dmf.mr.utils.Utils;
60 import com.att.eelf.configuration.EELFLogger;
61 import com.att.eelf.configuration.EELFManager;
62
63 /**
64  * @author rajashree.khare
65  *Util class for MM Rest Service
66  */
67 @Component
68 public class MMAgentUtil {/*
69         @Autowired
70         @Qualifier("configurationReader")
71         private ConfigurationReader configReader;
72
73         @Context
74         private HttpServletRequest request;
75
76         @Context
77         private HttpServletResponse response;
78
79         @Autowired
80         private MMService mirrorService;
81
82         private String topic;
83         private int timeout;
84         private String consumergroup;
85         private String consumerid;
86         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMAgentUtil.class);
87                 
88         public JSONObject callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream, String name, boolean listAll) throws Exception {
89                 loadProperty();
90                 JSONObject jsonObj = new JSONObject();
91                 JSONObject finalJsonObj = new JSONObject();
92                 JSONArray jsonArray = null;
93                 try {
94                         String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
95                         mirrorService.pushEvents(ctx, topic, inStream, null, null);
96                         long startTime = System.currentTimeMillis();
97                         
98                         while (!isListMirrorMaker(msgFrmSubscribe, randomstr)
99                                         && ((System.currentTimeMillis() - startTime) < timeout)) {
100                                 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
101                         
102                         }
103                         
104
105                         if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
106                                         && isListMirrorMaker(msgFrmSubscribe, randomstr)) {
107                                 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
108                                 
109                                 jsonArray = new JSONArray(msgFrmSubscribe);
110                                 jsonObj = jsonArray.getJSONObject(0);
111                                 if(jsonObj.has("listMirrorMaker"))
112                                 {
113                                         jsonArray = (JSONArray) jsonObj.get("listMirrorMaker");
114                                         if(true==listAll)
115                                         {
116                                                 return jsonObj;
117                                         } 
118                                         else 
119                                         {
120                                                 for (int i = 0; i < jsonArray.length(); i++) 
121                                                 {
122                                                         jsonObj = jsonArray.getJSONObject(i);
123                                                                 if(null!=name && !name.isEmpty())
124                                                                 {
125                                                                                 if(jsonObj.getString("name").equals(name))
126                                                                                         {
127                                                                                                 finalJsonObj.put("listMirrorMaker", jsonObj);
128                                                                                                 break;
129                                                                                         }
130                                                                 }
131                                                                 else
132                                                                 {
133                                                                         finalJsonObj.put("listMirrorMaker", jsonObj);
134                                                                 }
135                                                 
136                                                 }
137                                         }
138                                 }
139                                 return finalJsonObj;
140
141                         } else {
142
143                                 ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,
144                                                 DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(),
145                                                 "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null,
146                                                 Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost());
147                                 LOGGER.info(errRes.toString());
148                                 throw new CambriaApiException(errRes);
149                                 
150                         }
151                         
152                 } catch (Exception e) {
153                         
154                         throw e;
155                 }
156         }
157
158         public void sendErrResponse(DMaaPContext ctx, String errMsg) {
159                 JSONObject err = new JSONObject();
160                 err.append("Error", errMsg);
161
162                 try {
163                         DMaaPResponseBuilder.respondOk(ctx, err);
164                         LOGGER.error(errMsg.toString());
165
166                 } catch (JSONException | IOException e) {
167                         LOGGER.error(errMsg.toString());
168                 }
169         }
170         public boolean isListMirrorMaker(String msg, String messageID) {
171                 String topicmsg = msg;
172                 topicmsg = removeExtraChar(topicmsg);
173                 JSONObject jObj = new JSONObject();
174                 JSONArray jArray = null;
175                 boolean exist = false;
176
177                 if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) {
178                         jArray = new JSONArray(topicmsg);
179
180                         for (int i = 0; i < jArray.length(); i++) {
181                                 jObj = jArray.getJSONObject(i);
182                                 
183                                 
184                                 if (jObj.has("messageID") && jObj.get("messageID").equals(messageID) && jObj.has("listMirrorMaker")) {
185                                         exist = true;
186                                         break;
187                                 }
188                         }
189                 }
190                 return exist;
191         }
192
193         public void loadProperty() {
194
195                 this.timeout = Integer.parseInt(
196                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim());
197                 this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim();
198                 this.consumergroup = AJSCPropertiesMap
199                                 .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim();
200                 this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid")
201                                 .trim();
202                 
203
204         }
205
206         public String removeExtraChar(String message) {
207                 String str = message;
208                 str = checkJsonFormate(str);
209
210                 if (str != null && str.length() > 0) {
211                         str = str.replace("\\", "");
212                         str = str.replace("\"{", "{");
213                         str = str.replace("}\"", "}");
214                 }
215                 return str;
216         }
217
218         public String getRandomNum() {
219                 long random = Math.round(Math.random() * 89999) + 10000;
220                 String strLong = Long.toString(random);
221                 return strLong;
222         }
223
224         public boolean isAlphaNumeric(String name) {
225                 String pattern = "^[a-zA-Z0-9]*$";
226                 if (name.matches(pattern)) {
227                         return true;
228                 }
229                 return false;
230         }
231
232         // This method validate IPv4
233         public boolean validateIPPort(String ipPort) {
234                 String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
235                                 + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):"
236                                 + "([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$";
237                 if (ipPort.matches(pattern)) {
238                         return true;
239                 }
240                 return false;
241         }
242
243         public String checkJsonFormate(String jsonStr) {
244
245                 String json = jsonStr;
246                 if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) {
247                         json = json + "]";
248                 }
249                 return json;
250         }
251
252         public boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) {
253
254                 boolean hasPermission = false;
255
256                 DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl();
257
258                 if (aaf.aafAuthentication(ctx.getRequest(), permission)) {
259                         hasPermission = true;
260                 }
261                 return hasPermission;
262         }
263         
264         public String getNamespace(String topic) {
265                 return topic.substring(0, topic.lastIndexOf("."));
266         }
267
268         public String removeTopic(String whitelist, String topicToRemove) {
269                 List<String> topicList = new ArrayList<String>();
270                 List<String> newTopicList = new ArrayList<String>();
271
272                 if (whitelist.contains(",")) {
273                         topicList = Arrays.asList(whitelist.split(","));
274
275                 }
276
277                 if (topicList.contains(topicToRemove)) {
278                         for (String topic : topicList) {
279                                 if (!topic.equals(topicToRemove)) {
280                                         newTopicList.add(topic);
281                                 }
282                         }
283                 }
284
285                 String newWhitelist = StringUtils.join(newTopicList, ",");
286
287                 return newWhitelist;
288         }
289
290         public void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, JSONObject jsonOb) {
291                 
292                 loadProperty();
293                 try {
294                         String namespace = jsonOb.getString("namespace");
295                         String mmName = jsonOb.getString("name");
296                         
297                         String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
298                         mirrorService.pushEvents(ctx, topic, inStream, null, null);
299                         long startTime = System.currentTimeMillis();
300
301                         while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
302                                         && (System.currentTimeMillis() - startTime) < timeout) {
303                                 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
304                         }
305                         
306                         JSONObject jsonObj = new JSONObject();
307                         JSONArray jsonArray = null;
308                         JSONArray jsonArrayNamespace = null;
309
310                         if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
311                                         && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
312                                 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
313                                 jsonArray = new JSONArray(msgFrmSubscribe);
314
315                                 for (int i = 0; i < jsonArray.length(); i++) {
316                                         jsonObj = jsonArray.getJSONObject(i);
317                                         
318
319                                         if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) {
320                                                 jsonArrayNamespace = jsonObj.getJSONArray("listMirrorMaker");
321                                         }
322                                 }
323                                 JSONObject finalJasonObj = new JSONObject();
324                                 JSONArray finalJsonArray = new JSONArray();
325
326                                 for (int i = 0; i < jsonArrayNamespace.length(); i++) {
327
328                                         JSONObject mmObj = new JSONObject();
329                                         mmObj = jsonArrayNamespace.getJSONObject(i);
330                                         if(mmObj.has("name")&& mmName.equals(mmObj.getString("name")))
331                                         {
332                                                                                 
333                                                 finalJsonArray.put(mmObj);
334                                         }
335                                         
336                                 }
337                                 finalJasonObj.put("listMirrorMaker", finalJsonArray);
338
339                                 DMaaPResponseBuilder.respondOk(ctx, finalJasonObj);
340
341                         } else {
342
343                                 ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,
344                                                 DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(),
345                                                 "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null,
346                                                 Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost());
347                                 LOGGER.info(errRes.toString());
348                                 throw new CambriaApiException(errRes);
349                         }
350
351                 } catch (Exception e) {
352                         e.printStackTrace();
353                 }
354         }
355
356         public String getWhitelistByNamespace(String originalWhitelist, String namespace) {
357
358                 String whitelist = null;
359                 List<String> resultList = new ArrayList<String>();
360                 List<String> whitelistList = new ArrayList<String>();
361                 whitelistList = Arrays.asList(originalWhitelist.split(","));
362
363                 for (String topic : whitelistList) {
364                         if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) {
365                                 resultList.add(topic);
366                         }
367                 }
368                 if (resultList.size() > 0) {
369                         whitelist = StringUtils.join(resultList, ",");
370                 }
371
372                 return whitelist;
373         }
374         
375         public JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) {
376                 JSONObject jsonObj = new JSONObject();
377                 JSONArray jsonArray = new JSONArray();
378                 JSONArray listMirrorMaker = new JSONArray();
379                 
380                 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
381                 jsonArray = new JSONArray(msgFrmSubscribe);
382                 jsonObj = jsonArray.getJSONObject(0);
383                 
384                 for (int i = 0; i < jsonArray.length(); i++) {
385                         jsonObj = jsonArray.getJSONObject(i);
386                         
387                         if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) {
388                                 listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker");
389                                 break;
390                         }
391                 }
392                 return listMirrorMaker;         
393         }
394         
395         public  JSONObject validateMMExists(DMaaPContext ctx,String name) throws Exception
396         {
397                 // Create a listAllMirrorMaker Json object
398                 JSONObject listAll = new JSONObject();
399                 try {
400                         listAll.put("listAllMirrorMaker", new JSONObject());
401
402                 } catch (JSONException e) {
403
404                         e.printStackTrace();
405                 }
406
407                 // set a random number as messageID
408                 String randomStr = getRandomNum();
409                 listAll.put("messageID", randomStr);
410                 InputStream inStream = null;
411
412                 // convert listAll Json object to InputStream object
413                 try {
414                         inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8");
415
416                 } catch (IOException ioe) {
417                         ioe.printStackTrace();
418                 }
419                 JSONObject listMirrorMaker =new JSONObject();
420                 listMirrorMaker = callPubSub(randomStr, ctx, inStream, name, false);
421                 if (null!=listMirrorMaker && listMirrorMaker.length()>0){
422                         listMirrorMaker.put("exists", true);
423                         return listMirrorMaker;
424                         
425                 }
426                 listMirrorMaker.put("exists", false);
427                 return listMirrorMaker;
428         
429         }
430 */}