4 /*******************************************************************************
5 * ============LICENSE_START=======================================================
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
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=========================================================
22 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 *******************************************************************************/
25 package com.att.nsa.dmaap.mmagent;
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;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35 import javax.ws.rs.core.Context;
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;
47 import com.att.ajsc.filemonitor.AJSCPropertiesMap;
48 import com.att.dmf.mr.CambriaApiException;
49 import com.att.dmf.mr.beans.DMaaPContext;
50 import com.att.dmf.mr.constants.CambriaConstants;
51 import com.att.dmf.mr.exception.DMaaPErrorMessages;
52 import com.att.dmf.mr.exception.DMaaPResponseCode;
53 import com.att.dmf.mr.exception.ErrorResponse;
54 import com.att.dmf.mr.security.DMaaPAAFAuthenticator;
55 import com.att.dmf.mr.security.DMaaPAAFAuthenticatorImpl;
56 import com.att.dmf.mr.service.MMService;
57 import com.att.dmf.mr.utils.ConfigurationReader;
58 import com.att.dmf.mr.utils.DMaaPResponseBuilder;
59 import com.att.dmf.mr.utils.Utils;
60 import com.att.eelf.configuration.EELFLogger;
61 import com.att.eelf.configuration.EELFManager;
62 import edu.emory.mathcs.backport.java.util.Arrays;
65 * @author rajashree.khare
66 *Util class for MM Rest Service
69 public class MMAgentUtil {/*
71 @Qualifier("configurationReader")
72 private ConfigurationReader configReader;
75 private HttpServletRequest request;
78 private HttpServletResponse response;
81 private MMService mirrorService;
85 private String consumergroup;
86 private String consumerid;
87 private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMAgentUtil.class);
89 public JSONObject callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream, String name, boolean listAll) throws Exception {
91 JSONObject jsonObj = new JSONObject();
92 JSONObject finalJsonObj = new JSONObject();
93 JSONArray jsonArray = null;
95 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
96 mirrorService.pushEvents(ctx, topic, inStream, null, null);
97 long startTime = System.currentTimeMillis();
99 while (!isListMirrorMaker(msgFrmSubscribe, randomstr)
100 && ((System.currentTimeMillis() - startTime) < timeout)) {
101 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
106 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
107 && isListMirrorMaker(msgFrmSubscribe, randomstr)) {
108 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
110 jsonArray = new JSONArray(msgFrmSubscribe);
111 jsonObj = jsonArray.getJSONObject(0);
112 if(jsonObj.has("listMirrorMaker"))
114 jsonArray = (JSONArray) jsonObj.get("listMirrorMaker");
121 for (int i = 0; i < jsonArray.length(); i++)
123 jsonObj = jsonArray.getJSONObject(i);
124 if(null!=name && !name.isEmpty())
126 if(jsonObj.getString("name").equals(name))
128 finalJsonObj.put("listMirrorMaker", jsonObj);
134 finalJsonObj.put("listMirrorMaker", jsonObj);
144 ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,
145 DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(),
146 "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null,
147 Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost());
148 LOGGER.info(errRes.toString());
149 throw new CambriaApiException(errRes);
153 } catch (Exception e) {
159 public void sendErrResponse(DMaaPContext ctx, String errMsg) {
160 JSONObject err = new JSONObject();
161 err.append("Error", errMsg);
164 DMaaPResponseBuilder.respondOk(ctx, err);
165 LOGGER.error(errMsg.toString());
167 } catch (JSONException | IOException e) {
168 LOGGER.error(errMsg.toString());
171 public boolean isListMirrorMaker(String msg, String messageID) {
172 String topicmsg = msg;
173 topicmsg = removeExtraChar(topicmsg);
174 JSONObject jObj = new JSONObject();
175 JSONArray jArray = null;
176 boolean exist = false;
178 if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) {
179 jArray = new JSONArray(topicmsg);
181 for (int i = 0; i < jArray.length(); i++) {
182 jObj = jArray.getJSONObject(i);
185 if (jObj.has("messageID") && jObj.get("messageID").equals(messageID) && jObj.has("listMirrorMaker")) {
194 public void loadProperty() {
196 this.timeout = Integer.parseInt(
197 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim());
198 this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim();
199 this.consumergroup = AJSCPropertiesMap
200 .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim();
201 this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid")
207 public String removeExtraChar(String message) {
208 String str = message;
209 str = checkJsonFormate(str);
211 if (str != null && str.length() > 0) {
212 str = str.replace("\\", "");
213 str = str.replace("\"{", "{");
214 str = str.replace("}\"", "}");
219 public String getRandomNum() {
220 long random = Math.round(Math.random() * 89999) + 10000;
221 String strLong = Long.toString(random);
225 public boolean isAlphaNumeric(String name) {
226 String pattern = "^[a-zA-Z0-9]*$";
227 if (name.matches(pattern)) {
233 // This method validate IPv4
234 public boolean validateIPPort(String ipPort) {
235 String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
236 + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):"
237 + "([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])$";
238 if (ipPort.matches(pattern)) {
244 public String checkJsonFormate(String jsonStr) {
246 String json = jsonStr;
247 if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) {
253 public boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) {
255 boolean hasPermission = false;
257 DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl();
259 if (aaf.aafAuthentication(ctx.getRequest(), permission)) {
260 hasPermission = true;
262 return hasPermission;
265 public String getNamespace(String topic) {
266 return topic.substring(0, topic.lastIndexOf("."));
269 public String removeTopic(String whitelist, String topicToRemove) {
270 List<String> topicList = new ArrayList<String>();
271 List<String> newTopicList = new ArrayList<String>();
273 if (whitelist.contains(",")) {
274 topicList = Arrays.asList(whitelist.split(","));
278 if (topicList.contains(topicToRemove)) {
279 for (String topic : topicList) {
280 if (!topic.equals(topicToRemove)) {
281 newTopicList.add(topic);
286 String newWhitelist = StringUtils.join(newTopicList, ",");
291 public void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, JSONObject jsonOb) {
295 String namespace = jsonOb.getString("namespace");
296 String mmName = jsonOb.getString("name");
298 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
299 mirrorService.pushEvents(ctx, topic, inStream, null, null);
300 long startTime = System.currentTimeMillis();
302 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
303 && (System.currentTimeMillis() - startTime) < timeout) {
304 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
307 JSONObject jsonObj = new JSONObject();
308 JSONArray jsonArray = null;
309 JSONArray jsonArrayNamespace = null;
311 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
312 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
313 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
314 jsonArray = new JSONArray(msgFrmSubscribe);
316 for (int i = 0; i < jsonArray.length(); i++) {
317 jsonObj = jsonArray.getJSONObject(i);
320 if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) {
321 jsonArrayNamespace = jsonObj.getJSONArray("listMirrorMaker");
324 JSONObject finalJasonObj = new JSONObject();
325 JSONArray finalJsonArray = new JSONArray();
327 for (int i = 0; i < jsonArrayNamespace.length(); i++) {
329 JSONObject mmObj = new JSONObject();
330 mmObj = jsonArrayNamespace.getJSONObject(i);
331 if(mmObj.has("name")&& mmName.equals(mmObj.getString("name")))
334 finalJsonArray.put(mmObj);
338 finalJasonObj.put("listMirrorMaker", finalJsonArray);
340 DMaaPResponseBuilder.respondOk(ctx, finalJasonObj);
344 ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,
345 DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(),
346 "listMirrorMaker is not available, please make sure MirrorMakerAgent is running", null,
347 Utils.getFormattedDate(new Date()), topic, null, null, "mirrorMakerAgent", ctx.getRequest().getRemoteHost());
348 LOGGER.info(errRes.toString());
349 throw new CambriaApiException(errRes);
352 } catch (Exception e) {
357 public String getWhitelistByNamespace(String originalWhitelist, String namespace) {
359 String whitelist = null;
360 List<String> resultList = new ArrayList<String>();
361 List<String> whitelistList = new ArrayList<String>();
362 whitelistList = Arrays.asList(originalWhitelist.split(","));
364 for (String topic : whitelistList) {
365 if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) {
366 resultList.add(topic);
369 if (resultList.size() > 0) {
370 whitelist = StringUtils.join(resultList, ",");
376 public JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) {
377 JSONObject jsonObj = new JSONObject();
378 JSONArray jsonArray = new JSONArray();
379 JSONArray listMirrorMaker = new JSONArray();
381 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
382 jsonArray = new JSONArray(msgFrmSubscribe);
383 jsonObj = jsonArray.getJSONObject(0);
385 for (int i = 0; i < jsonArray.length(); i++) {
386 jsonObj = jsonArray.getJSONObject(i);
388 if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) {
389 listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker");
393 return listMirrorMaker;
396 public JSONObject validateMMExists(DMaaPContext ctx,String name) throws Exception
398 // Create a listAllMirrorMaker Json object
399 JSONObject listAll = new JSONObject();
401 listAll.put("listAllMirrorMaker", new JSONObject());
403 } catch (JSONException e) {
408 // set a random number as messageID
409 String randomStr = getRandomNum();
410 listAll.put("messageID", randomStr);
411 InputStream inStream = null;
413 // convert listAll Json object to InputStream object
415 inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8");
417 } catch (IOException ioe) {
418 ioe.printStackTrace();
420 JSONObject listMirrorMaker =new JSONObject();
421 listMirrorMaker = callPubSub(randomStr, ctx, inStream, name, false);
422 if (null!=listMirrorMaker && listMirrorMaker.length()>0){
423 listMirrorMaker.put("exists", true);
424 return listMirrorMaker;
427 listMirrorMaker.put("exists", false);
428 return listMirrorMaker;