1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
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
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=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package com.att.nsa.dmaap.service;
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;
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;
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;
56 import edu.emory.mathcs.backport.java.util.Arrays;
58 import com.att.ajsc.filemonitor.AJSCPropertiesMap;
59 import com.att.nsa.cambria.CambriaApiException;
60 import com.att.nsa.cambria.backends.ConsumerFactory.UnavailableException;
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;
73 * Rest Service class for Mirror Maker proxy Rest Services
75 * @author <a href="mailto:"></a>
81 public class MMRestService {
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";
99 private String consumergroup;
100 private String consumerid;
103 @Qualifier("configurationReader")
104 private ConfigurationReader configReader;
107 private HttpServletRequest request;
110 private HttpServletResponse response;
113 private MMService mirrorService;
116 private DMaaPErrorMessages errorMessages;
119 * This method is used for taking Configuration Object,HttpServletRequest
120 * Object,HttpServletRequest HttpServletResponse Object,HttpServletSession
123 * @return DMaaPContext object from where user can get Configuration
124 * Object,HttpServlet Object
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()));
138 @Produces("application/json")
140 public void callCreateMirrorMaker(InputStream msg) {
142 DMaaPContext ctx = getDmaapContext();
143 if (checkMirrorMakerPermission(ctx,
144 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
148 String randomStr = getRandomNum();
150 InputStream inStream = null;
151 Gson gson = new Gson();
152 CreateMirrorMaker createMirrorMaker = new CreateMirrorMaker();
155 input = IOUtils.toString(msg, UTF_8);
157 if (input != null && input.length() > 0) {
158 input = removeExtraChar(input);
161 // Check if the request has CreateMirrorMaker
163 createMirrorMaker = gson.fromJson(input, CreateMirrorMaker.class);
165 } catch (JsonSyntaxException ex) {
167 sendErrResponse(ctx, errorMessages.getIncorrectJson());
168 LOGGER.error("JsonSyntaxException: ", ex);
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.");
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.");
182 // if empty, blank name is entered
183 else if (StringUtils.isBlank(name)) {
184 sendErrResponse(ctx, "Name can not be empty or blank.");
187 // Check if the name contains only Alpha Numeric
188 else if (!isAlphaNumeric(name)) {
189 sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT);
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);
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())) {
206 createMirrorMaker.setMessageID(randomStr);
207 inStream = IOUtils.toInputStream(gson.toJson(createMirrorMaker), UTF_8);
208 callPubSub(randomStr, ctx, inStream);
211 } catch (IOException e) {
213 LOGGER.error("IOException: ", e);
216 // Send error response if user does not provide Authorization
218 sendErrResponse(ctx, NO_ADMIN_PERMISSION);
223 @Produces("application/json")
225 public void callListAllMirrorMaker(InputStream msg) throws CambriaApiException {
226 DMaaPContext ctx = getDmaapContext();
228 if (checkMirrorMakerPermission(ctx,
229 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
236 input = IOUtils.toString(msg, UTF_8);
238 if (input != null && input.length() > 0) {
239 input = removeExtraChar(input);
242 String randomStr = getRandomNum();
243 JSONObject jsonOb = null;
246 jsonOb = new JSONObject(input);
248 } catch (JSONException ex) {
250 sendErrResponse(ctx, errorMessages.getIncorrectJson());
251 LOGGER.error("JSONException: ", ex);
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;
262 inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8);
264 } catch (IOException ioe) {
265 LOGGER.error("IOException: ", ioe);
268 callPubSub(randomStr, ctx, inStream);
272 sendErrResponse(ctx, "This is not a ListAllMirrorMaker request. Please try again.");
275 } catch (IOException ioe) {
277 LOGGER.error("IOException: ", ioe);
282 sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION);
287 @Produces("application/json")
289 public void callUpdateMirrorMaker(InputStream msg) throws CambriaApiException {
291 DMaaPContext ctx = getDmaapContext();
292 if (checkMirrorMakerPermission(ctx,
293 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
297 String randomStr = getRandomNum();
299 InputStream inStream = null;
300 Gson gson = new Gson();
301 UpdateMirrorMaker updateMirrorMaker = new UpdateMirrorMaker();
304 input = IOUtils.toString(msg, UTF_8);
306 if (input != null && input.length() > 0) {
307 input = removeExtraChar(input);
310 // Check if the request has UpdateMirrorMaker
312 updateMirrorMaker = gson.fromJson(input, UpdateMirrorMaker.class);
314 } catch (JsonSyntaxException ex) {
316 sendErrResponse(ctx, errorMessages.getIncorrectJson());
317 LOGGER.error("JsonSyntaxException: ", ex);
320 String name = updateMirrorMaker.getUpdateMirrorMaker().getName();
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.");
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.");
333 // if empty, blank name is entered
334 else if (StringUtils.isBlank(name)) {
335 sendErrResponse(ctx, "Name can not be empty or blank.");
338 // Check if the name contains only Alpha Numeric
339 else if (!isAlphaNumeric(name)) {
340 sendErrResponse(ctx, NAME_DOES_NOT_MEET_REQUIREMENT);
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);
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())) {
357 updateMirrorMaker.setMessageID(randomStr);
358 inStream = IOUtils.toInputStream(gson.toJson(updateMirrorMaker), UTF_8);
359 callPubSub(randomStr, ctx, inStream);
362 } catch (IOException e) {
364 LOGGER.error("IOException: ", e);
367 // Send error response if user does not provide Authorization
369 sendErrResponse(ctx, NO_ADMIN_PERMISSION);
374 @Produces("application/json")
376 public void callDeleteMirrorMaker(InputStream msg) throws CambriaApiException {
377 DMaaPContext ctx = getDmaapContext();
379 if (checkMirrorMakerPermission(ctx,
380 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERADMIN))) {
387 input = IOUtils.toString(msg, UTF_8);
389 if (input != null && input.length() > 0) {
390 input = removeExtraChar(input);
393 String randomStr = getRandomNum();
394 JSONObject jsonOb = null;
397 jsonOb = new JSONObject(input);
399 } catch (JSONException ex) {
401 sendErrResponse(ctx, errorMessages.getIncorrectJson());
402 LOGGER.error("JSONException: ", ex);
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")))) {
414 jsonOb.put("messageID", randomStr);
415 InputStream inStream = null;
418 inStream = IOUtils.toInputStream(jsonOb.toString(), UTF_8);
420 } catch (IOException ioe) {
421 LOGGER.error("IOException: ", ioe);
424 callPubSub(randomStr, ctx, inStream);
428 sendErrResponse(ctx, "This is not a DeleteMirrorMaker request. Please try again.");
431 } catch (IOException ioe) {
433 ioe.printStackTrace();
434 LOGGER.error("IOException: ", ioe);
439 sendErrResponse(getDmaapContext(), NO_ADMIN_PERMISSION);
443 private boolean isListMirrorMaker(String msg, String messageID) {
444 String topicmsg = msg;
445 topicmsg = removeExtraChar(topicmsg);
449 boolean exist = false;
451 if (!StringUtils.isBlank(topicmsg) && topicmsg.length() > 2) {
452 jArray = new JSONArray(topicmsg);
454 for (int i = 0; i < jArray.length(); i++) {
455 jObj = jArray.getJSONObject(i);
457 JSONObject obj = new JSONObject();
458 if (jObj.has(MESSAGE)) {
459 obj = jObj.getJSONObject(MESSAGE);
461 if (obj.has("messageID") && obj.get("messageID").equals(messageID) && obj.has(LISTMIRRORMAKER)) {
470 private void loadProperty() {
472 this.timeout = Integer.parseInt(
473 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.timeout").trim());
474 this.topic = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.topic").trim();
475 this.consumergroup = AJSCPropertiesMap
476 .getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumergroup").trim();
477 this.consumerid = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "msgRtr.mirrormaker.consumerid")
481 private String removeExtraChar(String message) {
482 String str = message;
483 str = checkJsonFormate(str);
485 if (str != null && str.length() > 0) {
486 str = str.replace("\\", "");
487 str = str.replace("\"{", "{");
488 str = str.replace("}\"", "}");
493 private String getRandomNum() {
494 long random = Math.round(Math.random() * 89999) + 10000;
495 String strLong = Long.toString(random);
499 private boolean isAlphaNumeric(String name) {
500 String pattern = "^[a-zA-Z0-9]*$";
501 if (name.matches(pattern)) {
507 // This method validate IPv4
508 private boolean validateIPPort(String ipPort) {
509 String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
510 + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5]):"
511 + "([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])$";
512 if (ipPort.matches(pattern)) {
518 private String checkJsonFormate(String jsonStr) {
520 String json = jsonStr;
521 if (jsonStr != null && jsonStr.length() > 0 && jsonStr.startsWith("[") && !jsonStr.endsWith("]")) {
527 private boolean checkMirrorMakerPermission(DMaaPContext ctx, String permission) {
529 boolean hasPermission = false;
531 DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl();
533 if (aaf.aafAuthentication(ctx.getRequest(), permission)) {
534 hasPermission = true;
536 return hasPermission;
539 private void callPubSub(String randomstr, DMaaPContext ctx, InputStream inStream) {
541 mirrorService.pushEvents(ctx, topic, inStream, null, null);
542 long startTime = System.currentTimeMillis();
543 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
545 while (!isListMirrorMaker(msgFrmSubscribe, randomstr)
546 && (System.currentTimeMillis() - startTime) < timeout) {
547 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
551 JSONObject finalJsonObj = new JSONObject();
554 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
555 && isListMirrorMaker(msgFrmSubscribe, randomstr)) {
556 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
557 jsonArray = new JSONArray(msgFrmSubscribe);
559 for (int i = 0; i < jsonArray.length(); i++) {
560 jsonObj = jsonArray.getJSONObject(i);
562 JSONObject obj = new JSONObject();
563 if (jsonObj.has(MESSAGE)) {
564 obj = jsonObj.getJSONObject(MESSAGE);
566 if (obj.has("messageID") && obj.get("messageID").equals(randomstr) && obj.has(LISTMIRRORMAKER)) {
567 finalJsonObj.put(LISTMIRRORMAKER, obj.get(LISTMIRRORMAKER));
572 DMaaPResponseBuilder.respondOk(ctx, finalJsonObj);
576 JSONObject err = new JSONObject();
577 err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running");
578 DMaaPResponseBuilder.respondOk(ctx, err);
581 } catch (Exception e) {
582 LOGGER.error("Exception: ", e);
586 private void sendErrResponse(DMaaPContext ctx, String errMsg) {
587 JSONObject err = new JSONObject();
588 err.append(ERROR, errMsg);
591 DMaaPResponseBuilder.respondOk(ctx, err);
592 LOGGER.error(errMsg);
594 } catch (JSONException | IOException e) {
595 LOGGER.error(errMsg);
599 @SuppressWarnings("unchecked")
601 @Produces("application/json")
602 @Path("/listallwhitelist")
603 public void listWhiteList(InputStream msg) {
605 DMaaPContext ctx = getDmaapContext();
606 if (checkMirrorMakerPermission(ctx,
607 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) {
613 input = IOUtils.toString(msg, UTF_8);
615 if (input != null && input.length() > 0) {
616 input = removeExtraChar(input);
619 // Check if it is correct Json object
620 JSONObject jsonOb = null;
623 jsonOb = new JSONObject(input);
625 } catch (JSONException ex) {
627 sendErrResponse(ctx, errorMessages.getIncorrectJson());
628 LOGGER.error("JSONException: ", ex);
631 // Check if the request has name and name contains only alpha
633 // and check if the request has namespace and namespace contains
634 // only alpha numeric
636 && jsonOb.length() == 2 && jsonOb.has("name")
637 && !StringUtils.isBlank(jsonOb.getString("name"))
638 && isAlphaNumeric(jsonOb.getString("name")) && jsonOb.has(NAMESPACE)
639 && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))) {
641 String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
642 "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create";
644 // Check if the user have create permission for the
646 if (checkMirrorMakerPermission(ctx, permission)) {
648 JSONObject listAll = new JSONObject();
649 JSONObject emptyObject = new JSONObject();
651 // Create a listAllMirrorMaker Json object
653 listAll.put("listAllMirrorMaker", emptyObject);
655 } catch (JSONException e) {
657 LOGGER.error("JSONException: ", e);
660 // set a random number as messageID
661 String randomStr = getRandomNum();
662 listAll.put("messageID", randomStr);
663 InputStream inStream = null;
665 // convert listAll Json object to InputStream object
667 inStream = IOUtils.toInputStream(listAll.toString(), UTF_8);
669 } catch (IOException ioe) {
670 LOGGER.error("IOException: ", ioe);
672 // call listAllMirrorMaker
673 mirrorService.pushEvents(ctx, topic, inStream, null, null);
675 // subscribe for listMirrorMaker
676 long startTime = System.currentTimeMillis();
677 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
679 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
680 && (System.currentTimeMillis() - startTime) < timeout) {
681 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
684 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
685 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
687 JSONArray listMirrorMaker;
688 listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr);
690 String whitelist = null;
691 for (int i = 0; i < listMirrorMaker.length(); i++) {
694 mm = listMirrorMaker.getJSONObject(i);
695 String name = mm.getString("name");
697 if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) {
698 whitelist = mm.getString("whitelist");
703 if (!StringUtils.isBlank(whitelist)) {
705 List<String> topicList = new ArrayList<>();
706 List<String> finalTopicList = new ArrayList<>();
707 topicList = Arrays.asList(whitelist.split(","));
709 for (String topic : topicList) {
710 if (topic != null && !topic.equals("null")
711 && getNamespace(topic).equals(jsonOb.getString(NAMESPACE))) {
713 finalTopicList.add(topic);
717 String topicNames = "";
719 if (!finalTopicList.isEmpty()) {
720 topicNames = StringUtils.join(finalTopicList, ",");
723 JSONObject listAllWhiteList = new JSONObject();
724 listAllWhiteList.put("name", jsonOb.getString("name"));
725 listAllWhiteList.put("whitelist", topicNames);
727 DMaaPResponseBuilder.respondOk(ctx, listAllWhiteList);
732 JSONObject err = new JSONObject();
734 "listWhiteList is not available, please make sure MirrorMakerAgent is running");
735 DMaaPResponseBuilder.respondOk(ctx, err);
739 sendErrResponse(ctx, NO_USER_CREATE_PERMISSION);
744 sendErrResponse(ctx, "This is not a ListAllWhitelist request. Please try again.");
747 } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException
748 | TopicExistsException | missingReqdSetting | UnavailableException e) {
750 LOGGER.error("IOException: ", e);
753 sendErrResponse(ctx, NO_USER_PERMISSION);
757 @SuppressWarnings("unchecked")
759 @Produces("application/json")
760 @Path("/createwhitelist")
761 public void createWhiteList(InputStream msg) {
763 DMaaPContext ctx = getDmaapContext();
764 if (checkMirrorMakerPermission(ctx,
765 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) {
771 input = IOUtils.toString(msg, UTF_8);
773 if (input != null && input.length() > 0) {
774 input = removeExtraChar(input);
777 // Check if it is correct Json object
778 JSONObject jsonOb = null;
781 jsonOb = new JSONObject(input);
783 } catch (JSONException ex) {
785 sendErrResponse(ctx, errorMessages.getIncorrectJson());
786 LOGGER.error("JSONException: ", ex);
789 // Check if the request has name and name contains only alpha numeric,
790 // check if the request has namespace and
791 // check if the request has whitelistTopicName
792 // check if the topic name contains only alpha numeric
793 if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name")
794 && !StringUtils.isBlank(jsonOb.getString("name"))
795 && isAlphaNumeric(jsonOb.getString("name"))
796 && jsonOb.has(NAMESPACE) && !StringUtils.isBlank(jsonOb.getString(NAMESPACE))
797 && jsonOb.has("whitelistTopicName") && !StringUtils.isBlank(jsonOb.getString("whitelistTopicName"))
798 && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring(jsonOb.getString("whitelistTopicName").lastIndexOf(".")+1,
799 jsonOb.getString("whitelistTopicName").length()))) {
801 String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
802 "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create";
804 // Check if the user have create permission for the
806 if (checkMirrorMakerPermission(ctx, permission)) {
808 JSONObject listAll = new JSONObject();
809 JSONObject emptyObject = new JSONObject();
811 // Create a listAllMirrorMaker Json object
813 listAll.put("listAllMirrorMaker", emptyObject);
815 } catch (JSONException e) {
817 LOGGER.error("JSONException: ", e);
820 // set a random number as messageID
821 String randomStr = getRandomNum();
822 listAll.put("messageID", randomStr);
823 InputStream inStream = null;
825 // convert listAll Json object to InputStream object
827 inStream = IOUtils.toInputStream(listAll.toString(), UTF_8);
829 } catch (IOException ioe) {
830 ioe.printStackTrace();
831 LOGGER.error("IOException: ", ioe);
833 // call listAllMirrorMaker
834 mirrorService.pushEvents(ctx, topic, inStream, null, null);
836 // subscribe for listMirrorMaker
837 long startTime = System.currentTimeMillis();
838 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
840 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
841 && (System.currentTimeMillis() - startTime) < timeout) {
842 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
845 JSONArray listMirrorMaker;
847 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
848 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
850 listMirrorMaker = getListMirrorMaker(msgFrmSubscribe, randomStr);
851 String whitelist = null;
853 for (int i = 0; i < listMirrorMaker.length(); i++) {
855 mm = listMirrorMaker.getJSONObject(i);
856 String name = mm.getString("name");
858 if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) {
859 whitelist = mm.getString("whitelist");
864 List<String> topicList = new ArrayList<>();
865 List<String> finalTopicList = new ArrayList<>();
867 if (whitelist != null) {
868 topicList = Arrays.asList(whitelist.split(","));
871 for (String st : topicList) {
872 if (!StringUtils.isBlank(st)) {
873 finalTopicList.add(st);
877 String newTopic = jsonOb.getString("whitelistTopicName");
879 if (!topicList.contains(newTopic)
880 && getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) {
882 UpdateWhiteList updateWhiteList = new UpdateWhiteList();
883 MirrorMaker mirrorMaker = new MirrorMaker();
884 mirrorMaker.setName(jsonOb.getString("name"));
885 finalTopicList.add(newTopic);
886 String newWhitelist = "";
888 if (!finalTopicList.isEmpty()) {
889 newWhitelist = StringUtils.join(finalTopicList, ",");
892 mirrorMaker.setWhitelist(newWhitelist);
894 String newRandom = getRandomNum();
895 updateWhiteList.setMessageID(newRandom);
896 updateWhiteList.setUpdateWhiteList(mirrorMaker);
899 g.toJson(updateWhiteList);
900 InputStream inputStream;
901 inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8);
902 // callPubSub(newRandom, ctx, inputStream);
903 callPubSubForWhitelist(newRandom, ctx, inputStream, jsonOb.getString(NAMESPACE));
905 } else if (topicList.contains(newTopic)) {
906 sendErrResponse(ctx, "The topic already exist.");
908 } else if (!getNamespace(newTopic).equals(jsonOb.getString(NAMESPACE))) {
910 "The namespace of the topic does not match with the namespace you provided.");
914 JSONObject err = new JSONObject();
916 "listWhiteList is not available, please make sure MirrorMakerAgent is running");
917 DMaaPResponseBuilder.respondOk(ctx, err);
921 sendErrResponse(ctx, NO_USER_CREATE_PERMISSION);
926 sendErrResponse(ctx, "This is not a createWhitelist request. Please try again.");
929 } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException
930 | TopicExistsException | missingReqdSetting | UnavailableException e) {
932 LOGGER.error("IOException: ", e);
935 // Send error response if user does not provide Authorization
937 sendErrResponse(ctx, NO_USER_PERMISSION);
941 @SuppressWarnings("unchecked")
943 @Produces("application/json")
944 @Path("/deletewhitelist")
945 public void deleteWhiteList(InputStream msg) {
947 DMaaPContext ctx = getDmaapContext();
948 if (checkMirrorMakerPermission(ctx,
949 AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, MIRROR_MAKERUSER))) {
955 input = IOUtils.toString(msg, UTF_8);
957 if (input != null && input.length() > 0) {
958 input = removeExtraChar(input);
961 // Check if it is correct Json object
962 JSONObject jsonOb = null;
965 jsonOb = new JSONObject(input);
967 } catch (JSONException ex) {
969 sendErrResponse(ctx, errorMessages.getIncorrectJson());
970 LOGGER.error("JSONException: ", ex);
973 // Check if the request has name and name contains only alpha numeric,
974 // check if the request has namespace and
975 // check if the request has whitelistTopicName
976 if (jsonOb != null && jsonOb.length() == 3 && jsonOb.has("name") && isAlphaNumeric(jsonOb.getString("name"))
977 && jsonOb.has(NAMESPACE) && jsonOb.has("whitelistTopicName")
978 && isAlphaNumeric(jsonOb.getString("whitelistTopicName").substring(jsonOb.getString("whitelistTopicName").lastIndexOf(".")+1,
979 jsonOb.getString("whitelistTopicName").length()))) {
981 String permission = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,
982 "msgRtr.mirrormakeruser.aaf.create") + jsonOb.getString(NAMESPACE) + "|create";
984 // Check if the user have create permission for the
986 if (checkMirrorMakerPermission(ctx, permission)) {
988 JSONObject listAll = new JSONObject();
989 JSONObject emptyObject = new JSONObject();
991 // Create a listAllMirrorMaker Json object
993 listAll.put("listAllMirrorMaker", emptyObject);
995 } catch (JSONException e) {
997 LOGGER.error("JSONException: ", e);
1000 // set a random number as messageID
1001 String randomStr = getRandomNum();
1002 listAll.put("messageID", randomStr);
1003 InputStream inStream = null;
1005 // convert listAll Json object to InputStream object
1007 inStream = IOUtils.toInputStream(listAll.toString(), UTF_8);
1009 } catch (IOException ioe) {
1010 LOGGER.error("IOException: ", ioe);
1012 // call listAllMirrorMaker
1013 mirrorService.pushEvents(ctx, topic, inStream, null, null);
1015 // subscribe for listMirrorMaker
1016 long startTime = System.currentTimeMillis();
1017 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1019 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
1020 && (System.currentTimeMillis() - startTime) < timeout) {
1021 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1025 JSONArray jsonArray;
1026 JSONArray listMirrorMaker = null;
1028 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
1029 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
1030 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
1031 jsonArray = new JSONArray(msgFrmSubscribe);
1033 for (int i = 0; i < jsonArray.length(); i++) {
1034 jsonObj = jsonArray.getJSONObject(i);
1036 JSONObject obj = new JSONObject();
1037 if (jsonObj.has(MESSAGE)) {
1038 obj = jsonObj.getJSONObject(MESSAGE);
1040 if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) {
1041 listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER);
1045 String whitelist = null;
1046 if (listMirrorMaker != null) {
1047 for (int i = 0; i < listMirrorMaker.length(); i++) {
1049 JSONObject mm = new JSONObject();
1050 mm = listMirrorMaker.getJSONObject(i);
1051 String name = mm.getString("name");
1053 if (name.equals(jsonOb.getString("name")) && mm.has("whitelist")) {
1054 whitelist = mm.getString("whitelist");
1060 List<String> topicList = new ArrayList<>();
1062 if (whitelist != null) {
1063 topicList = Arrays.asList(whitelist.split(","));
1065 boolean removeTopic = false;
1066 String topicToRemove = jsonOb.getString("whitelistTopicName");
1068 if (topicList.contains(topicToRemove)) {
1071 sendErrResponse(ctx, "The topic does not exist.");
1076 UpdateWhiteList updateWhiteList = new UpdateWhiteList();
1077 MirrorMaker mirrorMaker = new MirrorMaker();
1079 mirrorMaker.setName(jsonOb.getString("name"));
1080 mirrorMaker.setWhitelist(removeTopic(whitelist, topicToRemove));
1082 String newRandom = getRandomNum();
1084 updateWhiteList.setMessageID(newRandom);
1085 updateWhiteList.setUpdateWhiteList(mirrorMaker);
1087 Gson g = new Gson();
1088 g.toJson(updateWhiteList);
1090 InputStream inputStream;
1091 inputStream = IOUtils.toInputStream(g.toJson(updateWhiteList), UTF_8);
1092 callPubSubForWhitelist(newRandom, ctx, inputStream, getNamespace(topicToRemove));
1097 JSONObject err = new JSONObject();
1099 "listWhiteList is not available, please make sure MirrorMakerAgent is running");
1100 DMaaPResponseBuilder.respondOk(ctx, err);
1104 sendErrResponse(ctx, NO_USER_CREATE_PERMISSION);
1109 sendErrResponse(ctx, "This is not a DeleteAllWhitelist request. Please try again.");
1112 } catch (IOException | CambriaApiException | ConfigDbException | AccessDeniedException
1113 | TopicExistsException | missingReqdSetting | UnavailableException e) {
1115 LOGGER.error("IOException: ", e);
1118 // Send error response if user does not provide Authorization
1120 sendErrResponse(ctx, NO_USER_PERMISSION);
1124 private String getNamespace(String topic) {
1125 return topic.substring(0, topic.lastIndexOf("."));
1128 private String removeTopic(String whitelist, String topicToRemove) {
1129 List<String> topicList = new ArrayList<>();
1130 List<String> newTopicList = new ArrayList<>();
1132 if (whitelist.contains(",")) {
1133 topicList = Arrays.asList(whitelist.split(","));
1137 if (topicList.contains(topicToRemove)) {
1138 for (String topic: topicList) {
1139 if (!topic.equals(topicToRemove)) {
1140 newTopicList.add(topic);
1145 String newWhitelist = StringUtils.join(newTopicList, ",");
1147 return newWhitelist;
1150 private void callPubSubForWhitelist(String randomStr, DMaaPContext ctx, InputStream inStream, String namespace) {
1153 mirrorService.pushEvents(ctx, topic, inStream, null, null);
1154 long startTime = System.currentTimeMillis();
1155 String msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1157 while (!isListMirrorMaker(msgFrmSubscribe, randomStr)
1158 && (System.currentTimeMillis() - startTime) < timeout) {
1159 msgFrmSubscribe = mirrorService.subscribe(ctx, topic, consumergroup, consumerid);
1163 JSONArray jsonArray;
1164 JSONArray jsonArrayNamespace = null;
1166 if (msgFrmSubscribe != null && msgFrmSubscribe.length() > 0
1167 && isListMirrorMaker(msgFrmSubscribe, randomStr)) {
1168 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
1169 jsonArray = new JSONArray(msgFrmSubscribe);
1171 for (int i = 0; i < jsonArray.length(); i++) {
1172 jsonObj = jsonArray.getJSONObject(i);
1174 JSONObject obj = new JSONObject();
1175 if (jsonObj.has(MESSAGE)) {
1176 obj = jsonObj.getJSONObject(MESSAGE);
1178 if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) {
1179 jsonArrayNamespace = obj.getJSONArray(LISTMIRRORMAKER);
1182 JSONObject finalJasonObj = new JSONObject();
1183 JSONArray finalJsonArray = new JSONArray();
1185 for (int i = 0; i < jsonArrayNamespace.length(); i++) {
1188 mmObj = jsonArrayNamespace.getJSONObject(i);
1191 if (mmObj.has("whitelist")) {
1192 whitelist = getWhitelistByNamespace(mmObj.getString("whitelist"), namespace);
1194 if (whitelist != null) {
1195 mmObj.remove("whitelist");
1196 mmObj.put("whitelist", whitelist);
1198 mmObj.remove("whitelist");
1201 finalJsonArray.put(mmObj);
1203 finalJasonObj.put(LISTMIRRORMAKER, finalJsonArray);
1205 DMaaPResponseBuilder.respondOk(ctx, finalJasonObj);
1209 JSONObject err = new JSONObject();
1210 err.append(ERROR, "listMirrorMaker is not available, please make sure MirrorMakerAgent is running");
1211 DMaaPResponseBuilder.respondOk(ctx, err);
1214 } catch (Exception e) {
1215 LOGGER.error("Exception: ", e);
1219 private String getWhitelistByNamespace(String originalWhitelist, String namespace) {
1221 String whitelist = null;
1222 List<String> resultList = new ArrayList<>();
1223 List<String> whitelistList = new ArrayList<>();
1224 whitelistList = Arrays.asList(originalWhitelist.split(","));
1226 for (String topic : whitelistList) {
1227 if (StringUtils.isNotBlank(originalWhitelist) && getNamespace(topic).equals(namespace)) {
1228 resultList.add(topic);
1231 if (!resultList.isEmpty()) {
1232 whitelist = StringUtils.join(resultList, ",");
1238 private JSONArray getListMirrorMaker(String msgFrmSubscribe, String randomStr) {
1240 JSONArray jsonArray;
1241 JSONArray listMirrorMaker = new JSONArray();
1243 msgFrmSubscribe = removeExtraChar(msgFrmSubscribe);
1244 jsonArray = new JSONArray(msgFrmSubscribe);
1246 for (int i = 0; i < jsonArray.length(); i++) {
1247 jsonObj = jsonArray.getJSONObject(i);
1249 JSONObject obj = new JSONObject();
1250 if (jsonObj.has(MESSAGE)) {
1251 obj = jsonObj.getJSONObject(MESSAGE);
1253 if (obj.has("messageID") && obj.get("messageID").equals(randomStr) && obj.has(LISTMIRRORMAKER)) {
1254 listMirrorMaker = obj.getJSONArray(LISTMIRRORMAKER);
1258 return listMirrorMaker;