Reduce number of parameters
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / RoleManageController.java
index c9a6f5d..e2dd658 100644 (file)
@@ -4,6 +4,8 @@
  * ===================================================================
  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ===================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ===================================================================
  *
  * Unless otherwise specified, all software contained herein is licensed
  * under the Apache License, Version 2.0 (the "License");
@@ -33,7 +35,7 @@
  *
  * ============LICENSE_END============================================
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * 
  */
 package org.onap.portalapp.portal.controller;
 
@@ -44,10 +46,13 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;
-
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-
+import javax.validation.ConstraintViolation;
+import javax.validation.Valid;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
 import org.apache.commons.lang.StringUtils;
 import org.json.JSONObject;
 import org.onap.portalapp.controller.EPRestrictedBaseController;
@@ -60,6 +65,7 @@ import org.onap.portalapp.portal.domain.EPUser;
 import org.onap.portalapp.portal.domain.EcompAuditLog;
 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
@@ -76,6 +82,7 @@ import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 import org.onap.portalapp.portal.utils.PortalConstants;
 import org.onap.portalapp.util.EPUserUtils;
+import org.onap.portalapp.validation.SecureString;
 import org.onap.portalsdk.core.domain.AuditLog;
 import org.onap.portalsdk.core.domain.Role;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
@@ -92,7 +99,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.servlet.ModelAndView;
-
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -108,6 +114,10 @@ import com.fasterxml.jackson.databind.type.TypeFactory;
 @EnableAspectJAutoProxy
 @EPAuditLog
 public class RoleManageController extends EPRestrictedBaseController {
+       private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
+
+       private static final String PIPE = "|";
+
        private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
 
        private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
@@ -117,37 +127,36 @@ public class RoleManageController extends EPRestrictedBaseController {
 
        @Autowired
        private RoleListController roleListController;
-       
+
        @Autowired
        private EPAppService appService;
 
        @Autowired
        private AuditService auditService;
-       
+
        @Autowired
        private ExternalAccessRolesService externalAccessRolesService;
-       
-       
+
        @Autowired
        private AdminRolesService adminRolesService;
 
        /**
         * Calls an SDK-Core library method that gets the available roles and writes
-        * them to the request object. Portal specifies a Hibernate mappings from
-        * the Role class to the fn_role_v view, which ensures that only Portal
-        * (app_id is null) roles are fetched.
+        * them to the request object. Portal specifies a Hibernate mappings from the
+        * Role class to the fn_role_v view, which ensures that only Portal (app_id is
+        * null) roles are fetched.
         * 
-        * Any method declared void (no return value) or returning null causes the
-        * audit log aspect method to declare failure. TODO: should return a JSON
-        * string.
+        * Any method declared void (no return value) or returning null causes the audit
+        * log aspect method to declare failure. TODO: should return a JSON string.
         * 
         * @param request
         * @param response
-        * @throws Exception 
+        * @throws Exception
         */
-       
+
        @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
-       public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception {
+       public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
+                       throws Exception {
                try {
                        EPUser user = EPUserUtils.getUserSession(request);
                        EPApp requestedApp = appService.getApp(appId);
@@ -173,12 +182,10 @@ public class RoleManageController extends EPRestrictedBaseController {
                        logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
                }
        }
-       
-       
 
        @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
-       public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
-                       @PathVariable("roleId") Long roleId) throws Exception {
+       public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
+                       @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
                EPApp requestedApp = null;
                String restcallStatus = null;
                HashMap<String, Object> responseMap = new HashMap<>();
@@ -191,7 +198,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
                                // role. toggle active ind
-                               boolean active = domainRole.isActive();
+                               boolean active = domainRole.getActive();
                                domainRole.setActive(!active);
 
                                String result = mapper.writeValueAsString(domainRole);
@@ -219,10 +226,10 @@ public class RoleManageController extends EPRestrictedBaseController {
                }
                return responseMap;
        }
-       
+
        @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
-       public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
-                       @PathVariable("roleId") Long roleId) throws Exception {
+       public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
+                       @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
 
                EPUser user = EPUserUtils.getUserSession(request);
                EPApp requestedApp = null;
@@ -285,7 +292,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                }
                return responseMap;
        }
-       
+
        @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
        public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
                        @PathVariable("appId") Long appId) throws Exception {
@@ -321,11 +328,12 @@ public class RoleManageController extends EPRestrictedBaseController {
                                                List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
                                                for (CentralV2Role existRole : roles)
                                                        if (existRole.getName().equalsIgnoreCase(role.getName()))
-                                                               throw new DuplicateRecordException("role already exists: " + existRole.getName());
+                                                               throw new DuplicateRecordException("Role already exists: " + existRole.getName());
 
-                                               domainRole = new CentralV2Role();
+                        domainRole = new CentralV2Role.CentralV2RoleBuilder().createCentralV2Role();
                                                domainRole.setName(role.getName());
                                                domainRole.setPriority(role.getPriority());
+                                               domainRole.setActive(role.getActive());
                                                if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
                                                        for (Object childRole : childRoles) {
                                                                domainRole.addChildRole((CentralV2Role) childRole);
@@ -339,9 +347,13 @@ public class RoleManageController extends EPRestrictedBaseController {
                                                                throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
                                                                                + " and action: " + roleFunction.getAction() + " found while saving!");
                                                        }
-                                                       roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
-                                                       roleFunction.setCode(roleFunction.getType() + "|" + roleFunction.getCode() + "|"
-                                                                       + roleFunction.getAction());
+                                                       if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
+                                                               roleFunction.setCode(roleFunction.getType() + PIPE
+                                                                               + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
+                                                                               + roleFunction.getAction());
+                                                       else
+                                                               roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
+                                                                               + roleFunction.getAction());
                                                        domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
                                                }
                                        } else {
@@ -430,29 +442,29 @@ public class RoleManageController extends EPRestrictedBaseController {
                        @PathVariable("roleId") Long roleId) throws Exception {
                try {
                        EPUser user = EPUserUtils.getUserSession(request);
-                               ObjectMapper mapper = new ObjectMapper();
-                               EPApp requestedApp = appService.getApp(appId);
-                               if (isAuthorizedUser(user, requestedApp)) {
-                                       fieldsValidation(requestedApp);
-                                       if (requestedApp.getCentralAuth()) {
-                                               CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
-                                               logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
-                                               Map<String, Object> model = new HashMap<>();
-                                               model.put("availableRoleFunctions", mapper.writeValueAsString(
-                                                               externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
-                                               model.put("availableRoles",
-                                                               mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
-                                               model.put("role", mapper.writeValueAsString(answer));
-                                               JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-                                               JSONObject j = new JSONObject(msg);
-                                               response.getWriter().write(j.toString());
-                                       } else
-                                               throw new NonCentralizedAppException(requestedApp.getName());
-                               } else {
-                                       logger.info(EELFLoggerDelegate.auditLogger,
-                                                       "RoleManageController.getRoleFunctionList, Unauthorized user");
-                                       SendErrorForUnauthorizedUser(response, user);
-                               }
+                       ObjectMapper mapper = new ObjectMapper();
+                       EPApp requestedApp = appService.getApp(appId);
+                       if (isAuthorizedUser(user, requestedApp)) {
+                               fieldsValidation(requestedApp);
+                               if (requestedApp.getCentralAuth()) {
+                                       CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
+                                       logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
+                                       Map<String, Object> model = new HashMap<>();
+                                       model.put("availableRoleFunctions", mapper
+                                                       .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
+                                       model.put("availableRoles",
+                                                       mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
+                                       model.put("role", mapper.writeValueAsString(answer));
+                                       JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+                                       JSONObject j = new JSONObject(msg);
+                                       response.getWriter().write(j.toString());
+                               } else
+                                       throw new NonCentralizedAppException(requestedApp.getName());
+                       } else {
+                               logger.info(EELFLoggerDelegate.auditLogger,
+                                               "RoleManageController.getRoleFunctionList, Unauthorized user");
+                               SendErrorForUnauthorizedUser(response, user);
+                       }
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
                        throw e;
@@ -464,26 +476,26 @@ public class RoleManageController extends EPRestrictedBaseController {
                        @PathVariable("appId") Long appId) throws Exception {
                try {
                        EPUser user = EPUserUtils.getUserSession(request);
-                               EPApp requestedApp = appService.getApp(appId);
-                               if (isAuthorizedUser(user, requestedApp)) {
-                                       fieldsValidation(requestedApp);
-                                       if (requestedApp.getCentralAuth()) {
-                                               List<CentralV2RoleFunction> answer = null;
-                                               Map<String, Object> model = new HashMap<>();
-                                               ObjectMapper mapper = new ObjectMapper();
-                                               answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
-                                               model.put("availableRoleFunctions", answer);
-                                               JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
-                                               JSONObject j = new JSONObject(msg);
-                                               response.getWriter().write(j.toString());
-                                       } else
-                                               throw new NonCentralizedAppException(requestedApp.getName());
-                               } else {
-                                       logger.info(EELFLoggerDelegate.auditLogger,
-                                                       "RoleManageController.getRoleFunctionList, Unauthorized user");
-                                       EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
-                                       response.getWriter().write("Unauthorized User");
-                               }
+                       EPApp requestedApp = appService.getApp(appId);
+                       if (isAuthorizedUser(user, requestedApp)) {
+                               fieldsValidation(requestedApp);
+                               if (requestedApp.getCentralAuth()) {
+                                       List<CentralV2RoleFunction> answer = null;
+                                       Map<String, Object> model = new HashMap<>();
+                                       ObjectMapper mapper = new ObjectMapper();
+                                       answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
+                                       model.put("availableRoleFunctions", answer);
+                                       JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+                                       JSONObject j = new JSONObject(msg);
+                                       response.getWriter().write(j.toString());
+                               } else
+                                       throw new NonCentralizedAppException(requestedApp.getName());
+                       } else {
+                               logger.info(EELFLoggerDelegate.auditLogger,
+                                               "RoleManageController.getRoleFunctionList, Unauthorized user");
+                               EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                               response.getWriter().write("Unauthorized User");
+                       }
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
                        throw e;
@@ -491,23 +503,40 @@ public class RoleManageController extends EPRestrictedBaseController {
        }
 
        @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
-       public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc,
+       public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
                        @PathVariable("appId") Long appId) throws Exception {
+               if (roleFunc!=null) {
+                       Validator validator = VALIDATOR_FACTORY.getValidator();
+                       Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
+
+                       if(!constraintViolations.isEmpty()){
+                               logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
+                               return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
+                       }
+               }
+
                EPUser user = EPUserUtils.getUserSession(request);
                boolean saveOrUpdateResponse = false;
                try {
                        EPApp requestedApp = appService.getApp(appId);
                        if (isAuthorizedUser(user, requestedApp)) {
                                fieldsValidation(requestedApp);
-                               if (requestedApp.getCentralAuth()) {
-                                       CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(roleFunc.getCode(),
+                               if (requestedApp.getCentralAuth() && roleFunc!=null) {
+                                       String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
+                                       CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
                                                        requestedApp.getUebKey());
+                                       if (domainRoleFunction != null
+                                                       && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
+                                               addIfTypeActionDoesNotExits(domainRoleFunction);
+                                       }
+                                       boolean isSave = true;
                                        if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
                                                        && domainRoleFunction.getType().equals(roleFunc.getType())
                                                        && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
                                                domainRoleFunction.setName(roleFunc.getName());
                                                saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
                                                                requestedApp);
+                                               isSave = false;
                                        } else {
                                                roleFunc.setAppId(requestedApp.getId());
                                                saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
@@ -516,38 +545,14 @@ public class RoleManageController extends EPRestrictedBaseController {
                                        if (saveOrUpdateResponse) {
                                                EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
                                                EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
-                                               CentralV2RoleFunction function = externalAccessRolesService.getRoleFunction(roleFunc.getCode(),
-                                                               requestedApp.getUebKey());
-                                               String activityCode = (function.getCode() == null)
-                                                               ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
+                                               String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
                                                                : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
-                                               logger.info(EELFLoggerDelegate.applicationLogger,
-                                                               "saveRoleFunction: succeeded for app {}, function {}", app.getId(), roleFunc.getCode());
-                                               AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
-                                               auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
-                                                               + app.getId() + " and function:'" + roleFunc.getCode() + "'",
-                                                               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("RoleManageController.saveRoleFunction", activityCode,
-                                                                               String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
-                                                                               roleFunc.getCode()));
-                                               MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
-                                               MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-                                               MDC.remove(SystemProperties.MDC_TIMER);
+                                               logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
                                        }
                                } else
                                        throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
                        } else {
-                               logger.info(EELFLoggerDelegate.auditLogger,
-                                               "RoleManageController.saveRoleFunction, Unauthorized user");
+                               logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
                                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
                        }
@@ -558,10 +563,59 @@ public class RoleManageController extends EPRestrictedBaseController {
                return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
        }
 
+       private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
+               logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
+                               app.getId(), code);
+               AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
+               auditLog.setComments(EcompPortalUtils.truncateString(
+                               "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
+                               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("RoleManageController.saveRoleFunction", activityCode,
+                                               String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
+               MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+               MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+               MDC.remove(SystemProperties.MDC_TIMER);
+       }
+
+       private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
+               if (domainRoleFunction.getCode().contains(PIPE)) {
+                       String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
+                       String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
+                       String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
+                       domainRoleFunction.setType(newfunctionTypeFormat);
+                       domainRoleFunction.setAction(newfunctionActionFormat);
+                       domainRoleFunction.setCode(newfunctionCodeFormat);
+               } else {
+                       String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
+                       String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
+                       domainRoleFunction.setType(type);
+                       domainRoleFunction.setAction(action);
+               }
+       }
+
        @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
        public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
                        @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
                EPUser user = EPUserUtils.getUserSession(request);
+
+               if (roleFunc!=null) {
+                       SecureString secureString = new SecureString(roleFunc);
+
+                       Validator validator = VALIDATOR_FACTORY.getValidator();
+                       Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+
+                       if(!constraintViolations.isEmpty()){
+                               logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
+                               return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
+                       }
+               }
+
                try {
                        EPApp requestedApp = appService.getApp(appId);
                        if (isAuthorizedUser(user, requestedApp)) {
@@ -571,17 +625,12 @@ public class RoleManageController extends EPRestrictedBaseController {
                                        String data = roleFunc;
                                        boolean getDelFuncResponse = false;
                                        CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
-                                       String code = availableRoleFunction.getType() + "|" + availableRoleFunction.getCode() + "|"
+                                       String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
                                                        + availableRoleFunction.getAction();
                                        CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
                                                        requestedApp.getUebKey());
-                                       if (domainRoleFunction.getCode().contains("|")) {
-                                               getDelFuncResponse = externalAccessRolesService
-                                                               .deleteCentralRoleFunction(code, requestedApp);
-                                       } else {
-                                               getDelFuncResponse = externalAccessRolesService
-                                                               .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
-                                       }
+                                       getDelFuncResponse = externalAccessRolesService
+                                                       .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
                                        if (getDelFuncResponse) {
                                                logger.info(EELFLoggerDelegate.applicationLogger,
                                                                "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
@@ -628,19 +677,32 @@ public class RoleManageController extends EPRestrictedBaseController {
        }
 
        @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
-       public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
+       public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
+               if(userId!=null) {
+                       SecureString secureString = new SecureString(userId);
+
+                       Validator validator = VALIDATOR_FACTORY.getValidator();
+                       Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+
+                       if(!constraintViolations.isEmpty()){
+                               logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
+                               return null;
+                       }
+               }
+
                EPUser user = EPUserUtils.getUserSession(request);
                List<CentralizedApp> applicationsList = null;
-                       if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)) {
-                               applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
-                       } else {
-                               logger.info(EELFLoggerDelegate.auditLogger,
-                                               "RoleManageController.getCentralizedAppRoles, Unauthorized user");
-                               EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
-                       }
+               if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
+                               || adminRolesService.isRoleAdmin(user)) {
+                       applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
+               } else {
+                       logger.info(EELFLoggerDelegate.auditLogger,
+                                       "RoleManageController.getCentralizedAppRoles, Unauthorized user");
+                       EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+               }
                return applicationsList;
        }
-       
+
        public RoleListController getRoleListController() {
                return roleListController;
        }
@@ -657,7 +719,6 @@ public class RoleManageController extends EPRestrictedBaseController {
                this.roleController = roleController;
        }
 
-
        @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
        public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
                        @RequestBody Long appId) {
@@ -669,7 +730,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                                externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
                        } else {
                                logger.info(EELFLoggerDelegate.auditLogger,
-                                               "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
+                                               "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
                                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
                        }
@@ -679,7 +740,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                }
                return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
        }
-       
+
        @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
        public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
                        @RequestBody Long appId) {
@@ -688,10 +749,10 @@ public class RoleManageController extends EPRestrictedBaseController {
                        EPApp app = appService.getApp(appId);
                        if (isAuthorizedUser(user, app)) {
                                fieldsValidation(app);
-                               externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);;
+                               externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
                        } else {
                                logger.info(EELFLoggerDelegate.auditLogger,
-                                               "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId());
+                                               "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
                                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
                        }
@@ -713,7 +774,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
                while (availableChildRolesIterator.hasNext()) {
                        CentralV2Role role = availableChildRolesIterator.next();
-                       if (!role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
+                       if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
                                availableChildRolesIterator.remove();
                        }
                }
@@ -729,33 +790,33 @@ public class RoleManageController extends EPRestrictedBaseController {
                }
                return allParentRoles;
        }
-       
-       public AuditLog getAuditInfo(EPUser user, String activityCode)
-       {
+
+       public AuditLog getAuditInfo(EPUser user, String activityCode) {
                AuditLog auditLog = new AuditLog();
                auditLog.setUserId(user.getId());
                auditLog.setActivityCode(activityCode);
                auditLog.setAffectedRecordId(user.getOrgUserId());
-               
+
                return auditLog;
        }
-       
-       private void  fieldsValidation(EPApp app) throws Exception{
+
+       private void fieldsValidation(EPApp app) throws Exception {
                app.getUebKey();
                List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
-               if(appInfo.isEmpty()){
-                       throw new InvalidApplicationException("Invalid uebkey");
+               if (appInfo.isEmpty()) {
+                       throw new InvalidApplicationException("Invalid credentials");
                }
-               if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
+               if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
+                               && appInfo.get(0).getCentralAuth()) {
                        ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
                        if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
                                throw new InvalidApplicationException("Invalid NameSpace");
                }
        }
-       
+
        private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
                if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
-                               || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
+                               || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
                        return true;
                return false;
        }
@@ -764,4 +825,31 @@ public class RoleManageController extends EPRestrictedBaseController {
                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                response.getWriter().write("Unauthorized User");
        }
+
+       @RequestMapping(value = {
+                       "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
+       public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
+                       @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
+               EPUser user = EPUserUtils.getUserSession(request);
+               try {
+                       EPApp app = appService.getApp(appId);
+                       if (isAuthorizedUser(user, app)) {
+                               fieldsValidation(app);
+                               externalAccessRolesService.bulkUploadRoleFunc(data, app);
+                               String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
+                               String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
+                                               + data.getAction();
+                               logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
+                       } else {
+                               logger.info(EELFLoggerDelegate.auditLogger,
+                                               "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
+                               EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                               return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+                       }
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
+                       return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+               }
+               return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");
+       }
 }