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