Merge "Fix NPE & other sonar issues"
authorManoop Talasila <talasila@research.att.com>
Thu, 19 Sep 2019 14:49:31 +0000 (14:49 +0000)
committerGerrit Code Review <gerrit@onap.org>
Thu, 19 Sep 2019 14:49:31 +0000 (14:49 +0000)
ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventController.java
ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserNotificationController.java
ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/UserRolesController.java

index 71f7f81..17b5a12 100644 (file)
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * 
+ *
  */
 package org.onap.portalapp.portal.controller;
 
@@ -85,163 +85,165 @@ import io.swagger.annotations.ApiOperation;
 @EnableAspectJAutoProxy
 @EPAuditLog
 public class TicketEventController implements BasicAuthenticationController {
-       private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
-
-       @Autowired
-       private UserNotificationService userNotificationService;
-       
-       @Autowired
-       private TicketEventService ticketEventService;
-
-       private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
-
-       public boolean isAuxRESTfulCall() {
-               return true;
-       }
-
-       private final ObjectMapper mapper = new ObjectMapper();
-
-
-
-       @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class)
-       @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
-       public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
-                       @RequestBody String ticketEventJson) throws Exception {
-
-               logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
-               PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-
-               if (ticketEventJson!=null){
-                       SecureString secureString = new SecureString(ticketEventJson);
-                       Validator validator = VALIDATOR_FACTORY.getValidator();
-
-                       Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
-                       if (!constraintViolations.isEmpty()){
-                               portalResponse.setStatus(PortalRestStatusEnum.ERROR);
-                               portalResponse.setMessage("Data is not valid");
-                               return portalResponse;
-                       }
-               }
-
-               try {
-                       JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
-
-                       // Reject request if required fields are missing.
-                       String error = validateTicketEventMessage(ticketEventNotif);
-                       if (error != null) {
-                               portalResponse.setStatus(PortalRestStatusEnum.ERROR);
-                               portalResponse.setMessage(error);
-                               response.setStatus(400);
-                               return portalResponse;
-                       }
-
-                       EpNotificationItem epItem = new EpNotificationItem();
-                       epItem.setCreatedDate(new Date());
-                       epItem.setIsForOnlineUsers("Y");
-                       epItem.setIsForAllRoles("N");
-                       epItem.setActiveYn("Y");
-
-                       JsonNode event = ticketEventNotif.get("event");
-                       JsonNode header = event.get("header");
-                       JsonNode body = event.get("body");
-                       JsonNode application = ticketEventNotif.get("application");
-                       epItem.setMsgDescription(body.toString());
-                       Long eventDate = System.currentTimeMillis();
-                       if (body.get("eventDate") != null) {
-                               eventDate = body.get("eventDate").asLong();
-                       }
-                       String eventSource = header.get("eventSource").asText();
-                       epItem.setMsgSource(eventSource);
-                       String ticket = body.get("ticketNum").asText();
-                       String hyperlink = ticketEventService.getNotificationHyperLink(application, ticket, eventSource);                       
-                       if(body.get("notificationHyperlink")!=null){
-                               hyperlink=body.get("notificationHyperlink").asText();
-                       }
-                       epItem.setNotificationHyperlink(hyperlink);
-                       epItem.setStartTime(new Date(eventDate));
-                       Calendar calendar = Calendar.getInstance();
-                       calendar.setTime(epItem.getStartTime());
-                       int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
-                       calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
-                       epItem.setEndTime(calendar.getTime());
-                       String severityString = "1";
-                       if (body.get("severity") != null) {
-                               severityString = (body.get("severity").toString()).substring(1, 2);
-                       }
-                       Long severity = Long.parseLong(severityString);
-                       epItem.setPriority(severity);
-                       epItem.setCreatorId(null);
-                       Set<EpRoleNotificationItem> roles = new HashSet<>();
-                       JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
-                       JsonNode userList = SubscriberInfo.get("UserList");
-                       String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
-                                       .split(",");
-                       String assetID = eventSource + ' '
-                                       + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' '
-                                       + new Date(eventDate);
-                       if (body.get("assetID") != null) {
-                               assetID = body.get("assetID").asText();
-                       }
-                       epItem.setMsgHeader(assetID);
-                       List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
-                       for (String userId : UserIds) {
-                               EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
-                               for (EPUser user : users) {
-                                       if (user.getOrgUserId().equals(userId)) {
-                                               roleNotifItem.setRecvUserId(user.getId().intValue());
-                                               roles.add(roleNotifItem);
-                                               break;
-                                       }
-                               }
-
-                       }
-                       epItem.setRoles(roles);
-                       userNotificationService.saveNotification(epItem);
-
-                       portalResponse.setStatus(PortalRestStatusEnum.OK);
-                       portalResponse.setMessage("processEventNotification: notification created");
-                       portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
-               } catch (Exception ex) {
-                       portalResponse.setStatus(PortalRestStatusEnum.ERROR);
-                       response.setStatus(400);
-                       portalResponse.setMessage(ex.toString());
-               }
-               return portalResponse;
-       }
-
-       /**
-        * Validates that mandatory fields are present.
-        * 
-        * @param ticketEventNotif
-        * @return Error message if a problem is found; null if all is well.
-        */
-       private String validateTicketEventMessage(JsonNode ticketEventNotif) {
-               JsonNode application = ticketEventNotif.get("application");
-               JsonNode event = ticketEventNotif.get("event");
-               JsonNode header = event.get("header");
-               JsonNode eventSource=header.get("eventSource");
-               JsonNode body = event.get("body");
-               JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
-               JsonNode userList = SubscriberInfo.get("UserList");
-
-               if (application == null||application.asText().length()==0||application.asText().equalsIgnoreCase("null"))
-                       return "Application is mandatory";
-               if (body == null)
-                       return "body is mandatory";
-               if (eventSource == null||eventSource.asText().trim().length()==0||eventSource.asText().equalsIgnoreCase("null"))
-                       return "Message Source is mandatory";
-               if (userList == null)
-                       return "At least one user Id is mandatory";
-               JsonNode eventDate=body.get("eventDate");
-               
-               if(eventDate!=null&&eventDate.asText().length()==8)
-                       return "EventDate is invalid";
-               String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
-                               .split(",");            
-               List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
-               if(users==null||users.size()==0)
-                       return "Invalid Org User ID";
-               return null;
-       }
-       
+    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
+
+    @Autowired
+    private UserNotificationService userNotificationService;
+
+    @Autowired
+    private TicketEventService ticketEventService;
+
+    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
+
+    public boolean isAuxRESTfulCall() {
+        return true;
+    }
+
+    private final ObjectMapper mapper = new ObjectMapper();
+    private static final String EVENT_DATE = "eventDate";
+
+    @ApiOperation(
+            value = "Accepts messages from external ticketing systems and creates notifications for Portal users.",
+            response = PortalRestResponse.class)
+    @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
+    public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
+            @RequestBody String ticketEventJson) throws Exception {
+
+        logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
+        PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+
+        if (ticketEventJson != null) {
+            SecureString secureString = new SecureString(ticketEventJson);
+            Validator validator = VALIDATOR_FACTORY.getValidator();
+
+            Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+            if (!constraintViolations.isEmpty()) {
+                portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+                portalResponse.setMessage("Data is not valid");
+                return portalResponse;
+            }
+        }
+
+        try {
+            JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
+
+            // Reject request if required fields are missing.
+            String error = validateTicketEventMessage(ticketEventNotif);
+            if (error != null) {
+                portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+                portalResponse.setMessage(error);
+                response.setStatus(400);
+                return portalResponse;
+            }
+
+            EpNotificationItem epItem = new EpNotificationItem();
+            epItem.setCreatedDate(new Date());
+            epItem.setIsForOnlineUsers("Y");
+            epItem.setIsForAllRoles("N");
+            epItem.setActiveYn("Y");
+
+            JsonNode event = ticketEventNotif.get("event");
+            JsonNode header = event.get("header");
+            JsonNode body = event.get("body");
+            JsonNode application = ticketEventNotif.get("application");
+            epItem.setMsgDescription(body.toString());
+            Long eventDate = System.currentTimeMillis();
+            if (body.get(EVENT_DATE) != null) {
+                eventDate = body.get(EVENT_DATE).asLong();
+            }
+            String eventSource = header.get("eventSource").asText();
+            epItem.setMsgSource(eventSource);
+            String ticket = body.get("ticketNum").asText();
+            String hyperlink = ticketEventService.getNotificationHyperLink(application, ticket, eventSource);
+            if (body.get("notificationHyperlink") != null) {
+                hyperlink = body.get("notificationHyperlink").asText();
+            }
+            epItem.setNotificationHyperlink(hyperlink);
+            epItem.setStartTime(new Date(eventDate));
+            Calendar calendar = Calendar.getInstance();
+            calendar.setTime(epItem.getStartTime());
+            int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
+            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
+            epItem.setEndTime(calendar.getTime());
+            String severityString = "1";
+            if (body.get("severity") != null) {
+                severityString = (body.get("severity").toString()).substring(1, 2);
+            }
+            Long severity = Long.parseLong(severityString);
+            epItem.setPriority(severity);
+            epItem.setCreatorId(null);
+            Set<EpRoleNotificationItem> roles = new HashSet<>();
+            JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
+            JsonNode userList = SubscriberInfo.get("UserList");
+            String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
+                    .split(",");
+            String assetID = eventSource + ' '
+                    + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' '
+                    + new Date(eventDate);
+            if (body.get("assetID") != null) {
+                assetID = body.get("assetID").asText();
+            }
+            epItem.setMsgHeader(assetID);
+            List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
+            for (String userId : UserIds) {
+                EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
+                for (EPUser user : users) {
+                    if (user.getOrgUserId().equals(userId)) {
+                        roleNotifItem.setRecvUserId(user.getId().intValue());
+                        roles.add(roleNotifItem);
+                        break;
+                    }
+                }
+
+            }
+            epItem.setRoles(roles);
+            userNotificationService.saveNotification(epItem);
+
+            portalResponse.setStatus(PortalRestStatusEnum.OK);
+            portalResponse.setMessage("processEventNotification: notification created");
+            portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
+        } catch (Exception ex) {
+            portalResponse.setStatus(PortalRestStatusEnum.ERROR);
+            response.setStatus(400);
+            portalResponse.setMessage(ex.toString());
+        }
+        return portalResponse;
+    }
+
+    /**
+     * Validates that mandatory fields are present.
+     *
+     * @param ticketEventNotif
+     * @return Error message if a problem is found; null if all is well.
+     */
+    private String validateTicketEventMessage(JsonNode ticketEventNotif) {
+        JsonNode application = ticketEventNotif.get("application");
+        JsonNode event = ticketEventNotif.get("event");
+        JsonNode header = event.get("header");
+        JsonNode eventSource = header.get("eventSource");
+        JsonNode body = event.get("body");
+        JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
+        JsonNode userList = SubscriberInfo.get("UserList");
+
+        if (application == null || application.asText().length() == 0 || application.asText().equalsIgnoreCase("null"))
+            return "Application is mandatory";
+        if (body == null)
+            return "body is mandatory";
+        if (eventSource == null || eventSource.asText().trim().length() == 0
+                || eventSource.asText().equalsIgnoreCase("null"))
+            return "Message Source is mandatory";
+        if (userList == null)
+            return "At least one user Id is mandatory";
+        JsonNode eventDate = body.get(EVENT_DATE);
+
+        if (eventDate != null && eventDate.asText().length() == 8)
+            return "EventDate is invalid";
+        String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
+                .split(",");
+        List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
+        if (users == null || users.size() == 0)
+            return "Invalid Org User ID";
+        return null;
+    }
+
 }
index af76cdc..0dfccc9 100644 (file)
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * 
+ *
  */
 package org.onap.portalapp.portal.controller;
 
@@ -77,158 +77,161 @@ import org.onap.portalsdk.core.web.support.UserUtils;
 @EPAuditLog
 public class UserNotificationController extends EPRestrictedBaseController {
 
-       @Autowired
-       FunctionalMenuService functionalMenuService;
-
-       @Autowired
-       UserNotificationService userNotificationService;
-
-       EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class);
-
-       @RequestMapping(value = {
-                       "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json")
-       public List<FunctionalMenuRole> getMenuIdRoleId(HttpServletRequest request, HttpServletResponse response) {
-               // EPUser user = EPUserUtils.getUserSession(request);
-               List<FunctionalMenuRole> menuRoleList = null;
-               menuRoleList = functionalMenuService.getFunctionalMenuRole();
-               return menuRoleList;
-       }
-
-       @RequestMapping(value = {
-                       "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json")
-       public PortalRestResponse<List<EpNotificationItem>> getNotifications(HttpServletRequest request,
-                       HttpServletResponse response) {
-               EPUser user = EPUserUtils.getUserSession(request);
-               PortalRestResponse<List<EpNotificationItem>> portalRestResponse = null;
-               try {
-                       List<EpNotificationItem> notificationList = userNotificationService.getNotifications(user.getId());
-                       portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.OK, "success",
-                                       notificationList);
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
-                       portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.ERROR,
-                                       e.getMessage(), null);
-               }
-               return portalRestResponse;
-       }
-
-       @RequestMapping(value = {
-                       "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json")
-       public List<EpNotificationItemVO> getAdminNotifications(HttpServletRequest request, HttpServletResponse response) {
-               List<EpNotificationItemVO> adminNotificationList = null;
-               EPUser user = EPUserUtils.getUserSession(request);
-               adminNotificationList = userNotificationService.getAdminNotificationVOS(user.getId());
-               return adminNotificationList;
-       }
-
-       @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json")
-       public PortalRestResponse<String> save(HttpServletRequest request, HttpServletResponse response,
-                       @RequestBody EpNotificationItem notificationItem) {
-
-               if (notificationItem == null || notificationItem.getMsgHeader() == null)
-                       return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
-                                       "Notification Header cannot be null or empty");
-               if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) {
-                       return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
-                                       "End Time should be greater than  start time");
-               }
-
-               if ((notificationItem.getIsForAllRoles() == "N") && notificationItem.getRoleIds().isEmpty()) {
-                       return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
-                                       "No Roles Ids Exist for the selected Roles");
-               }
-
-               Long creatorId = UserUtils.getUserIdAsLong(request);
-               notificationItem.setCreatorId(creatorId);
-
-               // Front-end date picker does not accept a time value, so all
-               // values are the start of the chosen day in the local time zone.
-               // Move the end time value to the very end of the chosen day.
-               // Avoid Calendar.getDefault() which uses the server's locale.
-               Long endTime = notificationItem.getEndTime().getTime();
-               endTime += (23 * 3600 + 59 * 60 + 59) * 1000;
-               notificationItem.getEndTime().setTime(endTime);
-
-               try {
-                       userNotificationService.saveNotification(notificationItem);
-               } catch (Exception e) {
-                       return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
-               }
-               return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
-       }
-
-       @RequestMapping(value = {
-                       "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json")
-       public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) {
-               try {
-                       String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE);
-                       String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION);
-                       Integer rateInMiliSec = Integer.valueOf(updateRate) * 1000;
-                       Integer durationInMiliSec = Integer.valueOf(updateDuration) * 1000;
-                       Map<String, String> results = new HashMap<String, String>();
-                       results.put("updateRate", String.valueOf(rateInMiliSec));
-                       results.put("updateDuration", String.valueOf(durationInMiliSec));
-                       return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e);
-                       return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
-               }
-       }
-
-       @RequestMapping(value = {
-                       "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json")
-       public PortalRestResponse<Map<String, String>> notificationRead(
-                       @RequestParam("notificationId") String notificationID, HttpServletRequest request) {
-               try {
-                       userNotificationService.setNotificationRead(Long.parseLong(notificationID), UserUtils.getUserId(request));
-                       return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e);
-                       return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
-               }
-       }
-
-       @RequestMapping(value = {
-                       "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json")
-       public List<EpNotificationItemVO> getNotificationHistory(HttpServletRequest request, HttpServletResponse response) {
-               EPUser user = EPUserUtils.getUserSession(request);
-               List<EpNotificationItemVO> notificationList = null;
-               notificationList = userNotificationService.getNotificationHistoryVO(user.getId());
-               return notificationList;
-       }
-
-       @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<Integer> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) {
-               List<EpRoleNotificationItem> NotifRoles = userNotificationService.getNotificationRoles(notificationId);
-               ArrayList<Integer> rolesList = new ArrayList<Integer>();
-               for (EpRoleNotificationItem notifRole : NotifRoles) {
-                       rolesList.add(notifRole.roleId);
-               }
-               return rolesList;
-       }
-
-       @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) {
-               List<EcompAppRole> epAppRoleList = null;
-               try {
-                       epAppRoleList = userNotificationService.getAppRoleList();
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger,
-                                       "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ",
-                                       e);
-               }
-               return epAppRoleList;
-       }
-
-       @RequestMapping(value = {
-                       "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json")
-       public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) {
-               // EPUser user = EPUserUtils.getUserSession(request);
-               List<String> messageUserRecipients = null;
-               messageUserRecipients = userNotificationService.getMessageRecipients(notificationID);
-               return messageUserRecipients;
-       }
+    @Autowired
+    FunctionalMenuService functionalMenuService;
+
+    @Autowired
+    UserNotificationService userNotificationService;
+
+    EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class);
+    private static final String SUCCESS = "success";
+    private static final String FAILURE = "FAILURE";
+
+    @RequestMapping(value = {
+            "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json")
+    public List<FunctionalMenuRole> getMenuIdRoleId(HttpServletRequest request, HttpServletResponse response) {
+        // EPUser user = EPUserUtils.getUserSession(request);
+        List<FunctionalMenuRole> menuRoleList = null;
+        menuRoleList = functionalMenuService.getFunctionalMenuRole();
+        return menuRoleList;
+    }
+
+    @RequestMapping(value = {
+            "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json")
+    public PortalRestResponse<List<EpNotificationItem>> getNotifications(HttpServletRequest request,
+            HttpServletResponse response) {
+        EPUser user = EPUserUtils.getUserSession(request);
+        PortalRestResponse<List<EpNotificationItem>> portalRestResponse = null;
+        try {
+            List<EpNotificationItem> notificationList = userNotificationService.getNotifications(user.getId());
+            portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS,
+                    notificationList);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
+            portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), null);
+        }
+        return portalRestResponse;
+    }
+
+    @RequestMapping(value = {
+            "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json")
+    public List<EpNotificationItemVO> getAdminNotifications(HttpServletRequest request, HttpServletResponse response) {
+        List<EpNotificationItemVO> adminNotificationList = null;
+        EPUser user = EPUserUtils.getUserSession(request);
+        adminNotificationList = userNotificationService.getAdminNotificationVOS(user.getId());
+        return adminNotificationList;
+    }
+
+    @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> save(HttpServletRequest request, HttpServletResponse response,
+            @RequestBody EpNotificationItem notificationItem) {
+
+        if (notificationItem == null || notificationItem.getMsgHeader() == null)
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE,
+                    "Notification Header cannot be null or empty");
+        if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE,
+                    "End Time should be greater than  start time");
+        }
+
+        if ((notificationItem.getIsForAllRoles() == "N") && notificationItem.getRoleIds().isEmpty()) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE,
+                    "No Roles Ids Exist for the selected Roles");
+        }
+
+        Long creatorId = UserUtils.getUserIdAsLong(request);
+        notificationItem.setCreatorId(creatorId);
+
+        // Front-end date picker does not accept a time value, so all
+        // values are the start of the chosen day in the local time zone.
+        // Move the end time value to the very end of the chosen day.
+        // Avoid Calendar.getDefault() which uses the server's locale.
+        Long endTime = notificationItem.getEndTime().getTime();
+        endTime += (23 * 3600 + 59 * 60 + 59) * 1000;
+        notificationItem.getEndTime().setTime(endTime);
+
+        try {
+            userNotificationService.saveNotification(notificationItem);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "saveNotification failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, FAILURE, e.getMessage());
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
+    }
+
+    @RequestMapping(value = {
+            "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json")
+    public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) {
+        try {
+            String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE);
+            String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION);
+            Integer rateInMiliSec = Integer.valueOf(updateRate) * 1000;
+            Integer durationInMiliSec = Integer.valueOf(updateDuration) * 1000;
+            Map<String, String> results = new HashMap<>();
+            results.put("updateRate", String.valueOf(rateInMiliSec));
+            results.put("updateDuration", String.valueOf(durationInMiliSec));
+            return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS, results);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+        }
+    }
+
+    @RequestMapping(value = {
+            "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json")
+    public PortalRestResponse<Map<String, String>> notificationRead(
+            @RequestParam("notificationId") String notificationID, HttpServletRequest request) {
+        try {
+            userNotificationService.setNotificationRead(Long.parseLong(notificationID), UserUtils.getUserId(request));
+            return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESS, null);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+        }
+    }
+
+    @RequestMapping(value = {
+            "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json")
+    public List<EpNotificationItemVO> getNotificationHistory(HttpServletRequest request, HttpServletResponse response) {
+        EPUser user = EPUserUtils.getUserSession(request);
+        List<EpNotificationItemVO> notificationList = null;
+        notificationList = userNotificationService.getNotificationHistoryVO(user.getId());
+        return notificationList;
+    }
+
+    @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<Integer> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) {
+        List<EpRoleNotificationItem> notifRoles = userNotificationService.getNotificationRoles(notificationId);
+        ArrayList<Integer> rolesList = new ArrayList<>();
+        for (EpRoleNotificationItem notifRole : notifRoles) {
+            rolesList.add(notifRole.roleId);
+        }
+        return rolesList;
+    }
+
+    @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) {
+        List<EcompAppRole> epAppRoleList = null;
+        try {
+            epAppRoleList = userNotificationService.getAppRoleList();
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                    "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ",
+                    e);
+        }
+        return epAppRoleList;
+    }
+
+    @RequestMapping(value = {
+            "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json")
+    public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) {
+        // EPUser user = EPUserUtils.getUserSession(request);
+        List<String> messageUserRecipients = null;
+        messageUserRecipients = userNotificationService.getMessageRecipients(notificationID);
+        return messageUserRecipients;
+    }
 
 }
index 0d665a9..852e2bb 100644 (file)
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * 
+ *
  */
 package org.onap.portalapp.portal.controller;
 
@@ -42,10 +42,8 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
-
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-
 import org.apache.cxf.transport.http.HTTPException;
 import org.onap.portalapp.controller.EPRestrictedBaseController;
 import org.onap.portalapp.portal.domain.EPRole;
@@ -65,7 +63,6 @@ import org.onap.portalapp.portal.service.UserRolesService;
 import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
 import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
-import org.onap.portalapp.portal.transport.EpNotificationItem;
 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
 import org.onap.portalapp.portal.transport.FieldsValidator;
 import org.onap.portalapp.portal.transport.RoleInAppForUser;
@@ -82,7 +79,6 @@ import org.onap.portalsdk.core.util.SystemProperties;
 import org.slf4j.MDC;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -96,481 +92,484 @@ import org.springframework.web.bind.annotation.RestController;
 @EPAuditLog
 public class UserRolesController extends EPRestrictedBaseController {
 
-       private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
-
-       @Autowired
-       private SearchService searchService;
-       @Autowired
-       private AdminRolesService adminRolesService;
-       private @Autowired UserRolesService userRolesService;
-       @Autowired
-       private ApplicationsRestClientService applicationsRestClientService;
-       @Autowired
-       private AuditService auditService;
-
-       private static final String FAILURE = "failure";
-
-       /**
-        * RESTful service method to fetch users in the WebPhone external service
-        * 
-        * @param request
-        *            HttpServletRequest
-        * @param searchString
-        *            search string
-        * @param response
-        *            HttpServletResponse
-        * @return array of found users as json
-        */
-       @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
-       public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
-                       HttpServletResponse response) {
-               EPUser user = EPUserUtils.getUserSession(request);
-               String searchResult = null;
-               if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)  ) {
-                       EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
-               } else {
-                       searchString = searchString.trim();
-                       if (searchString.length() > 2) {
-                               searchResult = searchService.searchUsersInPhoneBook(searchString);
-                       } else {
-                               logger.info(EELFLoggerDelegate.errorLogger,
-                                               "getPhoneBookSearchResult - too short search string: " + searchString);
-                       }
-               }
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
-
-               return searchResult;
-       }
-
-       /**
-        * RESTful service method to fetch applications where user is admin
-        * 
-        * @param request
-        *            HttpServletRequest
-        * @param orgUserId
-        *            search string
-        * @param response
-        *            HttpServletResponse
-        * @return for GET: array of all applications with boolean
-        *         isAdmin=true/false for each application
-        */
-       @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request,
-                       @RequestParam("user") String orgUserId, HttpServletResponse response) {
-
-               EPUser user = EPUserUtils.getUserSession(request);
-               AppsListWithAdminRole result = null;
-               if (!adminRolesService.isSuperAdmin(user)) {
-                       EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
-               } else {
-                       if (EcompPortalUtils.legitimateUserId(orgUserId)) {
-                               result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
-                       } else {
-                               logger.info(EELFLoggerDelegate.errorLogger,
-                                               "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
-                               response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
-                       }
-               }
-
-               StringBuilder adminAppRoles = new StringBuilder();
-               if(result != null){
-                       if ( result.appsRoles.size() >= 1) {
-                               adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
-                               for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
-                                       if (adminAppRole.isAdmin) {
-                                               adminAppRoles.append(adminAppRole.appName + ", ");
-                                       }
-                               }
-                               adminAppRoles.append("}.");
-                       } else {
-                               adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
-                       }
-               }else{
-                       logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null");
-               }
-               
-               logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
-
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
-
-               return result;
-       }
-
-       /**
-        * 
-        * @param request
-        *            HttpServletRequest
-        * @param newAppsListWithAdminRoles
-        *            new apps
-        * @param response
-        *            HttpServletResponse
-        * @return FieldsValidator
-        */
-       @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
-                       RequestMethod.PUT }, produces = "application/json")
-       public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
-                       @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
-
-               // newAppsListWithAdminRoles.appsRoles
-               FieldsValidator fieldsValidator = new FieldsValidator();
-               StringBuilder newAppRoles = new StringBuilder();
-               if(newAppsListWithAdminRoles != null ){
-                       if (newAppsListWithAdminRoles.appsRoles.size() >= 1) {
-                               newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
-                               for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
-                                       if (adminAppRole.isAdmin) {
-                                               newAppRoles.append(adminAppRole.appName + " ,");
-                                       }
-                               }
-                               newAppRoles.deleteCharAt(newAppRoles.length() - 1);
-                               newAppRoles.append("}.");
-                       } else {
-                               newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
-                       }
-               }else{
-                       logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
-                       fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-               }
-               
-               logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
-
-               EPUser user = EPUserUtils.getUserSession(request);
-               boolean changesApplied = false;
-
-               if (!adminRolesService.isSuperAdmin(user)) {
-                       EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
-               } else {
-                       changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
-                       AuditLog auditLog = new AuditLog();
-                       auditLog.setUserId(user.getId());
-                       auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
-                       auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
-                       auditLog.setComments(EcompPortalUtils.truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
-                       auditService.logActivity(auditLog, null);
-
-                       MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-                       MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-                       EcompPortalUtils.calculateDateTimeDifferenceForLog(
-                                       MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
-                                       MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
-                       logger.info(EELFLoggerDelegate.auditLogger,
-                                       EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
-                                                       EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
-                                                       newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
-                       MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
-                       MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-                       MDC.remove(SystemProperties.MDC_TIMER);
-               }
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
-
-               return fieldsValidator;
-       }
-
-       /**
-        * It returns a list of user app roles for single app
-        * 
-        * @param request
-        *            HttpServletRequest
-        * @param response
-        *            HttpServletResponse
-        * @param orgUserId
-        *            user ID
-        * @param appid
-        *            application ID
-        * @param extRequestValue
-        *            set to false if request is from users page otherwise true
-        * @return List<RoleInAppForUser>
-        */
-       @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
-                       @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,@RequestParam("isSystemUser") Boolean isSystemUser,
-                       HttpServletResponse response) {
-               EPUser user = EPUserUtils.getUserSession(request);
-               List<RoleInAppForUser> result = null;
-               String feErrorString = "";
-               if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user) ) {
-                       logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}", adminRolesService.isAccountAdmin(user) , adminRolesService.isRoleAdmin(user));
-                       EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
-                       feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
-               } else {
-                       if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) {
-                               result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user);
-                               logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result , appid);
-                               int responseCode = EcompPortalUtils.getExternalAppResponseCode();
-                               if (responseCode != 0 && responseCode != 200) {
-                                       // external error
-                                       response.setStatus(responseCode);
-                                       feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
-                               } else if (result == null) {
-                                       // If the result is null, there was an internal onap error
-                                       // in the service call.
-                                       response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-                                       feErrorString = EcompPortalUtils.getFEErrorString(true,
-                                                       HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-                               }
-                       } else {
-                               logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
-                               response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
-                               feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
-                       }
-               }
-
-               StringBuilder sbUserApps = new StringBuilder();
-               if (result != null && result.size() >= 1) {
-                       sbUserApps.append("User '" + orgUserId + "' has Roles={");
-                       for (RoleInAppForUser appRole : result) {
-                               if (appRole.isApplied) {
-                                       sbUserApps.append(appRole.roleName + ", ");
-                               }
-                       }
-                       sbUserApps.append("} assigned to the appId '" + appid + "'.");
-               } else {
-                       // Not sure creating an empty object will make any difference
-                       // but would like to give it a shot for defect #DE221057
-                       if (result == null) {
-                               result = new ArrayList<RoleInAppForUser>();
-                       }
-                       sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
-               }
-               logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
-
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
-               if (feErrorString != "") {
-                       logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
-
-                       response.addHeader("FEErrorString", feErrorString);
-                       response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
-               }
-               return result;
-       }
-
-       @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
-                       RequestMethod.PUT }, produces = "application/json")
-       public PortalRestResponse<String> putAppWithUserRoleStateForUser(HttpServletRequest request,
-                       @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
-               //FieldsValidator fieldsValidator = new FieldsValidator();
-               PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-               StringBuilder sbUserApps = new StringBuilder();
-               if (newAppRolesForUser != null) {
-                       sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId());
-                       if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
-                               sbUserApps.append("' has roles = { ");
-                               for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
-                                       if (appRole.isApplied) {
-                                               sbUserApps.append(appRole.roleName + " ,");
-                                       }
-                               }
-                               sbUserApps.deleteCharAt(sbUserApps.length() - 1);
-                               sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId());
-                       } else {
-                               sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId());
-                       }
-               }
-               logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
-
-               EPUser user = EPUserUtils.getUserSession(request);
-               //boolean changesApplied = false;
-               ExternalRequestFieldsValidator changesApplied = null;
-
-               if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user) ) {
-                       EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
-               } else if(newAppRolesForUser==null){
-                       logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
-               } else{
-                       changesApplied= userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
-                       try{
-                               if (changesApplied.isResult()) {
-                               logger.info(EELFLoggerDelegate.applicationLogger,
-                                               "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.getAppId(),
-                                               newAppRolesForUser.getAppId());
-
-                               MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-                               AuditLog auditLog = new AuditLog();
-                               auditLog.setUserId(user.getId());
-                               auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
-                               auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
-                               auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
-                               auditService.logActivity(auditLog, null);
-                               
-                               MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-                               EcompPortalUtils.calculateDateTimeDifferenceForLog(
-                                               MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
-                                               MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
-                               logger.info(EELFLoggerDelegate.auditLogger,
-                                               EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
-                                                               EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
-                                                       newAppRolesForUser.getOrgUserId(), sbUserApps.toString()));
-                               MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
-                               MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-                               MDC.remove(SystemProperties.MDC_TIMER);
-                               portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK,"success",null);
-
-                       }
-                                if (!changesApplied.isResult())
-                                               throw new Exception(changesApplied.getDetailMessage());
-                       
-               }catch (Exception e){
-                               logger.error(EELFLoggerDelegate.errorLogger,
-                                               "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(),
-                                       newAppRolesForUser.getOrgUserId());
-                               portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
-                       }
-               }
-
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
-               return portalResponse;
-       }
-       
-       
-       @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
-                       HttpServletResponse response) {
-
-               String updateRemoteUserFlag = FAILURE;
-               try {
-                       // saveNewUser = userService.saveNewUser(newUser);
-                       String orgUserId = request.getParameter("loginId");
-                       Long appId = Long.parseLong(request.getParameter("appId"));
-                       userRolesService.updateRemoteUserProfile(orgUserId, appId);
-
-               } catch (Exception e) {
-                       return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
-               }
-               return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
-
-       }
-
-       @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
-                       @PathVariable("appId") Long appId) throws HTTPException {
-               try {
-                       logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
-                       List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId);
-                       return appUsers;
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger,    "getUsersFromAppEndpoint failed", e);
-                       return new ArrayList<UserApplicationRoles>();
-               }
-       }
-
-       @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
-                       throws HTTPException {
-               EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
-               List<EcompRole> rolesList = Arrays.asList(appRoles);
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
-                               rolesList);
-
-               return rolesList;
-       }
-
-       @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
-                       throws HTTPException {
-               List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
-                               "response for appId=" + appId, rolesList);
-
-               return rolesList;
-       }
-
-       @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
-                       @PathVariable("orgUserId") String orgUserId) throws Exception {
-               if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
-                       String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
-                       logger.error(EELFLoggerDelegate.errorLogger, msg);
-                       throw new Exception(msg);
-               }
-               EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
-                               String.format("/user/%s/roles", orgUserId));
-               if (roles.length != 1) {
-                       String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
-                       logger.error(EELFLoggerDelegate.errorLogger, msg);
-                       throw new Exception(msg);
-               }
-
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
-                               "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
-               return roles[0];
-       }
-
-       @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = {
-                       RequestMethod.PUT }, produces = "application/json")
-       public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
-                       @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
-               FieldsValidator fieldsValidator = null;
-               try {
-
-                       EPUser user = EPUserUtils.getUserSession(request);
-                       fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
-                       response.setStatus(fieldsValidator.httpStatusCode.intValue());
-
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
-
-               }
-               // return fieldsValidator;
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
-                               response.getStatus());
-               return fieldsValidator;
-       }
-
-       @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
-                       RequestMethod.GET }, produces = "application/json")
-       public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
-                       @RequestParam("appName") String appName) {
-               EPUser user = EPUserUtils.getUserSession(request);
-               List<EPUserAppCatalogRoles> userAppRoleList = null;
-               try {
-                       userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
-
-               }
-               Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
-               EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
-
-               return userAppRoleList;
-
-       }
-
-       private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = new Comparator<EPUserAppCatalogRoles>() {
-               public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
-                       return o1.getRolename().compareTo(o2.getRolename());
-               }
-       };
-
-       @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, produces = "application/json")
-       public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
-               ExternalSystemAccess result = null;
-               try {
-                       result = userRolesService.getExternalRequestAccess();
-                       EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
-                                       result);
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());
-               }
-               return result;
-       }
-
-       @RequestMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, method = RequestMethod.GET, produces = "application/json")
-       public boolean checkIfUserIsSuperAdmin(HttpServletRequest request,
-                       HttpServletResponse response) {
-               EPUser user = EPUserUtils.getUserSession(request);
-               boolean isSuperAdmin = false;
-               try {
-                       isSuperAdmin = adminRolesService.isSuperAdmin(user) ;
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
-               }
-               return isSuperAdmin;
-       }
+    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
+
+    @Autowired
+    private SearchService searchService;
+    @Autowired
+    private AdminRolesService adminRolesService;
+    private @Autowired UserRolesService userRolesService;
+    @Autowired
+    private ApplicationsRestClientService applicationsRestClientService;
+    @Autowired
+    private AuditService auditService;
+
+    private static final String FAILURE = "failure";
+
+    /**
+     * RESTful service method to fetch users in the WebPhone external service
+     *
+     * @param request HttpServletRequest
+     * @param searchString search string
+     * @param response HttpServletResponse
+     * @return array of found users as json
+     */
+    @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
+    public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
+            HttpServletResponse response) {
+        EPUser user = EPUserUtils.getUserSession(request);
+        String searchResult = null;
+        if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)
+                && !adminRolesService.isRoleAdmin(user)) {
+            EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
+        } else {
+            searchString = searchString.trim();
+            if (searchString.length() > 2) {
+                searchResult = searchService.searchUsersInPhoneBook(searchString);
+            } else {
+                logger.info(EELFLoggerDelegate.errorLogger,
+                        "getPhoneBookSearchResult - too short search string: " + searchString);
+            }
+        }
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
+
+        return searchResult;
+    }
+
+    /**
+     * RESTful service method to fetch applications where user is admin
+     *
+     * @param request HttpServletRequest
+     * @param orgUserId search string
+     * @param response HttpServletResponse
+     * @return for GET: array of all applications with boolean isAdmin=true/false for each application
+     */
+    @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request,
+            @RequestParam("user") String orgUserId, HttpServletResponse response) {
+
+        EPUser user = EPUserUtils.getUserSession(request);
+        AppsListWithAdminRole result = null;
+        if (!adminRolesService.isSuperAdmin(user)) {
+            EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
+        } else {
+            if (EcompPortalUtils.legitimateUserId(orgUserId)) {
+                result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
+            } else {
+                logger.info(EELFLoggerDelegate.errorLogger,
+                        "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            }
+        }
+
+        StringBuilder adminAppRoles = new StringBuilder();
+        if (result != null) {
+            if (!result.appsRoles.isEmpty()) {
+                adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
+                for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
+                    if (adminAppRole.isAdmin) {
+                        adminAppRoles.append(adminAppRole.appName + ", ");
+                    }
+                }
+                adminAppRoles.append("}.");
+            } else {
+                adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
+            }
+        } else {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                    "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null");
+        }
+
+        logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
+
+        return result;
+    }
+
+    /**
+     *
+     * @param request HttpServletRequest
+     * @param newAppsListWithAdminRoles new apps
+     * @param response HttpServletResponse
+     * @return FieldsValidator
+     */
+    @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
+            RequestMethod.PUT }, produces = "application/json")
+    public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
+            @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
+
+        // newAppsListWithAdminRoles.appsRoles
+        FieldsValidator fieldsValidator = new FieldsValidator();
+        StringBuilder newAppRoles = new StringBuilder();
+        if (newAppsListWithAdminRoles != null) {
+            if (!newAppsListWithAdminRoles.appsRoles.isEmpty()) {
+                newAppRoles
+                        .append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
+                for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
+                    if (adminAppRole.isAdmin) {
+                        newAppRoles.append(adminAppRole.appName + " ,");
+                    }
+                }
+                newAppRoles.deleteCharAt(newAppRoles.length() - 1);
+                newAppRoles.append("}.");
+            } else {
+                newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
+            }
+        } else {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                    "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
+            fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+        }
+
+        logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
+
+        EPUser user = EPUserUtils.getUserSession(request);
+        boolean changesApplied = false;
+
+        if (!adminRolesService.isSuperAdmin(user)) {
+            EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
+        } else {
+            changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
+            AuditLog auditLog = new AuditLog();
+            auditLog.setUserId(user.getId());
+            auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
+            if (newAppsListWithAdminRoles != null) {
+                auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
+            }
+            auditLog.setComments(
+                    EcompPortalUtils.truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+            auditService.logActivity(auditLog, null);
+
+            MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+            MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+            EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+            if (newAppsListWithAdminRoles != null) {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                        EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
+                                EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
+                                newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
+            }
+            MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+            MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+            MDC.remove(SystemProperties.MDC_TIMER);
+        }
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
+
+        return fieldsValidator;
+    }
+
+    /**
+     * It returns a list of user app roles for single app
+     *
+     * @param request HttpServletRequest
+     * @param response HttpServletResponse
+     * @param orgUserId user ID
+     * @param appid application ID
+     * @param extRequestValue set to false if request is from users page otherwise true
+     * @return List<RoleInAppForUser>
+     */
+    @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
+            @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
+            @RequestParam("isSystemUser") Boolean isSystemUser,
+            HttpServletResponse response) {
+        EPUser user = EPUserUtils.getUserSession(request);
+        List<RoleInAppForUser> result = null;
+        String feErrorString = "";
+        if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                    "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}",
+                    adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user));
+            EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
+            feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
+        } else {
+            if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) {
+                result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user);
+                logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result, appid);
+                int responseCode = EcompPortalUtils.getExternalAppResponseCode();
+                if (responseCode != 0 && responseCode != 200) {
+                    // external error
+                    response.setStatus(responseCode);
+                    feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
+                } else if (result == null) {
+                    // If the result is null, there was an internal onap error
+                    // in the service call.
+                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                    feErrorString = EcompPortalUtils.getFEErrorString(true,
+                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
+            }
+        }
+
+        StringBuilder sbUserApps = new StringBuilder();
+        if (result != null && !result.isEmpty()) {
+            sbUserApps.append("User '" + orgUserId + "' has Roles={");
+            for (RoleInAppForUser appRole : result) {
+                if (appRole.isApplied) {
+                    sbUserApps.append(appRole.roleName + ", ");
+                }
+            }
+            sbUserApps.append("} assigned to the appId '" + appid + "'.");
+        } else {
+            // Not sure creating an empty object will make any difference
+            // but would like to give it a shot for defect #DE221057
+            if (result == null) {
+                result = new ArrayList<>();
+            }
+            sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
+        }
+        logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
+        if (feErrorString != "") {
+            logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
+
+            response.addHeader("FEErrorString", feErrorString);
+            response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
+        }
+        return result;
+    }
+
+    @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
+            RequestMethod.PUT }, produces = "application/json")
+    public PortalRestResponse<String> putAppWithUserRoleStateForUser(HttpServletRequest request,
+            @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
+        // FieldsValidator fieldsValidator = new FieldsValidator();
+        PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+        StringBuilder sbUserApps = new StringBuilder();
+        if (newAppRolesForUser != null) {
+            sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId());
+            if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
+                sbUserApps.append("' has roles = { ");
+                for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
+                    if (appRole.isApplied) {
+                        sbUserApps.append(appRole.roleName + " ,");
+                    }
+                }
+                sbUserApps.deleteCharAt(sbUserApps.length() - 1);
+                sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId());
+            } else {
+                sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId());
+            }
+        }
+        logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
+
+        EPUser user = EPUserUtils.getUserSession(request);
+        // boolean changesApplied = false;
+        ExternalRequestFieldsValidator changesApplied = null;
+
+        if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
+            EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
+        } else if (newAppRolesForUser == null) {
+            logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
+        } else {
+            changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
+            try {
+                if (changesApplied.isResult()) {
+                    logger.info(EELFLoggerDelegate.applicationLogger,
+                            "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
+                            newAppRolesForUser.getAppId(),
+                            newAppRolesForUser.getAppId());
+
+                    MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                    AuditLog auditLog = new AuditLog();
+                    auditLog.setUserId(user.getId());
+                    auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
+                    auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
+                    auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(),
+                            PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                    auditService.logActivity(auditLog, null);
+
+                    MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                    EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                    logger.info(EELFLoggerDelegate.auditLogger,
+                            EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
+                                    EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
+                                    newAppRolesForUser.getOrgUserId(), sbUserApps.toString()));
+                    MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                    MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                    MDC.remove(SystemProperties.MDC_TIMER);
+                    portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
+
+                }
+                if (!changesApplied.isResult())
+                    throw new Exception(changesApplied.getDetailMessage());
+
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                        "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(),
+                        newAppRolesForUser.getOrgUserId(), e);
+                portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
+            }
+        }
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
+        return portalResponse;
+    }
+
+    @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
+            HttpServletResponse response) {
+
+        String updateRemoteUserFlag = FAILURE;
+        try {
+            // saveNewUser = userService.saveNewUser(newUser);
+            String orgUserId = request.getParameter("loginId");
+            Long appId = Long.parseLong(request.getParameter("appId"));
+            userRolesService.updateRemoteUserProfile(orgUserId, appId);
+
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
+
+    }
+
+    @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
+            @PathVariable("appId") Long appId) throws HTTPException {
+        try {
+            logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
+            return userRolesService.getUsersFromAppEndpoint(appId);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e);
+            return new ArrayList<>();
+        }
+    }
+
+    @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
+            throws HTTPException {
+        EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+        List<EcompRole> rolesList = Arrays.asList(appRoles);
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
+                rolesList);
+
+        return rolesList;
+    }
+
+    @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
+            throws HTTPException {
+        List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
+                "response for appId=" + appId, rolesList);
+
+        return rolesList;
+    }
+
+    @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
+            @PathVariable("orgUserId") String orgUserId) throws Exception {
+        if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
+            String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
+            logger.error(EELFLoggerDelegate.errorLogger, msg);
+            throw new Exception(msg);
+        }
+        EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
+                String.format("/user/%s/roles", orgUserId));
+        if (roles.length != 1) {
+            String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
+            logger.error(EELFLoggerDelegate.errorLogger, msg);
+            throw new Exception(msg);
+        }
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
+                "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
+        return roles[0];
+    }
+
+    @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = {
+            RequestMethod.PUT }, produces = "application/json")
+    public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
+            @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
+        FieldsValidator fieldsValidator = null;
+        try {
+
+            EPUser user = EPUserUtils.getUserSession(request);
+            fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
+            response.setStatus(fieldsValidator.httpStatusCode.intValue());
+
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
+
+        }
+        // return fieldsValidator;
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
+                response.getStatus());
+        return fieldsValidator;
+    }
+
+    @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
+            RequestMethod.GET }, produces = "application/json")
+    public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
+            @RequestParam("appName") String appName) {
+        EPUser user = EPUserUtils.getUserSession(request);
+        List<EPUserAppCatalogRoles> userAppRoleList = null;
+        try {
+            userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
+
+        }
+        Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
+
+        return userAppRoleList;
+
+    }
+
+    private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator =
+            new Comparator<EPUserAppCatalogRoles>() {
+                public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
+                    return o1.getRolename().compareTo(o2.getRolename());
+                }
+            };
+
+    @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET,
+            produces = "application/json")
+    public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
+        ExternalSystemAccess result = null;
+        try {
+            result = userRolesService.getExternalRequestAccess();
+            EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
+                    result);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());
+        }
+        return result;
+    }
+
+    @RequestMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, method = RequestMethod.GET,
+            produces = "application/json")
+    public boolean checkIfUserIsSuperAdmin(HttpServletRequest request,
+            HttpServletResponse response) {
+        EPUser user = EPUserUtils.getUserSession(request);
+        boolean isSuperAdmin = false;
+        try {
+            isSuperAdmin = adminRolesService.isSuperAdmin(user);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
+        }
+        return isSuperAdmin;
+    }
 }