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 org.onap.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 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;
64 * @author rajashree.khare
65 *Util class for MM Rest Service
68 public class MMAgentUtil {/*
70 @Qualifier("configurationReader")
71 private ConfigurationReader configReader;
74 private HttpServletRequest request;
77 private HttpServletResponse response;
80 private MMService mirrorService;
84 private String consumergroup;
85 private String consumerid;
86 private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMAgentUtil.class);
88 public JSONObject callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream, String name, boolean listAll) throws Exception {
90 JSONObject jsonObj = new JSONObject();
91 JSONObject finalJsonObj = new JSONObject();
92 JSONArray jsonArray = null;
94 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
95 mirrorService.pushEvents(ctx, topic, inStream, null, null);
96 long startTime = System.currentTimeMillis();
98 while (!isListMirrorMaker(msgFrmSubscribe, randomstr)
99 && ((System.currentTimeMillis() - startTime) < timeout)) {
100 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
105 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
106 && isListMirrorMaker(msgFrmSubscribe, randomstr)) {
107 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
109 jsonArray = new JSONArray(msgFrmSubscribe);
110 jsonObj = jsonArray.getJSONObject(0);
111 if(jsonObj.has("listMirrorMaker"))
113 jsonArray = (JSONArray) jsonObj.get("listMirrorMaker");
120 for (int i = 0; i < jsonArray.length(); i++)
122 jsonObj = jsonArray.getJSONObject(i);
123 if(null!=name && !name.isEmpty())
125 if(jsonObj.getString("name").equals(name))
127 finalJsonObj.put("listMirrorMaker", jsonObj);
133 finalJsonObj.put("listMirrorMaker", jsonObj);
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);
152 } catch (Exception e) {
158 public void sendErrResponse(DMaaPContext ctx, String errMsg) {
159 JSONObject err = new JSONObject();
160 err.append("Error", errMsg);
163 DMaaPResponseBuilder.respondOk(ctx, err);
164 LOGGER.error(errMsg.toString());
166 } catch (JSONException | IOException e) {
167 LOGGER.error(errMsg.toString());
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;
177 if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) {
178 jArray = new JSONArray(topicmsg);
180 for (int i = 0; i < jArray.length(); i++) {
181 jObj = jArray.getJSONObject(i);
184 if (jObj.has("messageID") && jObj.get("messageID").equals(messageID) && jObj.has("listMirrorMaker")) {
193 public void loadProperty() {
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")
206 public String removeExtraChar(String message) {
207 String str = message;
208 str = checkJsonFormate(str);
210 if (str != null && str.length() > 0) {
211 str = str.replace("\\", "");
212 str = str.replace("\"{", "{");
213 str = str.replace("}\"", "}");
218 public String getRandomNum() {
219 long random = Math.round(Math.random() * 89999) + 10000;
220 String strLong = Long.toString(random);
224 public boolean isAlphaNumeric(String name) {
225 String pattern = "^[a-zA-Z0-9]*$";
226 if (name.matches(pattern)) {
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)) {
243 public String checkJsonFormate(String jsonStr) {
245 String json = jsonStr;
246 if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) {
252 public boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) {
254 boolean hasPermission = false;
256 DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl();
258 if (aaf.aafAuthentication(ctx.getRequest(), permission)) {
259 hasPermission = true;
261 return hasPermission;
264 public String getNamespace(String topic) {
265 return topic.substring(0, topic.lastIndexOf("."));
268 public String removeTopic(String whitelist, String topicToRemove) {
269 List<String> topicList = new ArrayList<String>();
270 List<String> newTopicList = new ArrayList<String>();
272 if (whitelist.contains(",")) {
273 topicList = Arrays.asList(whitelist.split(","));
277 if (topicList.contains(topicToRemove)) {
278 for (String topic : topicList) {
279 if (!topic.equals(topicToRemove)) {
280 newTopicList.add(topic);
285 String newWhitelist = StringUtils.join(newTopicList, ",");
290 public void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, JSONObject jsonOb) {
294 String namespace = jsonOb.getString("namespace");
295 String mmName = jsonOb.getString("name");
297 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
298 mirrorService.pushEvents(ctx, topic, inStream, null, null);
299 long startTime = System.currentTimeMillis();
301 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
302 && (System.currentTimeMillis() - startTime) < timeout) {
303 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
306 JSONObject jsonObj = new JSONObject();
307 JSONArray jsonArray = null;
308 JSONArray jsonArrayNamespace = null;
310 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
311 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
312 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
313 jsonArray = new JSONArray(msgFrmSubscribe);
315 for (int i = 0; i < jsonArray.length(); i++) {
316 jsonObj = jsonArray.getJSONObject(i);
319 if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) {
320 jsonArrayNamespace = jsonObj.getJSONArray("listMirrorMaker");
323 JSONObject finalJasonObj = new JSONObject();
324 JSONArray finalJsonArray = new JSONArray();
326 for (int i = 0; i < jsonArrayNamespace.length(); i++) {
328 JSONObject mmObj = new JSONObject();
329 mmObj = jsonArrayNamespace.getJSONObject(i);
330 if(mmObj.has("name")&& mmName.equals(mmObj.getString("name")))
333 finalJsonArray.put(mmObj);
337 finalJasonObj.put("listMirrorMaker", finalJsonArray);
339 DMaaPResponseBuilder.respondOk(ctx, finalJasonObj);
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);
351 } catch (Exception e) {
356 public String getWhitelistByNamespace(String originalWhitelist, String namespace) {
358 String whitelist = null;
359 List<String> resultList = new ArrayList<String>();
360 List<String> whitelistList = new ArrayList<String>();
361 whitelistList = Arrays.asList(originalWhitelist.split(","));
363 for (String topic : whitelistList) {
364 if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) {
365 resultList.add(topic);
368 if (resultList.size() > 0) {
369 whitelist = StringUtils.join(resultList, ",");
375 public JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) {
376 JSONObject jsonObj = new JSONObject();
377 JSONArray jsonArray = new JSONArray();
378 JSONArray listMirrorMaker = new JSONArray();
380 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
381 jsonArray = new JSONArray(msgFrmSubscribe);
382 jsonObj = jsonArray.getJSONObject(0);
384 for (int i = 0; i < jsonArray.length(); i++) {
385 jsonObj = jsonArray.getJSONObject(i);
387 if (jsonObj.has("messageID") && jsonObj.get("messageID").equals(randomStr) && jsonObj.has("listMirrorMaker")) {
388 listMirrorMaker = jsonObj.getJSONArray("listMirrorMaker");
392 return listMirrorMaker;
395 public JSONObject validateMMExists(DMaaPContext ctx,String name) throws Exception
397 // Create a listAllMirrorMaker Json object
398 JSONObject listAll = new JSONObject();
400 listAll.put("listAllMirrorMaker", new JSONObject());
402 } catch (JSONException e) {
407 // set a random number as messageID
408 String randomStr = getRandomNum();
409 listAll.put("messageID", randomStr);
410 InputStream inStream = null;
412 // convert listAll Json object to InputStream object
414 inStream = IOUtils.toInputStream(listAll.toString(), "UTF-8");
416 } catch (IOException ioe) {
417 ioe.printStackTrace();
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;
426 listMirrorMaker.put("exists", false);
427 return listMirrorMaker;