Merge "Fix doc8"
[dmaap/messagerouter/messageservice.git] / src / main / java / com / att / nsa / dmaap / service / MMRestService.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.dmaap.service;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Date;
28 import java.util.List;
29
30
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.core.Context;
37 import org.json.JSONObject;
38 import org.apache.commons.io.IOUtils;
39 import org.apache.commons.lang.StringUtils;
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.beans.factory.annotation.Qualifier;
44 import org.springframework.stereotype.Component;
45
46 import com.att.nsa.cambria.utils.ConfigurationReader;
47 import com.att.nsa.cambria.utils.DMaaPResponseBuilder;
48 import com.att.nsa.cambria.utils.Utils;
49 import com.att.nsa.configs.ConfigDbException;
50 import com.att.nsa.dmaap.mmagent.*;
51 import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
52 import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException;
53 import com.google.gson.Gson;
54 import com.google.gson.JsonSyntaxException;
55
56 import edu.emory.mathcs.backport.java.util.Arrays;
57
58 import com.att.ajsc.filemonitor.AJSCPropertiesMap;
59 import com.att.nsa.cambria.CambriaApiException;
60 import com.att.nsa.cambria.backends.ConsumerFactory.UnavailableException;
61
62 import org.json.JSONArray;
63 import org.json.JSONException;
64 import com.att.nsa.cambria.beans.DMaaPContext;
65 import com.att.nsa.cambria.constants.CambriaConstants;
66 import com.att.nsa.cambria.exception.DMaaPErrorMessages;
67 import com.att.nsa.cambria.metabroker.Broker.TopicExistsException;
68 import com.att.nsa.cambria.security.DMaaPAAFAuthenticator;
69 import com.att.nsa.cambria.security.DMaaPAAFAuthenticatorImpl;
70 import com.att.nsa.cambria.service.MMService;
71
72 /**
73  * Rest Service class for Mirror Maker proxy Rest Services
74  * 
75  * @author <a href="mailto:"></a>
76  *
77  * @since May 25, 2016
78  */
79
80 @Component
81 public class MMRestService {
82
83         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MMRestService.class);
84         private static final String NO_ADMIN_PERMISSION = "No Mirror Maker Admin permission.";
85         private static final String NO_USER_PERMISSION = "No Mirror Maker User permission.";
86         private static final String NO_USER_CREATE_PERMISSION = "No Mirror Maker User Create permission.";
87         private static final String NAME_DOES_NOT_MEET_REQUIREMENT = "Mirror Maker name can only contain alpha numeric";
88         private static final String INVALID_IPPORT = "This is not a valid IP:Port";
89         private static final String MIRROR_MAKERADMIN = "msgRtr.mirrormakeradmin.aaf";
90         private static final String MIRROR_MAKERUSER = "msgRtr.mirrormakeruser.aaf";
91         private static final String UTF_8 = "UTF-8";
92         private static final String MESSAGE = "message";
93         private static final String LISTMIRRORMAKER = "listMirrorMaker";
94         private static final String ERROR = "error";
95         private static final String NAMESPACE = "namespace";
96
97         private String topic;
98         private int timeout;
99         private String consumergroup;
100         private String consumerid;
101
102         @Autowired
103         @Qualifier("configurationReader")
104         private ConfigurationReader configReader;
105
106         @Context
107         private HttpServletRequest request;
108
109         @Context
110         private HttpServletResponse response;
111
112         @Autowired
113         private MMService mirrorService;
114
115         @Autowired
116         private DMaaPErrorMessages errorMessages;
117
118         /**
119          * This method is used for taking Configuration Object,HttpServletRequest
120          * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession
121          * Object.
122          * 
123          * @return DMaaPContext object from where user can get Configuration
124          *         Object,HttpServlet Object
125          * 
126          */
127         private DMaaPContext getDmaapContext() {
128                 DMaaPContext dmaapContext = new DMaaPContext();
129                 dmaapContext.setRequest(request);
130                 dmaapContext.setResponse(response);
131                 dmaapContext.setConfigReader(configReader);
132                 dmaapContext.setConsumerRequestTime(Utils.getFormattedDate(new Date()));
133
134                 return dmaapContext;
135         }
136
137         @POST
138         @Produces("application/json")
139         @Path("/create")
140         public void callCreateMirrorMaker(InputStream msg) {
141
142                 DMaaPContext ctx = getDmaapContext();
143                 if (checkMirrorMakerPermission(ctx,
144                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
145
146                         loadProperty();
147                         String input = null;
148                         String randomStr = getRandomNum();
149
150                         InputStream inStream = null;
151                         Gson gson = new Gson();
152                         CreateMirrorMaker createMirrorMaker = new CreateMirrorMaker();
153
154                         try {
155                                 input = IOUtils.toString(msg, UTF_8);
156
157                                 if (input != null && input.length() > 0) {
158                                         input = removeExtraChar(input);
159                                 }
160
161                                 // Check if the request has CreateMirrorMaker
162                                 try {
163                                         createMirrorMaker = gson.fromJson(input, CreateMirrorMaker.class);
164
165                                 } catch (JsonSyntaxException ex) {
166
167                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
168                                         LOGGER.error("JsonSyntaxException: ", ex);
169                                 }
170                                 String name = createMirrorMaker.getCreateMirrorMaker().getName();
171                                 // send error message if it is not a CreateMirrorMaker request.
172                                 if (createMirrorMaker.getCreateMirrorMaker() == null) {
173                                         sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again.");
174                                 }
175
176                                 // MirrorMaker whitelist and status should not be passed
177                                 else if (createMirrorMaker.getCreateMirrorMaker().getWhitelist() != null
178                                                 || createMirrorMaker.getCreateMirrorMaker().getStatus() != null) {
179                                         sendErrResponse(ctx, "This is not a CreateMirrorMaker request. Please try again.");
180                                 }
181                                 
182                                 // if empty, blank name is entered
183                                 else if (StringUtils.isBlank(name)) {
184                                         sendErrResponse(ctx, "Name can not be empty or blank.");
185                                 }
186
187                                 // Check if the name contains only Alpha Numeric
188                                 else if (!isAlphaNumeric(name)) {
189                                         sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT);
190
191                                 }
192
193                                 // Validate the IP and Port
194                                 else if (!StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getConsumer())
195                                                 && !StringUtils.isBlank(createMirrorMaker.getCreateMirrorMaker().getProducer())
196                                                 && !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer())
197                                                 || !validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) {
198                                         sendErrResponse(ctx, INVALID_IPPORT);
199
200                                 }
201                                 // Set a random number as messageID, convert Json Object to
202                                 // InputStream and finally call publisher and subscriber
203                                 else if (isAlphaNumeric(name) && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getConsumer())
204                                                 && validateIPPort(createMirrorMaker.getCreateMirrorMaker().getProducer())) {
205
206                                         createMirrorMaker.setMessageID(randomStr);
207                                         inStream = IOUtils.toInputStream(gson.toJson(createMirrorMaker), UTF_8);
208                                         callPubSub(randomStr, ctx, inStream);
209                                 }
210
211                         } catch (IOException e) {
212
213                                 LOGGER.error("IOException: ", e);
214                         }
215                 }
216                 // Send error response if user does not provide Authorization
217                 else {
218                         sendErrResponse(ctx, NO_ADMIN_PERMISSION);
219                 }
220         }
221
222         @POST
223         @Produces("application/json")
224         @Path("/listall")
225         public void callListAllMirrorMaker(InputStream msg) throws CambriaApiException {
226                 DMaaPContext ctx = getDmaapContext();
227
228                 if (checkMirrorMakerPermission(ctx,
229                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
230
231                         loadProperty();
232
233                         String input = null;
234
235                         try {
236                                 input = IOUtils.toString(msg, UTF_8);
237
238                                 if (input != null && input.length() > 0) {
239                                         input = removeExtraChar(input);
240                                 }
241
242                                 String randomStr = getRandomNum();
243                                 JSONObject jsonOb = null;
244
245                                 try {
246                                         jsonOb = new JSONObject(input);
247
248                                 } catch (JSONException ex) {
249
250                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
251                                         LOGGER.error("JSONException: ", ex);
252                                 }
253
254                                 // Check if request has listAllMirrorMaker and
255                                 // listAllMirrorMaker is empty
256                                 if ((jsonOb != null) && (jsonOb.has("listAllMirrorMaker") &&
257                                     jsonOb.getJSONObject("listAllMirrorMaker").length() == 0)) {
258                                         jsonOb.put("messageID", randomStr);
259                                         InputStream inStream = null;
260
261                                         try {
262                                                 inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8);
263
264                                         } catch (IOException ioe) {
265                                                 LOGGER.error("IOException: ", ioe);
266                                         }
267
268                                         callPubSub(randomStr, ctx, inStream);
269
270                                 } else {
271
272                                         sendErrResponse(ctx, "This is not a ListAllMirrorMaker request. Please try again.");
273                                 }
274
275                         } catch (IOException ioe) {
276
277                                 LOGGER.error("IOException: ", ioe);
278                         }
279
280                 } else {
281
282                         sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION);
283                 }
284         }
285
286         @POST
287         @Produces("application/json")
288         @Path("/update")
289         public void callUpdateMirrorMaker(InputStream msg) throws CambriaApiException {
290
291                 DMaaPContext ctx = getDmaapContext();
292                 if (checkMirrorMakerPermission(ctx,
293                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
294
295                         loadProperty();
296                         String input = null;
297                         String randomStr = getRandomNum();
298
299                         InputStream inStream = null;
300                         Gson gson = new Gson();
301                         UpdateMirrorMaker updateMirrorMaker = new UpdateMirrorMaker();
302
303                         try {
304                                 input = IOUtils.toString(msg, UTF_8);
305
306                                 if (input != null && input.length() > 0) {
307                                         input = removeExtraChar(input);
308                                 }
309
310                                 // Check if the request has UpdateMirrorMaker
311                                 try {
312                                         updateMirrorMaker = gson.fromJson(input, UpdateMirrorMaker.class);
313
314                                 } catch (JsonSyntaxException ex) {
315
316                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
317                                         LOGGER.error("JsonSyntaxException: ", ex);
318
319                                 }
320                                 String name = updateMirrorMaker.getUpdateMirrorMaker().getName();
321
322                                 // send error message if it is not a UpdateMirrorMaker request.
323                                 if (updateMirrorMaker.getUpdateMirrorMaker() == null) {
324                                         sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again.");
325                                 }
326
327                                 // MirrorMaker whitelist and status should not be passed
328                                 else if (updateMirrorMaker.getUpdateMirrorMaker().getWhitelist() != null
329                                                 || updateMirrorMaker.getUpdateMirrorMaker().getStatus() != null) {
330                                         sendErrResponse(ctx, "This is not a UpdateMirrorMaker request. Please try again.");
331                                 }
332                                 
333                                 // if empty, blank name is entered
334                                 else if (StringUtils.isBlank(name)) {
335                                         sendErrResponse(ctx, "Name can not be empty or blank.");
336                                 }
337
338                                 // Check if the name contains only Alpha Numeric
339                                 else if (!isAlphaNumeric(name)) {
340                                         sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT);
341
342                                 }
343
344                                 // Validate the IP and Port
345                                 else if (!StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getConsumer())
346                                                 && !StringUtils.isBlank(updateMirrorMaker.getUpdateMirrorMaker().getProducer())
347                                                 && !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer())
348                                                 || !validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) {
349                                         sendErrResponse(ctx, INVALID_IPPORT);
350
351                                 }
352                                 // Set a random number as messageID, convert Json Object to
353                                 // InputStream and finally call publisher and subscriber
354                                 else if (isAlphaNumeric(name) && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getConsumer())
355                                                 && validateIPPort(updateMirrorMaker.getUpdateMirrorMaker().getProducer())) {
356
357                                         updateMirrorMaker.setMessageID(randomStr);
358                                         inStream = IOUtils.toInputStream(gson.toJson(updateMirrorMaker), UTF_8);
359                                         callPubSub(randomStr, ctx, inStream);
360                                 }
361
362                         } catch (IOException e) {
363
364                                 LOGGER.error("IOException: ", e);
365                         }
366                 }
367                 // Send error response if user does not provide Authorization
368                 else {
369                         sendErrResponse(ctx, NO_ADMIN_PERMISSION);
370                 }
371         }
372
373         @POST
374         @Produces("application/json")
375         @Path("/delete")
376         public void callDeleteMirrorMaker(InputStream msg) throws CambriaApiException {
377                 DMaaPContext ctx = getDmaapContext();
378
379                 if (checkMirrorMakerPermission(ctx,
380                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
381
382                         loadProperty();
383
384                         String input = null;
385
386                         try {
387                                 input = IOUtils.toString(msg, UTF_8);
388
389                                 if (input != null && input.length() > 0) {
390                                         input = removeExtraChar(input);
391                                 }
392
393                                 String randomStr = getRandomNum();
394                                 JSONObject jsonOb = null;
395
396                                 try {
397                                         jsonOb = new JSONObject(input);
398
399                                 } catch (JSONException ex) {
400
401                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
402                                         LOGGER.error("JSONException: ", ex);
403                                 }
404
405                                 // Check if request has DeleteMirrorMaker and
406                                 // DeleteMirrorMaker has MirrorMaker object with name variable
407                                 // and check if the name contain only alpha numeric
408                                 if ((jsonOb != null) && (jsonOb.has("deleteMirrorMaker") 
409                                                 && jsonOb.getJSONObject("deleteMirrorMaker").length() == 1
410                                                 && jsonOb.getJSONObject("deleteMirrorMaker").has("name") 
411                                                 && !StringUtils.isBlank(jsonOb.getJSONObject("deleteMirrorMaker").getString("name"))
412                                                 && isAlphaNumeric(jsonOb.getJSONObject("deleteMirrorMaker").getString("name")))) {
413
414                                         jsonOb.put("messageID", randomStr);
415                                         InputStream inStream = null;
416
417                                         try {
418                                                 inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8);
419
420                                         } catch (IOException ioe) {
421                                                 LOGGER.error("IOException: ", ioe);
422                                         }
423
424                                         callPubSub(randomStr, ctx, inStream);
425
426                                 } else {
427
428                                         sendErrResponse(ctx, "This is not a DeleteMirrorMaker request. Please try again.");
429                                 }
430
431                         } catch (IOException ioe) {
432                                 LOGGER.error("IOException: ", ioe);
433                         }
434
435                 } else {
436
437                         sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION);
438                 }
439         }
440
441         private boolean isListMirrorMaker(String msg, String messageID) {
442                 String topicmsg = msg;
443                 topicmsg = removeExtraChar(topicmsg);
444
445                 JSONObject jObj;
446                 JSONArray jArray;
447                 boolean exist = false;
448
449                 if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) {
450                         jArray = new JSONArray(topicmsg);
451
452                         for (int i = 0; i < jArray.length(); i++) {
453                                 jObj = jArray.getJSONObject(i);
454                                 
455                                 JSONObject obj = new JSONObject();
456                                 if (jObj.has(MESSAGE)) {
457                                         obj = jObj.getJSONObject(MESSAGE);
458                                 }
459                                 if (obj.has("messageID") && obj.get("messageID").equals(messageID) && obj.has(LISTMIRRORMAKER)) {
460                                         exist = true;
461                                         break;
462                                 }
463                         }
464                 }
465                 return exist;
466         }
467
468         private void loadProperty() {
469
470                 this.timeout = Integer.parseInt(
471                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim());
472                 this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim();
473                 this.consumergroup = AJSCPropertiesMap
474                                 .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim();
475                 this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid")
476                                 .trim();
477         }
478
479         private String removeExtraChar(String message) {
480                 String str = message;
481                 str = checkJsonFormate(str);
482
483                 if (str != null && str.length() > 0) {
484                         str = str.replace("\\", "");
485                         str = str.replace("\"{", "{");
486                         str = str.replace("}\"", "}");
487                 }
488                 return str;
489         }
490
491         private String getRandomNum() {
492                 long random = Math.round(Math.random() * 89999) + 10000;
493                 String strLong = Long.toString(random);
494                 return strLong;
495         }
496
497         private boolean isAlphaNumeric(String name) {
498                 String pattern = "^[a-zA-Z0-9]*$";
499                 if (name.matches(pattern)) {
500                         return true;
501                 }
502                 return false;
503         }
504
505         // This method validate IPv4
506         private boolean validateIPPort(String ipPort) {
507                 String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
508                                 + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):"
509                                 + "([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])$";
510                 if (ipPort.matches(pattern)) {
511                         return true;
512                 }
513                 return false;
514         }
515
516         private String checkJsonFormate(String jsonStr) {
517
518                 String json = jsonStr;
519                 if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) {
520                         json = json + "]";
521                 }
522                 return json;
523         }
524
525         private boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) {
526
527                 boolean hasPermission = false;
528
529                 DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl();
530
531                 if (aaf.aafAuthentication(ctx.getRequest(), permission)) {
532                         hasPermission = true;
533                 }
534                 return hasPermission;
535         }
536
537         private void callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream) {
538                 try {
539                         mirrorService.pushEvents(ctx, topic, inStream, null, null);
540                         long startTime = System.currentTimeMillis();
541                         String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
542
543                         while (!isListMirrorMaker(msgFrmSubscribe, randomstr)
544                                         && (System.currentTimeMillis() - startTime) < timeout) {
545                                 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
546                         }
547
548                         JSONObject jsonObj;
549                         JSONObject finalJsonObj = new JSONObject();
550                         JSONArray jsonArray;
551
552                         if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
553                                         && isListMirrorMaker(msgFrmSubscribe, randomstr)) {
554                                 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
555                                 jsonArray = new JSONArray(msgFrmSubscribe);
556
557                                 for (int i = 0; i < jsonArray.length(); i++) {
558                                         jsonObj = jsonArray.getJSONObject(i);
559                                         
560                                         JSONObject obj = new JSONObject();
561                                         if (jsonObj.has(MESSAGE)) {
562                                                 obj = jsonObj.getJSONObject(MESSAGE);
563                                         }
564                                         if (obj.has("messageID") && obj.get("messageID").equals(randomstr) && obj.has(LISTMIRRORMAKER)) {
565                                                 finalJsonObj.put(LISTMIRRORMAKER, obj.get(LISTMIRRORMAKER));
566                                                 break;
567                                         }
568                                 }
569
570                                 DMaaPResponseBuilder.respondOk(ctx, finalJsonObj);
571
572                         } else {
573
574                                 JSONObject err = new JSONObject();
575                                 err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running");
576                                 DMaaPResponseBuilder.respondOk(ctx, err);
577                         }
578
579                 } catch (Exception e) {
580                         LOGGER.error("Exception: ", e);                 
581                 }
582         }
583
584         private void sendErrResponse(DMaaPContext ctx, String errMsg) {
585                 JSONObject err = new JSONObject();
586                 err.append(ERROR, errMsg);
587
588                 try {
589                         DMaaPResponseBuilder.respondOk(ctx, err);
590                         LOGGER.error(errMsg);
591
592                 } catch (JSONException | IOException e) {
593                         LOGGER.error(errMsg);
594                 }
595         }
596
597         @SuppressWarnings("unchecked")
598         @POST
599         @Produces("application/json")
600         @Path("/listallwhitelist")
601         public void listWhiteList(InputStream msg) {
602
603                 DMaaPContext ctx = getDmaapContext();
604                 if (checkMirrorMakerPermission(ctx,
605                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) {
606
607                         loadProperty();
608                         String input = null;
609
610                         try {
611                                 input = IOUtils.toString(msg, UTF_8);
612
613                                 if (input != null && input.length() > 0) {
614                                         input = removeExtraChar(input);
615                                 }
616
617                                 // Check if it is correct Json object
618                                 JSONObject jsonOb = null;
619
620                                 try {
621                                         jsonOb = new JSONObject(input);
622
623                                 } catch (JSONException ex) {
624
625                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
626                                         LOGGER.error("JSONException: ", ex);
627                                 }
628
629                                 // Check if the request has name and name contains only alpha
630                                 // numeric
631                                 // and check if the request has namespace and namespace contains
632                                 // only alpha numeric
633                                 if (jsonOb != null 
634                                                 && jsonOb.length() == 2 && jsonOb.has("name")
635                                                 && !StringUtils.isBlank(jsonOb.getString("name"))
636                                                 && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has(NAMESPACE)
637                                                 && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))) {
638
639                                         String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
640                                                         "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create";
641
642                                         // Check if the user have create permission for the
643                                         // namespace
644                                         if (checkMirrorMakerPermission(ctx, permission)) {
645
646                                                 JSONObject listAll = new JSONObject();
647                                                 JSONObject emptyObject = new JSONObject();
648
649                                                 // Create a listAllMirrorMaker Json object
650                                                 try {
651                                                         listAll.put("listAllMirrorMaker", emptyObject);
652
653                                                 } catch (JSONException e) {
654
655                                                         LOGGER.error("JSONException: ", e);
656                                                 }
657
658                                                 // set a random number as messageID
659                                                 String randomStr = getRandomNum();
660                                                 listAll.put("messageID", randomStr);
661                                                 InputStream inStream = null;
662
663                                                 // convert listAll Json object to InputStream object
664                                                 try {
665                                                         inStream = IOUtils.toInputStream(listAll.toString(), UTF_8);
666
667                                                 } catch (IOException ioe) {
668                                                         LOGGER.error("IOException: ", ioe);
669                                                 }
670                                                 // call listAllMirrorMaker
671                                                 mirrorService.pushEvents(ctx, topic, inStream, null, null);
672
673                                                 // subscribe for listMirrorMaker
674                                                 long startTime = System.currentTimeMillis();
675                                                 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
676
677                                                 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
678                                                                 && (System.currentTimeMillis() - startTime) < timeout) {
679                                                         msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
680                                                 }
681
682                                                 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
683                                                                 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
684                                                         
685                                                         JSONArray listMirrorMaker;
686                                                         listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr);
687
688                                                         String whitelist = null;
689                                                         for (int i = 0; i < listMirrorMaker.length(); i++) {
690
691                                                                 JSONObject mm;
692                                                                 mm = listMirrorMaker.getJSONObject(i);
693                                                                 String name = mm.getString("name");
694
695                                                                 if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) {
696                                                                         whitelist = mm.getString("whitelist");
697                                                                         break;
698                                                                 }
699                                                         }
700
701                                                         if (!StringUtils.isBlank(whitelist)) {
702
703                                                                 List<String> topicList = new ArrayList<>();
704                                                                 List<String> finalTopicList = new ArrayList<>();
705                                                                 topicList = Arrays.asList(whitelist.split(","));
706
707                                                                 for (String topic : topicList) {
708                                                                         if (topic != null && !topic.equals("null")
709                                                                                         && getNamespace(topic).equals(jsonOb.getString(NAMESPACE))) {
710
711                                                                                 finalTopicList.add(topic);
712                                                                         }
713                                                                 }
714
715                                                                 String topicNames = "";
716
717                                                                 if (!finalTopicList.isEmpty()) {
718                                                                         topicNames = StringUtils.join(finalTopicList, ",");
719                                                                 }
720
721                                                                 JSONObject listAllWhiteList = new JSONObject();
722                                                                 listAllWhiteList.put("name", jsonOb.getString("name"));
723                                                                 listAllWhiteList.put("whitelist", topicNames);
724
725                                                                 DMaaPResponseBuilder.respondOk(ctx, listAllWhiteList);
726                                                         }
727
728                                                 } else {
729
730                                                         JSONObject err = new JSONObject();
731                                                         err.append(ERROR,
732                                                                         "listWhiteList is not available, please make sure MirrorMakerAgent is running");
733                                                         DMaaPResponseBuilder.respondOk(ctx, err);
734                                                 }
735
736                                         } else {
737                                                 sendErrResponse(ctx, NO_USER_CREATE_PERMISSION);
738                                         }
739
740                                 } else {
741
742                                         sendErrResponse(ctx, "This is not a ListAllWhitelist request. Please try again.");
743                                 }
744
745                         } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException
746                                         | TopicExistsException | missingReqdSetting | UnavailableException e) {
747
748                                 LOGGER.error("IOException: ", e);
749                         }
750                 } else {
751                         sendErrResponse(ctx, NO_USER_PERMISSION);
752                 }
753         }
754
755         @SuppressWarnings("unchecked")
756         @POST
757         @Produces("application/json")
758         @Path("/createwhitelist")
759         public void createWhiteList(InputStream msg) {
760
761                 DMaaPContext ctx = getDmaapContext();
762                 if (checkMirrorMakerPermission(ctx,
763                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) {
764
765                         loadProperty();
766                         String input = null;
767
768                         try {
769                                 input = IOUtils.toString(msg, UTF_8);
770
771                                 if (input != null && input.length() > 0) {
772                                         input = removeExtraChar(input);
773                                 }
774
775                                 // Check if it is correct Json object
776                                 JSONObject jsonOb = null;
777
778                                 try {
779                                         jsonOb = new JSONObject(input);
780
781                                 } catch (JSONException ex) {
782
783                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
784                                         LOGGER.error("JSONException: ", ex);
785                                 }
786
787                                 // Check if the request has name and name contains only alpha numeric,
788                                 // check if the request has namespace and
789                                 // check if the request has whitelistTopicName
790                                 // check if the topic name contains only alpha numeric
791                                 if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name")
792                                                 && !StringUtils.isBlank(jsonOb.getString("name")) 
793                                                 && isAlphaNumeric(jsonOb.getString("name")) 
794                                                 && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))
795                                                 && jsonOb.has("whitelistTopicName") && !StringUtils.isBlank(jsonOb.getString("whitelistTopicName"))
796                                                 && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring(jsonOb.getString("whitelistTopicName").lastIndexOf(".")+1, 
797                                                                 jsonOb.getString("whitelistTopicName").length()))) {
798
799                                         String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
800                                                         "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create";
801
802                                         // Check if the user have create permission for the
803                                         // namespace
804                                         if (checkMirrorMakerPermission(ctx, permission)) {
805
806                                                 JSONObject listAll = new JSONObject();
807                                                 JSONObject emptyObject = new JSONObject();
808
809                                                 // Create a listAllMirrorMaker Json object
810                                                 try {
811                                                         listAll.put("listAllMirrorMaker", emptyObject);
812
813                                                 } catch (JSONException e) {
814
815                                                         LOGGER.error("JSONException: ", e);
816                                                 }
817
818                                                 // set a random number as messageID
819                                                 String randomStr = getRandomNum();
820                                                 listAll.put("messageID", randomStr);
821                                                 InputStream inStream = null;
822
823                                                 // convert listAll Json object to InputStream object
824                                                 try {
825                                                         inStream = IOUtils.toInputStream(listAll.toString(), UTF_8);
826
827                                                 } catch (IOException ioe) {
828                                                         LOGGER.error("IOException: ", ioe);
829                                                 }
830                                                 // call listAllMirrorMaker
831                                                 mirrorService.pushEvents(ctx, topic, inStream, null, null);
832
833                                                 // subscribe for listMirrorMaker
834                                                 long startTime = System.currentTimeMillis();
835                                                 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
836
837                                                 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
838                                                                 && (System.currentTimeMillis() - startTime) < timeout) {
839                                                         msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
840                                                 }
841
842                                                 JSONArray listMirrorMaker;
843
844                                                 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
845                                                                 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
846                                                         
847                                                         listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr);
848                                                         String whitelist = null;
849
850                                                         for (int i = 0; i < listMirrorMaker.length(); i++) {
851                                                                 JSONObject mm;
852                                                                 mm = listMirrorMaker.getJSONObject(i);
853                                                                 String name = mm.getString("name");
854
855                                                                 if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) {
856                                                                         whitelist = mm.getString("whitelist");
857                                                                         break;
858                                                                 }
859                                                         }
860
861                                                         List<String> topicList = new ArrayList<>();
862                                                         List<String> finalTopicList = new ArrayList<>();
863
864                                                         if (whitelist != null) {
865                                                                 topicList = Arrays.asList(whitelist.split(","));
866                                                         }
867
868                                                         for (String st : topicList) {
869                                                                 if (!StringUtils.isBlank(st)) {
870                                                                         finalTopicList.add(st);
871                                                                 }
872                                                         }
873
874                                                         String newTopic = jsonOb.getString("whitelistTopicName");
875
876                                                         if (!topicList.contains(newTopic)
877                                                                         && getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) {
878
879                                                                 UpdateWhiteList updateWhiteList = new UpdateWhiteList();
880                                                                 MirrorMaker mirrorMaker = new MirrorMaker();
881                                                                 mirrorMaker.setName(jsonOb.getString("name"));
882                                                                 finalTopicList.add(newTopic);
883                                                                 String newWhitelist = "";
884
885                                                                 if (!finalTopicList.isEmpty()) {
886                                                                         newWhitelist = StringUtils.join(finalTopicList, ",");
887                                                                 }
888
889                                                                 mirrorMaker.setWhitelist(newWhitelist);
890
891                                                                 String newRandom = getRandomNum();
892                                                                 updateWhiteList.setMessageID(newRandom);
893                                                                 updateWhiteList.setUpdateWhiteList(mirrorMaker);
894
895                                                                 Gson g = new Gson();
896                                                                 g.toJson(updateWhiteList);
897                                                                 InputStream inputStream;
898                                                                 inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8);
899                                                                 // callPubSub(newRandom, ctx, inputStream);
900                                                                 callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb.getString(NAMESPACE));
901
902                                                         } else if (topicList.contains(newTopic)) {
903                                                                 sendErrResponse(ctx, "The topic already exist.");
904
905                                                         } else if (!getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) {
906                                                                 sendErrResponse(ctx,
907                                                                                 "The namespace of the topic does not match with the namespace you provided.");
908                                                         }
909                                                 } else {
910
911                                                         JSONObject err = new JSONObject();
912                                                         err.append(ERROR,
913                                                                         "listWhiteList is not available, please make sure MirrorMakerAgent is running");
914                                                         DMaaPResponseBuilder.respondOk(ctx, err);
915                                                 }
916
917                                         } else {
918                                                 sendErrResponse(ctx, NO_USER_CREATE_PERMISSION);
919                                         }
920
921                                 } else {
922
923                                         sendErrResponse(ctx, "This is not a createWhitelist request. Please try again.");
924                                 }
925
926                         } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException
927                                         | TopicExistsException | missingReqdSetting | UnavailableException e) {
928
929                                 LOGGER.error("IOException: ", e);
930                         }
931                 }
932                 // Send error response if user does not provide Authorization
933                 else {
934                         sendErrResponse(ctx, NO_USER_PERMISSION);
935                 }
936         }
937
938         @SuppressWarnings("unchecked")
939         @POST
940         @Produces("application/json")
941         @Path("/deletewhitelist")
942         public void deleteWhiteList(InputStream msg) {
943
944                 DMaaPContext ctx = getDmaapContext();
945                 if (checkMirrorMakerPermission(ctx,
946                                 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) {
947
948                         loadProperty();
949                         String input = null;
950
951                         try {
952                                 input = IOUtils.toString(msg, UTF_8);
953
954                                 if (input != null && input.length() > 0) {
955                                         input = removeExtraChar(input);
956                                 }
957
958                                 // Check if it is correct Json object
959                                 JSONObject jsonOb = null;
960
961                                 try {
962                                         jsonOb = new JSONObject(input);
963
964                                 } catch (JSONException ex) {
965
966                                         sendErrResponse(ctx, errorMessages.getIncorrectJson());
967                                         LOGGER.error("JSONException: ", ex);
968                                 }
969
970                                 // Check if the request has name and name contains only alpha numeric,
971                                 // check if the request has namespace and
972                                 // check if the request has whitelistTopicName
973                                 if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") && isAlphaNumeric(jsonOb.getString("name"))
974                                                 && jsonOb.has(NAMESPACE) && jsonOb.has("whitelistTopicName") 
975                                                 && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring(jsonOb.getString("whitelistTopicName").lastIndexOf(".")+1, 
976                                                                 jsonOb.getString("whitelistTopicName").length()))) {
977
978                                         String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
979                                                         "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create";
980
981                                         // Check if the user have create permission for the
982                                         // namespace
983                                         if (checkMirrorMakerPermission(ctx, permission)) {
984
985                                                 JSONObject listAll = new JSONObject();
986                                                 JSONObject emptyObject = new JSONObject();
987
988                                                 // Create a listAllMirrorMaker Json object
989                                                 try {
990                                                         listAll.put("listAllMirrorMaker", emptyObject);
991
992                                                 } catch (JSONException e) {
993
994                                                         LOGGER.error("JSONException: ", e);
995                                                 }
996
997                                                 // set a random number as messageID
998                                                 String randomStr = getRandomNum();
999                                                 listAll.put("messageID", randomStr);
1000                                                 InputStream inStream = null;
1001
1002                                                 // convert listAll Json object to InputStream object
1003                                                 try {
1004                                                         inStream = IOUtils.toInputStream(listAll.toString(), UTF_8);
1005
1006                                                 } catch (IOException ioe) {
1007                                                         LOGGER.error("IOException: ", ioe);
1008                                                 }
1009                                                 // call listAllMirrorMaker
1010                                                 mirrorService.pushEvents(ctx, topic, inStream, null, null);
1011
1012                                                 // subscribe for listMirrorMaker
1013                                                 long startTime = System.currentTimeMillis();
1014                                                 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1015
1016                                                 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
1017                                                                 && (System.currentTimeMillis() - startTime) < timeout) {
1018                                                         msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1019                                                 }
1020
1021                                                 JSONObject jsonObj;
1022                                                 JSONArray jsonArray;
1023                                                 JSONArray listMirrorMaker = null;
1024
1025                                                 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
1026                                                                 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
1027                                                         msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
1028                                                         jsonArray = new JSONArray(msgFrmSubscribe);
1029
1030                                                         for (int i = 0; i < jsonArray.length(); i++) {
1031                                                                 jsonObj = jsonArray.getJSONObject(i);
1032                                                                 
1033                                                                 JSONObject obj = new JSONObject();
1034                                                                 if (jsonObj.has(MESSAGE)) {
1035                                                                         obj = jsonObj.getJSONObject(MESSAGE);
1036                                                                 }
1037                                                                 if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) {
1038                                                                         listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER);
1039                                                                         break;
1040                                                                 }
1041                                                         }
1042                                                         String whitelist = null;
1043                                                         if (listMirrorMaker != null) {
1044                                                                 for (int i = 0; i < listMirrorMaker.length(); i++) {
1045
1046                                                                         JSONObject mm = new JSONObject();
1047                                                                         mm = listMirrorMaker.getJSONObject(i);
1048                                                                         String name = mm.getString("name");
1049
1050                                                                         if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) {
1051                                                                                 whitelist = mm.getString("whitelist");
1052                                                                                 break;
1053                                                                         }
1054                                                                 }
1055                                                         }
1056
1057                                                         List<String> topicList = new ArrayList<>();
1058
1059                                                         if (whitelist != null) {
1060                                                                 topicList = Arrays.asList(whitelist.split(","));
1061                                                         }
1062                                                         boolean removeTopic = false;
1063                                                         String topicToRemove = jsonOb.getString("whitelistTopicName");
1064
1065                                                         if (topicList.contains(topicToRemove)) {
1066                                                                 removeTopic = true;
1067                                                         } else {
1068                                                                 sendErrResponse(ctx, "The topic does not exist.");
1069                                                         }
1070
1071
1072                                                         if (removeTopic) {
1073                                                                 UpdateWhiteList updateWhiteList = new UpdateWhiteList();
1074                                                                 MirrorMaker mirrorMaker = new MirrorMaker();
1075                                                                 
1076                                                                 mirrorMaker.setName(jsonOb.getString("name"));
1077                                                                 mirrorMaker.setWhitelist(removeTopic(whitelist, topicToRemove));
1078                                                         
1079                                                                 String newRandom = getRandomNum();
1080                                                                 
1081                                                                 updateWhiteList.setMessageID(newRandom);
1082                                                                 updateWhiteList.setUpdateWhiteList(mirrorMaker);
1083                                                                 
1084                                                                 Gson g = new Gson();
1085                                                                 g.toJson(updateWhiteList);
1086                                                                 
1087                                                                 InputStream inputStream;
1088                                                                 inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8);
1089                                                                 callPubSubForWhitelist(newRandom, ctx, inputStream, getNamespace(topicToRemove));
1090                                                         }
1091
1092                                                 } else {
1093
1094                                                         JSONObject err = new JSONObject();
1095                                                         err.append(ERROR,
1096                                                                         "listWhiteList is not available, please make sure MirrorMakerAgent is running");
1097                                                         DMaaPResponseBuilder.respondOk(ctx, err);
1098                                                 }
1099
1100                                         } else {
1101                                                 sendErrResponse(ctx, NO_USER_CREATE_PERMISSION);
1102                                         }
1103
1104                                 } else {
1105
1106                                         sendErrResponse(ctx, "This is not a DeleteAllWhitelist request. Please try again.");
1107                                 }
1108
1109                         } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException
1110                                         | TopicExistsException | missingReqdSetting | UnavailableException e) {
1111
1112                                 LOGGER.error("IOException: ", e);
1113                         }
1114                 }
1115                 // Send error response if user does not provide Authorization
1116                 else {
1117                         sendErrResponse(ctx, NO_USER_PERMISSION);
1118                 }
1119         }
1120
1121         private String getNamespace(String topic) {
1122                 return topic.substring(0, topic.lastIndexOf("."));
1123         }
1124
1125         private String removeTopic(String whitelist, String topicToRemove) {
1126                 List<String> topicList = new ArrayList<>();
1127                 List<String> newTopicList = new ArrayList<>();
1128
1129                 if (whitelist.contains(",")) {
1130                         topicList = Arrays.asList(whitelist.split(","));
1131
1132                 }
1133
1134                 if (topicList.contains(topicToRemove)) {
1135                         for (String topic: topicList) {
1136                                 if (!topic.equals(topicToRemove)) {
1137                                         newTopicList.add(topic);
1138                                 }
1139                         }
1140                 }
1141
1142                 String newWhitelist = StringUtils.join(newTopicList, ",");
1143
1144                 return newWhitelist;
1145         }
1146
1147         private void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, String namespace) {
1148                 
1149                 try {
1150                         mirrorService.pushEvents(ctx, topic, inStream, null, null);
1151                         long startTime = System.currentTimeMillis();
1152                         String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1153
1154                         while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
1155                                         && (System.currentTimeMillis() - startTime) < timeout) {
1156                                 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1157                         }
1158
1159                         JSONObject jsonObj;
1160                         JSONArray jsonArray;
1161                         JSONArray jsonArrayNamespace = null;
1162
1163                         if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
1164                                         && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
1165                                 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
1166                                 jsonArray = new JSONArray(msgFrmSubscribe);
1167
1168                                 for (int i = 0; i < jsonArray.length(); i++) {
1169                                         jsonObj = jsonArray.getJSONObject(i);
1170                                         
1171                                         JSONObject obj = new JSONObject();
1172                                         if (jsonObj.has(MESSAGE)) {
1173                                                 obj = jsonObj.getJSONObject(MESSAGE);
1174                                         }
1175                                         if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) {
1176                                                 jsonArrayNamespace = obj.getJSONArray(LISTMIRRORMAKER);
1177                                         }
1178                                 }
1179                                 JSONObject finalJasonObj = new JSONObject();
1180                                 JSONArray finalJsonArray = new JSONArray();
1181
1182                                 for (int i = 0; i < jsonArrayNamespace.length(); i++) {
1183
1184                                         JSONObject mmObj;
1185                                         mmObj = jsonArrayNamespace.getJSONObject(i);
1186                                         String whitelist;
1187
1188                                         if (mmObj.has("whitelist")) {
1189                                                 whitelist = getWhitelistByNamespace(mmObj.getString("whitelist"), namespace);
1190
1191                                                 if (whitelist != null) {
1192                                                         mmObj.remove("whitelist");
1193                                                         mmObj.put("whitelist", whitelist);
1194                                                 } else {
1195                                                         mmObj.remove("whitelist");
1196                                                 }
1197                                         }
1198                                         finalJsonArray.put(mmObj);
1199                                 }
1200                                 finalJasonObj.put(LISTMIRRORMAKER, finalJsonArray);
1201
1202                                 DMaaPResponseBuilder.respondOk(ctx, finalJasonObj);
1203
1204                         } else {
1205
1206                                 JSONObject err = new JSONObject();
1207                                 err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running");
1208                                 DMaaPResponseBuilder.respondOk(ctx, err);
1209                         }
1210
1211                 } catch (Exception e) {
1212                         LOGGER.error("Exception: ", e);
1213                 }
1214         }
1215
1216         private String getWhitelistByNamespace(String originalWhitelist, String namespace) {
1217
1218                 String whitelist = null;
1219                 List<String> resultList = new ArrayList<>();
1220                 List<String> whitelistList = new ArrayList<>();
1221                 whitelistList = Arrays.asList(originalWhitelist.split(","));
1222
1223                 for (String topic : whitelistList) {
1224                         if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) {
1225                                 resultList.add(topic);
1226                         }
1227                 }
1228                 if (!resultList.isEmpty()) {
1229                         whitelist = StringUtils.join(resultList, ",");
1230                 }
1231
1232                 return whitelist;
1233         }
1234         
1235         private JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) {
1236                 JSONObject jsonObj;
1237                 JSONArray jsonArray;
1238                 JSONArray listMirrorMaker = new JSONArray();
1239                 
1240                 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
1241                 jsonArray = new JSONArray(msgFrmSubscribe);
1242
1243                 for (int i = 0; i < jsonArray.length(); i++) {
1244                         jsonObj = jsonArray.getJSONObject(i);
1245                         
1246                         JSONObject obj = new JSONObject();
1247                         if (jsonObj.has(MESSAGE)) {
1248                                 obj = jsonObj.getJSONObject(MESSAGE);
1249                         }
1250                         if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) {
1251                                 listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER);
1252                                 break;
1253                         }
1254                 }
1255                 return listMirrorMaker;         
1256         }
1257 }