Merge "NotificationCleanupConfig.java - Fixed sonar issue"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / ExternalAccessRolesServiceImpl.java
index af5b500..4197d23 100644 (file)
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * 
  */
 package org.onap.portalapp.portal.service;
 
@@ -70,6 +70,7 @@ import org.onap.portalapp.portal.domain.EPRole;
 import org.onap.portalapp.portal.domain.EPUser;
 import org.onap.portalapp.portal.domain.EPUserApp;
 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
+import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
@@ -89,12 +90,14 @@ import org.onap.portalapp.portal.transport.CentralUserApp;
 import org.onap.portalapp.portal.transport.CentralV2Role;
 import org.onap.portalapp.portal.transport.CentralV2User;
 import org.onap.portalapp.portal.transport.CentralV2UserApp;
+import org.onap.portalapp.portal.transport.CentralizedAppRoles;
 import org.onap.portalapp.portal.transport.EcompUserRoles;
 import org.onap.portalapp.portal.transport.ExternalAccessPerms;
 import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
 import org.onap.portalapp.portal.transport.ExternalAccessRole;
 import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
 import org.onap.portalapp.portal.transport.ExternalAccessUser;
+import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
 import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
@@ -107,6 +110,7 @@ import org.onap.portalsdk.core.domain.Role;
 import org.onap.portalsdk.core.domain.RoleFunction;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
 import org.onap.portalsdk.core.restful.domain.EcompUser;
 import org.onap.portalsdk.core.service.DataAccessService;
 import org.onap.portalsdk.core.util.SystemProperties;
@@ -513,8 +517,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                String action = "";
                if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
                        code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
-                       type = getFunctionType(roleFunc.getCode());
-                       action = getFunctionAction(roleFunc.getCode());
+                       type = getFunctionCodeType(roleFunc.getCode());
+                       action = getFunctionCodeAction(roleFunc.getCode());
                } else {
                        code = roleFunc.getCode();
                        type = roleFunc.getCode().contains("menu") ? "menu" : "url";
@@ -663,8 +667,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                String action = "";
                                if (addFunction.getCode().contains(FUNCTION_PIPE)) {
                                        code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
-                                       type = getFunctionType(addFunction.getCode());
-                                       action = getFunctionAction(addFunction.getCode());
+                                       type = getFunctionCodeType(addFunction.getCode());
+                                       action = getFunctionCodeAction(addFunction.getCode());
                                } else {
                                        code = addFunction.getCode();
                                        type = addFunction.getCode().contains("menu") ? "menu" : "url";
@@ -720,8 +724,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        String action = "";
                        if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
                                code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
-                               type = getFunctionType(roleFunc.getCode());
-                               action = getFunctionAction(roleFunc.getCode());
+                               type = getFunctionCodeType(roleFunc.getCode());
+                               action = getFunctionCodeAction(roleFunc.getCode());
                        } else {
                                code = roleFunc.getCode();
                                type = roleFunc.getCode().contains("menu") ? "menu" : "url";
@@ -893,8 +897,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
         * @throws Exception
         */
        @SuppressWarnings("unchecked")
-       @Transactional(rollbackFor = Exception.class)
-       private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {                
+        @Transactional(rollbackFor = Exception.class)
+       public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {         
                boolean result = false;
                EPRole epRole = null;
                Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
@@ -1191,8 +1195,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
                for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
                        String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
-                       String type = getFunctionType(roleFuncItem.getCode());
-                       String action = getFunctionAction(roleFuncItem.getCode());
+                       String type = getFunctionCodeType(roleFuncItem.getCode());
+                       String action = getFunctionCodeAction(roleFuncItem.getCode());
                        roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
                        roleFuncItem.setType(type);
                        roleFuncItem.setAction(action);
@@ -1202,26 +1206,14 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        }
 
 
-       /**
-        * It return function action
-        * 
-        * @param roleFuncItem
-        * @return String action
-        */
-       private String getFunctionAction(String roleFuncItem) {
+       @Override
+       public String getFunctionCodeAction(String roleFuncItem) {
                return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
                                : EcompPortalUtils.getFunctionAction(roleFuncItem);
        }
 
-       /**
-        * 
-        * It check function code has any pipes, if found return function type
-        * 
-        * @param roleFuncItem
-        * @param type
-        * @return function type
-        */
-       private String getFunctionType(String roleFuncItem) {
+       @Override
+       public String getFunctionCodeType(String roleFuncItem) {
                String type = null;
                if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
                                || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
@@ -1285,7 +1277,15 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                final Map<String, Long> params = new HashMap<>();
                CentralV2User userAppList = new CentralV2User();
                CentralV2User user1 = null;
+               final Map<String, Long> params1 = new HashMap<>();
+               List<EPRole> globalRoleList = new ArrayList<>();
+
                try {
+                       if (app.getId() != PortalConstants.PORTAL_APP_ID) {
+                               params1.put("userId", userInfo.getId());
+                               params1.put("appId", app.getId());
+                               globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
+                       }
                        userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
                        for (EPUserApp userApp : userAppSet) {
                                if (userApp.getRole().getActive()) {
@@ -1306,41 +1306,48 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                                                epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
                                                                epApp.getUebTopicName());
                                                cua.setApp(cenApp);
+                                               Long appId = null;
+                                               if (globalRole.toLowerCase().startsWith("global_")
+                                                               && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
+                                                               && !epApp.getId().equals(app.getId())) {
+                                                       appId = app.getId();
+                                                       EPRole result = null;
+                                                       if (globalRoleList.size() > 0)
+                                                               result = globalRoleList.stream()
+                                                                               .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
+                                                                               .orElse(null);
+                                                       if (result == null)
+                                                               continue;
+                                               } else {
+                                                       appId = userApp.getApp().getId();
+                                               }
                                                params.put("roleId", userApp.getRole().getId());
-                                               params.put(APP_ID, userApp.getApp().getId());
-                                               CentralV2Role centralRole;
-                                               List<EPRole> globalRoleList;
-                                               globalRoleList = getGlobalRolesOfPortal();
-                                               EPRole result = globalRoleList.stream().filter(x -> userApp.getRole().getId().equals(x.getId()))
-                                                               .findAny().orElse(null);
-                                               if (result != null && userApp.getApp().getId() != app.getId()) {
-                                                       userApp.getRole().setId(result.getId());
-                                                       centralRole = getGlobalRoleForRequestedApp(app.getId(), userApp.getRole().getId());
-                                                       cua.setRole(centralRole);
+                                               params.put(APP_ID, appId);
+                                               List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
+                                                               .executeNamedQuery("getAppRoleFunctionList", params, null);
+                                               SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
+                                               for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
+                                                       String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+                                                       String type = getFunctionCodeType(roleFunc.getCode());
+                                                       String action = getFunctionCodeAction(roleFunc.getCode());
+                                                       CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
+                                                                       functionCode, roleFunc.getName(), null, type, action, null);
+                                                       roleFunctionSet.add(cenRoleFunc);
+                                               }
+                                               Long userRoleId = null;
+                                               if (globalRole.toLowerCase().startsWith("global_")
+                                                               || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                                                       userRoleId = userApp.getRole().getId();
                                                } else {
-                                                       List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
-                                                                       .executeNamedQuery("getAppRoleFunctionList", params, null);
-                                                       SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
-                                                       for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
-                                                               String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
-                                                               CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
-                                                                               functionCode, roleFunc.getName(), null, null);
-                                                               roleFunctionSet.add(cenRoleFunc);
-                                                       }
-                                                       Long userRoleId = null;
-                                                       if (globalRole.toLowerCase().startsWith("global_")
-                                                                       && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
-                                                               userRoleId = userApp.getRole().getId();
-                                                       } else {
-                                                               userRoleId = userApp.getRole().getAppRoleId();
-                                                       }
-                                                       CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
-                                                                       userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
-                                                                       userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
-                                                                       userApp.getRole().getName(), userApp.getRole().getActive(),
-                                                                       userApp.getRole().getPriority(), roleFunctionSet, null, null);
-                                                       cua.setRole(cenRole);
+                                                       userRoleId = userApp.getRole().getAppRoleId();
                                                }
+                                               CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
+                                                               userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
+                                                               userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
+                                                               userApp.getRole().getName(), userApp.getRole().getActive(),
+                                                               userApp.getRole().getPriority(), roleFunctionSet, null, null);
+                                               cua.setRole(cenRole);
+
                                                userAppList.getUserApps().add(cua);
                                        }
                                }
@@ -1454,8 +1461,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
                                String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
                                functionCode = EPUserUtils.decodeFunctionCode(functionCode);
-                               String type = getFunctionType(roleFunc.getCode());
-                               String action = getFunctionAction(roleFunc.getCode());
+                               String type = getFunctionCodeType(roleFunc.getCode());
+                               String action = getFunctionCodeAction(roleFunc.getCode());
                                CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
                                                roleFunc.getName(), null, type, action, null);
                                roleFunctionSet.add(cenRoleFunc);
@@ -1480,9 +1487,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        @SuppressWarnings("unchecked")
        @Override
        public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
-               if (functionCode.contains("|"))
-                       functionCode = EcompPortalUtils.getFunctionCode(functionCode);
-               functionCode = encodeFunctionCode(functionCode);
+               String code = EcompPortalUtils.getFunctionCode(functionCode);
+               String encodedCode = encodeFunctionCode(code);
                CentralV2RoleFunction roleFunc = null;
                EPApp app = getApp(uebkey).get(0);
                List<CentralV2RoleFunction> getRoleFuncList = null;
@@ -1492,15 +1498,23 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        params.put(APP_ID, String.valueOf(app.getId()));
                        getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
                        if (getRoleFuncList.isEmpty()) {
-                               return roleFunc;
+                               params.put(FUNCTION_CODE_PARAMS, encodedCode);
+                               getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
+                               if (getRoleFuncList.isEmpty()) {
+                                       return roleFunc;
+                               }
+                       }
+                       if (getRoleFuncList.size() > 1) {
+                               CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
+                               if (cenV2RoleFunction == null)
+                                       return roleFunc;
+                               roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
                        } else {
-                               if (getRoleFuncList.size() > 1) {
-                                       CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(functionCode, getRoleFuncList);
-                                       if(cenV2RoleFunction == null)
-                                               return roleFunc;
-                                       roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
-                               } else {
+                               // Check even if single record have pipes
+                               if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
                                        roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
+                               } else {
+                                       roleFunc = getRoleFuncList.get(0);
                                }
                        }
                } catch (Exception e) {
@@ -1528,7 +1542,6 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                return roleFunc;
        }
 
-       @SuppressWarnings("unchecked")
        @Override
        public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
                boolean saveOrUpdateFunction = false;
@@ -1536,41 +1549,15 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
                        final Map<String, String> functionParams = new HashMap<>();
                        functionParams.put("appId", String.valueOf(app.getId()));
-                       List<CentralV2RoleFunction> appRoleFuncWithPipe = new ArrayList<>();
-                       // If request coming from portal application we use type, instance/code and action to fetch record
-                       if(domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null){
-                               functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getType()+FUNCTION_PIPE
-                                               +domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
-                               appRoleFuncWithPipe =  dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, functionParams, null);
-                               if(appRoleFuncWithPipe.isEmpty()){
-                                       functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getCode());
-                                       appRoleFuncWithPipe =  dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, functionParams, null);
-                               }
-                       } 
-                       // If request coming from SDK applications we use just function code to fetch record
-                       else{
-                               functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getCode());
-                       }               
-                       CentralV2RoleFunction appFunctionCode = null;
-                       if(!appRoleFuncWithPipe.isEmpty()){
-                               // Make sure we extract correct record if similar records are found as query uses like condition 
-                          appFunctionCode = appFunctionListFilter(domainCentralRoleFunction.getCode(), appRoleFuncWithPipe);   
-                          if(appFunctionCode == null){
-                                  appFunctionCode = domainCentralRoleFunction;
-                          }
-                       } else{
-                               appFunctionCode = domainCentralRoleFunction;
-                       }
-                       appFunctionCode.setName(domainCentralRoleFunction.getName());
                        if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
-                               addRoleFunctionInExternalSystem(appFunctionCode, app);                  
+                               addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);                        
                        }
                        if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
-                               appFunctionCode.setCode(domainCentralRoleFunction.getType()+
+                               domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
                                        FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
                        }
-                       appFunctionCode.setAppId(app.getId());
-                       dataAccessService.saveDomainObject(appFunctionCode, null);
+                       domainCentralRoleFunction.setAppId(app.getId());
+                       dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
                        saveOrUpdateFunction = true;
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
@@ -1704,8 +1691,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        ObjectMapper mapper = new ObjectMapper();
                        ExternalAccessPerms extPerms = new ExternalAccessPerms();
                        String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
-                       String checkType = getFunctionType(domainCentralRoleFunction.getCode());
-                       String actionValue = getFunctionAction(domainCentralRoleFunction.getCode());
+                       String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
+                       String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
                        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
                        extPerms.setAction(actionValue);
                        extPerms.setInstance(instanceValue);
@@ -2434,6 +2421,35 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                addRoleInExternalSystem(role, app.get(0));
                                rolesListAdded++;
                        }
+                       if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                               // Add Account Admin role in External AUTH System
+                               try {
+                                       String addAccountAdminRole = "";
+                                       ExternalAccessRole extRole = new ExternalAccessRole();
+                                       extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
+                                                       .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+                                       addAccountAdminRole = mapper.writeValueAsString(extRole);
+                                       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                                       HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
+                                       template.exchange(
+                                                       SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+                                                       HttpMethod.POST, entity, String.class);
+                                       rolesListAdded++;
+                               } catch (HttpClientErrorException e) {
+                                       logger.error(EELFLoggerDelegate.errorLogger,
+                                                       "HttpClientErrorException - Failed to create Account Admin role", e);
+                                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                               } catch (Exception e) {
+                                       if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                                               logger.error(EELFLoggerDelegate.errorLogger,
+                                                               "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
+                                                               e);
+                                       } else {
+                                               logger.error(EELFLoggerDelegate.errorLogger,
+                                                               "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
+                                       }
+                               }
+                       }
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
                        throw e;
@@ -2504,14 +2520,24 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
         * @param app
         */
        private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
-               String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+               String type = "";
+               String instance = "";
+               String action = "";
+               if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
+                       type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd()); 
+                       instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
+                       action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
+               } else{
+                       type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+                       instance = addRoleFunc.getFunctionCd();
+                       action = "*"; 
+               }
                ExternalAccessRolePerms extRolePerms = null;
                ExternalAccessPerms extPerms = null;
                ObjectMapper mapper = new ObjectMapper();
                try {
                        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
-
-                       extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*",
+                       extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
                                        addRoleFunc.getFunctionName());
                        extRolePerms = new ExternalAccessRolePerms(extPerms,
                                        app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
@@ -2531,16 +2557,73 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                }
        }
 
+       @SuppressWarnings("unchecked")
        @Override
-       public void bulkUploadPartnerFunctions(String uebkey, List<RoleFunction> roleFunctionsList) throws Exception {
+       public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
                EPApp app = getApp(uebkey).get(0);
-               CentralV2RoleFunction cenRoleFunc = null;
-               for (RoleFunction roleFunction : roleFunctionsList) {
-                       cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName());
-                       addRoleFunctionInExternalSystem(cenRoleFunc, app);
+               final Map<String, Long> params = new HashMap<>();
+               params.put("appId", app.getId());
+               List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
+                               null);
+               Integer functionsAdded = 0;
+               try {
+                       for (CentralV2RoleFunction roleFunc : roleFuncList) {
+                               addFunctionInExternalSystem(roleFunc, app);
+                               functionsAdded++;
+                       }
+               } catch (HttpClientErrorException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
                }
+               return functionsAdded;
        }
 
+       private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
+               ObjectMapper mapper = new ObjectMapper();
+               ExternalAccessPerms extPerms = new ExternalAccessPerms();
+               HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+               String type = "";
+               String instance = "";
+               String action = "";
+               if ((roleFunc.getCode().contains(FUNCTION_PIPE))
+                               || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
+                       type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
+                       instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+                       action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
+               } else {
+                       type = roleFunc.getCode().contains("menu") ? "menu" : "url";
+                       instance = roleFunc.getCode();
+                       action = "*";
+               }
+               try {
+                       extPerms.setAction(action);
+                       extPerms.setInstance(instance);
+                       extPerms.setType(app.getNameSpace() + "." + type);
+                       extPerms.setDescription(roleFunc.getName());
+                       String addFunction = mapper.writeValueAsString(extPerms);
+                       HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
+                       logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
+                                       CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
+                       ResponseEntity<String> addPermResponse = template.exchange(
+                                       SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+                                       HttpMethod.POST, entity, String.class);
+                       logger.debug(EELFLoggerDelegate.debugLogger,
+                                       "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
+                                       addPermResponse.getStatusCode().value(), addFunction);
+               } catch (HttpClientErrorException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "HttpClientErrorException - Failed to add function in external central auth system", e);
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                       throw e;
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
+                       throw e;
+               }
+       } 
+
        @Override
        public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
                EPApp app = getApp(uebkey).get(0);
@@ -2551,47 +2634,80 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
 
        @SuppressWarnings("unchecked")
        @Override
-       public void bulkUploadPartnerRoleFunctions(String uebkey, List<Role> roleList) throws Exception {
+       public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
                EPApp app = getApp(uebkey).get(0);
-               HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
-               for (Role role : roleList) {
-                       try {
-                               Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
-                               List<RoleFunction> roleFunctionListNew = new ArrayList<>();
-                               ObjectMapper roleFunctionsMapper = new ObjectMapper();
-                               Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
-                               while (itetaror.hasNext()) {
-                                       Object nextValue = itetaror.next();
-                                       RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class);
-                                       roleFunctionListNew.add(roleFunction);
-                               }
-                               List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct()
-                                               .collect(Collectors.toList());
-                               for (RoleFunction roleFunction : listWithoutDuplicates) {
-                                       String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url";
-                                       ExternalAccessRolePerms extRolePerms = null;
-                                       ExternalAccessPerms extPerms = null;
-                                       ObjectMapper mapper = new ObjectMapper();
-                                       extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(),
-                                                       "*");
-                                       extRolePerms = new ExternalAccessRolePerms(extPerms,
-                                                       app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
-                                       String updateRolePerms = mapper.writeValueAsString(extRolePerms);
-                                       HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
-                                       template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
-                                                       + "role/perm", HttpMethod.PUT, entity, String.class);
+               List<EPRole> roles = getAppRoles(app.getId());
+               final Map<String, Long> params = new HashMap<>();
+               Integer roleFunctions = 0;
+               try {
+                       for (EPRole role : roles) {
+                               params.put("roleId", role.getId());
+                               List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
+                                               params, null);
+                               if (!appRoleFunc.isEmpty()) {
+                                       for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
+                                               addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
+                                               roleFunctions++;
+                                       }
                                }
-                       } catch (Exception e) {
-                               if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
-                                       logger.error(EELFLoggerDelegate.errorLogger,
-                                                       "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality");
+                       }
+                       // upload global role functions to ext auth system
+                       if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                               roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
+                       }
+               } catch(HttpClientErrorException e){
+                       logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
+               }
+               return roleFunctions;
+       }
+
+       @SuppressWarnings("unchecked")
+       private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
+               try {
+                       EPApp portalApp = epAppService.getApp(1l);
+                       final Map<String, Long> params = new HashMap<>();
+                       params.put("appId", app.getId());
+                       List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
+                                       .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
+                       ObjectMapper mapper = new ObjectMapper();
+                       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                       for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
+                               ExternalAccessRolePerms extRolePerms;
+                               ExternalAccessPerms extPerms;
+                               String type = "";
+                               String instance = "";
+                               String action = "";
+                               if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+                                       type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
+                                       instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
+                                       action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
                                } else {
-                                       logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem",
-                                                       e);
+                                       type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+                                       instance = globalRoleFunc.getFunctionCd();
+                                       action = "*";
                                }
+                               extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
+                               extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
+                                               .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+                               String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+                               HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+                               updateRoleFunctionInExternalSystem(updateRolePerms, entity);
+                               roleFunctions++;
                        }
-
+               } catch (HttpClientErrorException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "HttpClientErrorException - Failed to add role function in external central auth system", e);
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                       throw e;
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
+                       throw e;
                }
+               return roleFunctions;
        }
 
        @Override
@@ -3104,79 +3220,116 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        @Override
        public List<String> getMenuFunctionsList(String uebkey) throws Exception {
                List<String> appMenuFunctionsList = null;
+               List<String> appMenuFunctionsFinalList = new ArrayList<>();
                try {
                        EPApp app = getApp(uebkey).get(0);
                        final Map<String, Long> appParams = new HashMap<>();
                        appParams.put(APP_ID, app.getId());
                        appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
+                       for(String appMenuFunction : appMenuFunctionsList) {
+                               if(appMenuFunction.contains(FUNCTION_PIPE)) {
+                                       appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
+                               } else {
+                                       appMenuFunctionsFinalList.add(appMenuFunction);
+                               }
+                       }
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
-                       return appMenuFunctionsList;
+                       return appMenuFunctionsFinalList;
                }
-               return appMenuFunctionsList;
+               return appMenuFunctionsFinalList;
        }
 
        @SuppressWarnings({ "unchecked"})
        @Override
        public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
                List<String> usersList = new ArrayList<>();
-               List<EcompUser> usersfinalList = new ArrayList<>();
-               try {
-                       EPApp app = getApp(uebkey).get(0);
-                       final Map<String, Long> appParams = new HashMap<>();
-                       appParams.put("appId", app.getId());
-                       List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
-                                       .executeNamedQuery("ApplicationUserRoles", appParams, null);
-                       for (EcompUserRoles ecompUserRole : userList) {
-                               boolean found = false;
-                               Set<EcompRole> roles = null;
-                               for (EcompUser user : usersfinalList) {
-                                       if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
-                                               EcompRole ecompRole = new EcompRole();
-                                               ecompRole.setId(ecompUserRole.getRoleId());
-                                               ecompRole.setName(ecompUserRole.getRoleName());
-                                               roles = user.getRoles();
-                                               roles.add(ecompRole);
-                                               user.setRoles(roles);
-                                               found = true;
-                                               break;
-                                       }
-                               }
-
-                               if (!found) {
-                                       EcompUser epUser = new EcompUser();
-                                       epUser.setOrgId(ecompUserRole.getOrgId());
-                                       epUser.setManagerId(ecompUserRole.getManagerId());
-                                       epUser.setFirstName(ecompUserRole.getFirstName());
-                                       epUser.setLastName(ecompUserRole.getLastName());
-                                       epUser.setPhone(ecompUserRole.getPhone());
-                                       epUser.setEmail(ecompUserRole.getEmail());
-                                       epUser.setOrgUserId(ecompUserRole.getOrgUserId());
-                                       epUser.setOrgCode(ecompUserRole.getOrgCode());
-                                       epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
-                                       epUser.setJobTitle(ecompUserRole.getJobTitle());
-                                       epUser.setLoginId(ecompUserRole.getLoginId());
-                                       epUser.setActive(true);
-                                       roles = new HashSet<>();
-                                       EcompRole ecompRole = new EcompRole();
-                                       ecompRole.setId(ecompUserRole.getRoleId());
-                                       ecompRole.setName(ecompUserRole.getRoleName());
-                                       roles.add(ecompRole);
-                                       epUser.setRoles(roles);
-                                       usersfinalList.add(epUser);
-                               }
-                       }
-                       ObjectMapper mapper = new ObjectMapper();
+        List<EcompUser> usersfinalList = new ArrayList<>();
+        try {
+               EPApp app = getApp(uebkey).get(0);
+               final Map<String, Long> appParams = new HashMap<>();
+               appParams.put("appId", app.getId());
+               List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
+                            .executeNamedQuery("ApplicationUserRoles", appParams, null);
+               for (EcompUserRoles ecompUserRole : userList) {
+                     boolean found = false;
+                     Set<EcompRole> roles = null;
+                     for (EcompUser user : usersfinalList) {
+                            if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
+                                   EcompRole ecompRole = new EcompRole();
+                                   ecompRole.setId(ecompUserRole.getRoleId());
+                                   ecompRole.setName(ecompUserRole.getRoleName());
+                                   roles = user.getRoles();
+                                   EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
+                                                 .orElse(null);
+                                   SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+                                   if(role != null)
+                                   {
+                                          roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
+                                   }
+                                          
+                             String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
+                            functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+                            EcompRoleFunction epRoleFunction = new EcompRoleFunction();
+                            epRoleFunction.setName(ecompUserRole.getFunctionName());
+                            epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
+                            epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
+                            epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
+                            roleFunctionSet.add(epRoleFunction);
+                        ecompRole.setRoleFunctions(roleFunctionSet);
+                                   roles.add(ecompRole);
+                                   user.setRoles(roles);
+                                   found = true;
+                                   break;
+                            }
+                     }
+
+                     if (!found) {
+                            EcompUser epUser = new EcompUser();
+                            epUser.setOrgId(ecompUserRole.getOrgId());
+                            epUser.setManagerId(ecompUserRole.getManagerId());
+                            epUser.setFirstName(ecompUserRole.getFirstName());
+                            epUser.setLastName(ecompUserRole.getLastName());
+                            epUser.setPhone(ecompUserRole.getPhone());
+                            epUser.setEmail(ecompUserRole.getEmail());
+                            epUser.setOrgUserId(ecompUserRole.getOrgUserId());
+                            epUser.setOrgCode(ecompUserRole.getOrgCode());
+                            epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
+                            epUser.setJobTitle(ecompUserRole.getJobTitle());
+                            epUser.setLoginId(ecompUserRole.getLoginId());
+                            epUser.setActive(true);
+                            roles = new HashSet<>();
+                            EcompRole ecompRole = new EcompRole();
+                            ecompRole.setId(ecompUserRole.getRoleId());
+                            ecompRole.setName(ecompUserRole.getRoleName());
+              SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+              
+                            String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
+              functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+              EcompRoleFunction epRoleFunction = new EcompRoleFunction();
+              epRoleFunction.setName(ecompUserRole.getFunctionName());
+              epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
+              epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
+              epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
+              roleFunctionSet.add(epRoleFunction);
+              ecompRole.setRoleFunctions(roleFunctionSet);
+                            roles.add(ecompRole);
+                            epUser.setRoles(roles);
+                            usersfinalList.add(epUser);
+                     }
+               }
+               ObjectMapper mapper = new ObjectMapper();
+
+               for (EcompUser u1 : usersfinalList) {
+                     String str = mapper.writeValueAsString(u1);
+                     usersList.add(str);
+               }
+        } catch (Exception e) {
+               logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
+               throw e;
+        }
+        return usersfinalList;
 
-                       for (EcompUser u1 : usersfinalList) {
-                               String str = mapper.writeValueAsString(u1);
-                               usersList.add(str);
-                       }
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
-                       throw e;
-               }
-               return usersfinalList;
        }
        
 
@@ -3301,8 +3454,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
                        cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
                } else{
-                       type = getFunctionType(role.getFunctionCd());
-                       action = getFunctionAction(role.getFunctionCd());
+                       type = getFunctionCodeType(role.getFunctionCd());
+                       action = getFunctionCodeAction(role.getFunctionCd());
                        cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
                }
                return cenRoleFun;
@@ -3328,10 +3481,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        }
        
        @Override
-       public List<RoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
-               List<RoleFunction> addRoleFuncList = new ArrayList<>();
+       public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
+               List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
                for(CentralV2RoleFunction cenRoleFunc : answer){
-                       RoleFunction setRoleFunc = new RoleFunction();
+                       CentralRoleFunction setRoleFunc = new CentralRoleFunction();
                        setRoleFunc.setCode(cenRoleFunc.getCode());
                        setRoleFunc.setName(cenRoleFunc.getName());
                        addRoleFuncList.add(setRoleFunc);
@@ -3348,6 +3501,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
+                       throw e;
                }
                return sendUserRoles;
        }
@@ -3391,7 +3545,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                        CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());                                                            
                                        cenRoleFunction.add(cenRoleFunc);
                                }
-                               CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(),
+                               CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
                                                cenRoleFunction);
                                cua.setRole(role);
                                userApps.add(cua);
@@ -3417,13 +3571,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        @Override
        public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
                List<CentralRole> cenRoleList = new ArrayList<>();
-               SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
                        for(CentralV2Role v2CenRole : v2CenRoleList){
+                               SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
                                for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
                                        CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
                                        cenRoleFuncList.add(roleFunc);
                                }
-                               CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList);
+                               CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
                                cenRoleList.add(role);
                        }               
                return cenRoleList;
@@ -3459,7 +3613,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
                        cenRoleFuncList.add(roleFunc);
                }
-               return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
+               return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
                                cenRoleFuncList);
        }
 
@@ -3498,4 +3652,207 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
                return encodedString;
        }
+       
+       @Override
+       public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
+               ObjectMapper mapper = new ObjectMapper();
+               HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+               try {
+                       ExternalAccessRolePerms extRolePerms;
+                       ExternalAccessPerms extPerms;
+                       extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
+                       String appNameSpace = "";
+                       if(data.getIsGlobalRolePartnerFunc()) {
+                               appNameSpace =  epAppService.getApp(1l).getNameSpace();
+                       } else {
+                               appNameSpace =  app.getNameSpace();
+                       }
+                       extRolePerms = new ExternalAccessRolePerms(extPerms,
+                                       appNameSpace + "."
+                                                       + data.getRoleName().replaceAll(
+                                                                       EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
+                                                                       "_"));
+                       String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+                       HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+                       updateRoleFunctionInExternalSystem(updateRolePerms, entity);
+               } catch (HttpClientErrorException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "HttpClientErrorException - Failed to add role function in external central auth system", e);
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                       throw e;
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
+                       throw e;
+               }
+               
+       }
+
+       private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
+               logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
+                               CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+               ResponseEntity<String> addPermResponse = template.exchange(
+                               SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+                               HttpMethod.POST, entity, String.class);
+               logger.debug(EELFLoggerDelegate.debugLogger,
+                               "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
+                               addPermResponse.getStatusCode().value(), updateRolePerms);
+       }
+       
+       @Override
+       public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
+               String name = "";
+               if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                       name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+               }
+               HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+               HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
+               ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
+               List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
+               String res = getResponse.getBody();
+               JSONObject jsonObj = null;
+               JSONArray extRoles = null;
+               if (!res.equals("{}")) {
+                       jsonObj = new JSONObject(res);
+                       extRoles = jsonObj.getJSONArray("role");
+               }
+               updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
+       }
+
+       @SuppressWarnings("unchecked")
+       private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
+                       String loginId) throws InvalidUserException {
+               HashMap<String, String> userParams = new HashMap<>();
+               userParams.put("orgUserId", loginId);
+               // Get all centralized applications existing user roles from local
+               List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
+                               .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
+               EPUser user = getUser(loginId).get(0);
+               // Get all centralized applications roles from local
+               HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
+               HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
+                               currentUserAppRoles);
+               // Get all centralized applications + admin role from local
+               HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
+               if (extRoles != null) {
+                       ExternalAccessUserRoleDetail userRoleDetail = null;
+                       for (int i = 0; i < extRoles.length(); i++) {
+                               if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
+                                               && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
+                                       userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
+                                                       null);
+                                       userRoleDetailList.add(userRoleDetail);
+                               }
+                       }
+                       addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
+                                       centralisedAppsMap);
+               }
+       }
+
+       private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
+                       HashMap<String, CentralizedAppRoles> cenAppRolesMap,
+                       HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
+                       HashMap<String, EPApp> centralisedAppsMap) {
+               for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
+                       try {
+                               // check if user already has role in local
+                               if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
+                                       CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
+                                       if (getCenAppRole != null) {
+                                               logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system  {}",
+                                                               extUserRoleDetail.toString());
+                                               EPUserApp userApp = new EPUserApp();
+                                               EPApp app = new EPApp();
+                                               app.setId(getCenAppRole.getAppId());
+                                               EPRole epRole = new EPRole();
+                                               epRole.setId(getCenAppRole.getRoleId());
+                                               userApp.setApp(app);
+                                               userApp.setUserId(user.getId());
+                                               userApp.setRole(epRole);
+                                               dataAccessService.saveDomainObject(userApp, null);
+                                               logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system  {}",
+                                                               extUserRoleDetail.toString());
+                                       } else if (getCenAppRole == null // check if user has app account admin role
+                                                       && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
+                                                                       EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
+                                               EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
+                                               if (app != null) {
+                                                       logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system  {}",
+                                                                       extUserRoleDetail.toString());
+                                                       EPUserApp userApp = new EPUserApp();
+                                                       EPRole epRole = new EPRole();
+                                                       epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
+                                                       userApp.setApp(app);
+                                                       userApp.setUserId(user.getId());
+                                                       userApp.setRole(epRole);
+                                                       dataAccessService.saveDomainObject(userApp, null);
+                                                       logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system  {}",
+                                                                       extUserRoleDetail.toString());
+                                               }
+                                       }
+                               }
+                       } catch (Exception e) {
+                               logger.error(EELFLoggerDelegate.errorLogger,
+                                               "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
+                                               extUserRoleDetail.toString(), e);
+                       }
+               }
+       }
+
+       @SuppressWarnings("unchecked")
+       private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
+               List<EPApp> centralizedApps = dataAccessService
+                               .executeNamedQuery("getCentralizedApps", null, null);
+               HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
+               for (EPApp cenApp : centralizedApps) {
+                       centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
+                                       PortalConstants.ADMIN_ROLE.replaceAll(
+                                                       EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
+               }
+               return centralisedAppsMap;
+       }
+
+       private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
+                       List<CentralizedAppRoles> currentUserAppRoles) {
+               HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
+               for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
+                       currentCentralizedUserAppRolesMap.put(
+                                       cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
+                                                       .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+                                                       cenAppUserRole);
+               }
+               return currentCentralizedUserAppRolesMap;
+       }
+
+       @SuppressWarnings("unchecked")
+       private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
+               List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
+                               .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
+               HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
+               for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
+                       cenAppRolesMap.put(
+                                       CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
+                                                       .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+                                       CentralizedAppRole);
+               }
+               return cenAppRolesMap;
+       }
+       
+       @Override
+       public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
+               logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
+               ResponseEntity<String> getResponse = template
+                               .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                                               + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
+               if (getResponse.getStatusCode().value() == 200) {
+                       logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
+                                       getResponse.getBody());
+
+               }else{
+                       logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
+               }
+               return getResponse;
+       }
+
 }