MariaDB Connector and Sonar Scans; clean nl
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / ExternalAccessRolesServiceImpl.java
index 95e5ddc..97fa98e 100644 (file)
@@ -2,6 +2,7 @@ package org.openecomp.portalapp.portal.service;
 
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
@@ -11,6 +12,7 @@ import java.util.SortedSet;
 import java.util.TreeSet;
 import java.util.stream.Collectors;
 
+import org.apache.commons.lang.StringUtils;
 import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
@@ -33,6 +35,7 @@ import org.openecomp.portalapp.portal.transport.CentralApp;
 import org.openecomp.portalapp.portal.transport.CentralRole;
 import org.openecomp.portalapp.portal.transport.CentralUser;
 import org.openecomp.portalapp.portal.transport.CentralUserApp;
+import org.openecomp.portalapp.portal.transport.EcompUserRoles;
 import org.openecomp.portalapp.portal.transport.ExternalAccessPerms;
 import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail;
 import org.openecomp.portalapp.portal.transport.ExternalAccessRole;
@@ -45,6 +48,8 @@ import org.openecomp.portalapp.portal.utils.PortalConstants;
 import org.openecomp.portalsdk.core.domain.Role;
 import org.openecomp.portalsdk.core.domain.RoleFunction;
 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.restful.domain.EcompUser;
 import org.openecomp.portalsdk.core.service.DataAccessService;
 import org.openecomp.portalsdk.core.util.SystemProperties;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -69,6 +74,18 @@ import com.fasterxml.jackson.databind.type.TypeFactory;
 @EPAuditLog
 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
 
+       private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
+
+       private static final String OWNER = ".owner";
+
+       private static final String ADMIN = ".admin";
+
+       private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
+
+       private static final String FUNCTION_CD_LIKE_CLAUSE = " and function_cd like '%";
+
+       private static final String FUNCTION_PIPE = "|";
+
        private static final String IS_NULL_STRING = "null";
 
        private static final String EXTERNAL_AUTH_PERMS = "perms";
@@ -133,7 +150,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                List<EPApp> app = null;
                try {
                        app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null);
-                       if(!app.get(0).getEnabled()){
+                       if(!app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
                                throw new Exception("Application:"+app.get(0).getName()+" is Unavailable");
                        }
                } catch (Exception e) {
@@ -225,7 +242,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                ExternalAccessRolePerms extRolePerms = null;
                ExternalAccessPerms extPerms = null;
                List<EPRole> epRoleList = null;
-               epRoleList = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + updateExtRole.getId(), null, null);
+               if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                       epRoleList = dataAccessService.getList(EPRole.class,
+                                       WHERE_ROLE_ID_EQUALS + updateExtRole.getId() + " and app_id is null", null, null);
+               } else {
+                       epRoleList = dataAccessService.getList(EPRole.class,
+                                       " where app_role_id = " + updateExtRole.getId() + " and app_id = " + app.getId(), null, null);
+               }               
                String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
                if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
                        JSONObject jsonObj = new JSONObject(appRole);
@@ -268,9 +291,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                        addRole(updateExtRole, app.getUebKey());
                                        addRoleFunctionsInExternalSystem(updateExtRole, mapper, app);
                                }
+                               boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),String.valueOf(updateExtRole.getPriority()));
                                ExternalAccessRole updateRole = new ExternalAccessRole();
                                if (!isActiveValueChanged
-                                               || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority()))
+                                               || !checkPriorityStatus
                                                || sysRoleList.getId().equals(IS_NULL_STRING)
                                                || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) {
                                        String updateDesc = "";
@@ -278,17 +302,17 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                                        : APP_ID_EQUALS + app.getId();
                                        List<EPRole> getRole = dataAccessService.getList(EPRole.class,
                                                        WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null);
-                                       Map<String, Object> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
-                                       extSystemUpdateRoleJsonMapper.put(ID, getRole.get(0).getId());
-                                       extSystemUpdateRoleJsonMapper.put(ROLE_NAME, updateExtRole.getName());
-                                       extSystemUpdateRoleJsonMapper.put(ACTIVE, updateExtRole.getActive());
-                                       extSystemUpdateRoleJsonMapper.put(PRIORITY, updateExtRole.getPriority());
+                                       Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>();
+                                       extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId()));
+                                       extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName()));
+                                       extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive()));
+                                       extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority()));
                                        if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
-                                               extSystemUpdateRoleJsonMapper.put(APP_ID, null);
-                                               extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, null);
+                                               extSystemUpdateRoleJsonMapper.put(APP_ID, "null");
+                                               extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null");
                                        } else {
-                                               extSystemUpdateRoleJsonMapper.put(APP_ID, app.getId());
-                                               extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, getRole.get(0).getAppRoleId());
+                                               extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId()));
+                                               extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, String.valueOf(getRole.get(0).getAppRoleId()));
 
                                        }
                                        updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper);
@@ -465,13 +489,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                String addNewRole = "";
                ExternalAccessRole extRole = new ExternalAccessRole();
                String addDesc = null;
-               Map<String, Object> extSystemJsonMapper = new LinkedHashMap<>();
-               extSystemJsonMapper.put(ID, newRole.get(0).getId());
-               extSystemJsonMapper.put(ROLE_NAME, newRole.get(0).getName());
-               extSystemJsonMapper.put(ACTIVE, newRole.get(0).getActive());
-               extSystemJsonMapper.put(PRIORITY, newRole.get(0).getPriority());
-               extSystemJsonMapper.put(APP_ID, newRole.get(0).getAppId());
-               extSystemJsonMapper.put(APP_ROLE_ID, newRole.get(0).getAppRoleId());
+               Map<String, String> extSystemJsonMapper = new LinkedHashMap<>();
+               extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId()));
+               extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName()));
+               extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive()));
+               extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority()));
+               extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId()));
+               extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId()));
                addDesc = mapper.writeValueAsString(extSystemJsonMapper);
                extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_"));
                extRole.setDescription(addDesc);
@@ -508,18 +532,18 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                ExternalAccessRole extRole = new ExternalAccessRole();
                List<EPRole> role = null;
                String addDesc = null;
-               Map<String, Object> extSystemUpdateRole = new LinkedHashMap<>();
+               Map<String, String> extSystemUpdateRole = new LinkedHashMap<>();
                if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
-                       role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId(), null, null);
+                       role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId() + " and app_id is null", null, null);
                } else {
-                       role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId(), null, null);
+                       role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId() + " and app_id ="+app.getId(), null, null);
                }
-               extSystemUpdateRole.put(ID, role.get(0).getId());
-               extSystemUpdateRole.put(ROLE_NAME, addRole.getName());
-               extSystemUpdateRole.put(ACTIVE, role.get(0).getActive());
-               extSystemUpdateRole.put(PRIORITY, role.get(0).getPriority());
-               extSystemUpdateRole.put(APP_ID, role.get(0).getAppId());
-               extSystemUpdateRole.put(APP_ROLE_ID, role.get(0).getAppRoleId());
+               extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId()));
+               extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName()));
+               extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive()));
+               extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority()));
+               extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId()));
+               extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId()));
                addDesc = mapper.writeValueAsString(extSystemUpdateRole);
                extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_"));
                extRole.setDescription(addDesc);
@@ -652,13 +676,17 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
         * @param applicationRoles
         * @throws Exception
         */
+       @SuppressWarnings("unchecked")
        private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles)
                        throws Exception {
                for (RoleFunction roleFunc : roleFunctionListNew) {
                        EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
                        appRoleFunc.setAppId(app.getId());
                        appRoleFunc.setRoleId(applicationRoles.get(0).getId());
-                       appRoleFunc.setCode(roleFunc.getCode());
+                       // query to check if function code is different for safe operation
+                       List<CentralRoleFunction> roleFunction = dataAccessService.getList(CentralRoleFunction.class,
+                                       WHERE_APP_ID_EQUALS+ app.getId()+FUNCTION_CD_LIKE_CLAUSE + roleFunc.getCode() + "'", null, null);
+                       appRoleFunc.setCode(roleFunction.get(0).getCode());
                        dataAccessService.saveDomainObject(appRoleFunc, null);
                }
        }
@@ -739,15 +767,33 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        @Override
        public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception {
                EPApp app = getApp(uebkey).get(0);
-               List<CentralRoleFunction> getRoleFuncList = null;
+               List<CentralRoleFunction> finalRoleList = new ArrayList<>();
                final Map<String, Long> params = new HashMap<>();
                params.put(APP_ID, app.getId());
                // Sync all functions from external system into Ecomp portal DB
                logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem");
                syncRoleFunctionFromExternalAccessSystem(app);
                logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem");
-               getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
-               return getRoleFuncList;
+               List<CentralRoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
+               for(CentralRoleFunction roleFuncItem : getRoleFuncList ){
+                       if(roleFuncItem.getCode().contains(FUNCTION_PIPE)){
+                               String code = "";
+                               int count = StringUtils.countMatches(roleFuncItem.getCode(), FUNCTION_PIPE);
+                               if (count == 2)
+                                       code = roleFuncItem.getCode().substring(
+                                                       roleFuncItem.getCode().indexOf(FUNCTION_PIPE) + 1,
+                                                       roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE));
+                               else
+                                       code = roleFuncItem.getCode()
+                                                       .substring(roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
+                               
+                               roleFuncItem.setCode(code);
+                               finalRoleList.add(roleFuncItem);
+                       } else{
+                               finalRoleList.add(roleFuncItem);
+                       }
+               }
+               return finalRoleList;
        }
 
        /**
@@ -792,8 +838,24 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                                                .executeNamedQuery("getAppRoleFunctionList", params, null);
                                                SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
                                                for (CentralRoleFunction roleFunc : appRoleFunctionList) {
-                                                       CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(),
-                                                                       roleFunc.getCode(), roleFunc.getName(), null, null);
+                                                       String functionCode = "";
+                                                       if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+                                                               int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
+                                                               String finalFunctionCodeVal;
+                                                               if (count == 2)
+                                                                       finalFunctionCodeVal = roleFunc.getCode().substring(
+                                                                                       roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
+                                                                                       roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
+                                                               else
+                                                                       finalFunctionCodeVal = roleFunc.getCode()
+                                                                                       .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
+
+                                                               functionCode = finalFunctionCodeVal;
+                                                       } else {
+                                                               functionCode = roleFunc.getCode();
+                                                       }
+                                                       CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), functionCode,
+                                                                       roleFunc.getName(), null, null);
                                                        roleFunctionSet.add(cenRoleFunc);
                                                }
                                                Long userRoleId = null;
@@ -892,7 +954,22 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                        params, null);
                        SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>();
                        for (CentralRoleFunction roleFunc : cenRoleFuncList) {
-                               CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(),
+                               String functionCode = "";
+                               if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+                                       int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE);
+                                       String finalFunctionCodeVal;
+                                       if (count == 2)
+                                               finalFunctionCodeVal = roleFunc.getCode().substring(
+                                                               roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1,
+                                                               roleFunc.getCode().lastIndexOf(FUNCTION_PIPE));
+                                       else
+                                               finalFunctionCodeVal = roleFunc.getCode()
+                                                               .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1);
+                                       functionCode = finalFunctionCodeVal;
+                               } else {
+                                       functionCode = roleFunc.getCode();
+                               }
+                               CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), functionCode,
                                                roleFunc.getName(), null, null);
                                roleFunctionSet.add(cenRoleFunc);
                        }
@@ -925,13 +1002,20 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null);
                        if (getRoleFuncList.isEmpty()) {
                                return roleFunc;
+                       } else{
+                               String functionCodeFormat = getRoleFuncList.get(0).getCode();
+                               if(functionCodeFormat.contains(FUNCTION_PIPE)){
+                                       String newfunctionCodeFormat = functionCodeFormat.substring(functionCodeFormat.lastIndexOf(FUNCTION_PIPE)+1); 
+                                       roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), newfunctionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
+                               } else{
+                                       roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), functionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl());
+                               }
                        }
-
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
                        throw new Exception("getRoleFunction failed", e);
                }
-               return getRoleFuncList.get(0);
+               return roleFunc;
        }
 
        @Override
@@ -959,13 +1043,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
        private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app)
                        throws Exception {
                ObjectMapper mapper = new ObjectMapper();
-               final Map<String, String> params = new HashMap<>();
-               params.put("functionCd", domainCentralRoleFunction.getCode());
-               params.put(APP_ID, String.valueOf(app.getId()));
                ExternalAccessPerms extPerms = new ExternalAccessPerms();
                HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
-               List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params,
-                               null);
+               List<CentralRoleFunction> appRoleFunc = dataAccessService.getList(CentralRoleFunction.class,
+                               WHERE_APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + domainCentralRoleFunction.getCode() + "'", null, null);
                String roleFuncName = null;
                if (!appRoleFunc.isEmpty()) {
                        roleFuncName = appRoleFunc.get(0).getCode();
@@ -1034,10 +1115,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                boolean deleteFunctionResponse = false;
                try {
                        final Map<String, String> params = new HashMap<>();
-                       params.put("functionCd", code);
+                       params.put("functionCode", code);
                        params.put(APP_ID, String.valueOf(app.getId()));
                        CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService
-                                       .executeNamedQuery("getAppFunctionDetails", params, null).get(0);
+                                       .executeNamedQuery("getRoleFunction", params, null).get(0);
                        deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
                        // Delete role function dependency records
                        deleteAppRoleFunctions(code, app);
@@ -1057,7 +1138,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
         */
        private void deleteAppRoleFunctions(String code, EPApp app) {
                dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
-                               APP_ID_EQUALS + app.getId() + " and function_cd = '" + code + "'", null);
+                               APP_ID_EQUALS + app.getId() + FUNCTION_CD_LIKE_CLAUSE + code + "'", null);
        }
        
        /**
@@ -1073,7 +1154,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                try {
                        ObjectMapper mapper = new ObjectMapper();
                        ExternalAccessPerms extPerms = new ExternalAccessPerms();
-                       String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
+                       String instanceValue = "";
+                       if(domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
+                               instanceValue = domainCentralRoleFunction.getCode().substring(domainCentralRoleFunction.getCode().lastIndexOf(FUNCTION_PIPE)+1);
+                       }else{
+                               instanceValue = domainCentralRoleFunction.getCode();
+                       }
+                       String checkType = instanceValue.contains("menu") ? "menu" : "url";
                        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
                        extPerms.setAction("*");
                        extPerms.setInstance(domainCentralRoleFunction.getCode());
@@ -1298,21 +1385,29 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        ExternalAccessPermsDetail permDetails = null;
                        List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
                        for (int i = 0; i < extPerms.length(); i++) {
+                               String description = null;
+                               if(extPerms.getJSONObject(i).has("description")){
+                                       description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+                               } else{
+                                       description = extPerms.getJSONObject(i).getString("instance");
+                               }
                                if (extPerms.getJSONObject(i).has("roles")) {
                                        ObjectMapper rolesListMapper = new ObjectMapper();
                                        JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
                                        List<String> list = rolesListMapper.readValue(resRoles.toString(),
                                                        TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
                                        permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
-                                                       extPerms.getJSONObject(i).getString("instance"),
-                                                       extPerms.getJSONObject(i).getString("action"), list,
-                                                       extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION));
+                                                       extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
+                                                                       + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
+                                                                       + extPerms.getJSONObject(i).getString("action"),
+                                                       extPerms.getJSONObject(i).getString("action"), list, description);
                                        permsDetailList.add(permDetails);
                                } else {
                                        permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
-                                                       extPerms.getJSONObject(i).getString("instance"),
-                                                       extPerms.getJSONObject(i).getString("action"),
-                                                       extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION));
+                                                       extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
+                                                                       + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
+                                                                       + extPerms.getJSONObject(i).getString("action"),
+                                                       extPerms.getJSONObject(i).getString("action"), description);
                                        permsDetailList.add(permDetails);
                                }
                        }
@@ -1329,20 +1424,34 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        }
                        // delete all application role functions
                        dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
-
                        // Add if new functions and app role functions were added in external auth system
                        for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
-                               if (!roleFuncMap.containsKey(permsDetail.getInstance())) {
-                                       try{
-                                       CentralRoleFunction addFunction = new CentralRoleFunction();
-                                       addFunction.setAppId(app.getId());
-                                       addFunction.setCode(permsDetail.getInstance());
-                                       addFunction.setName(permsDetail.getDescription());
-                                       dataAccessService.saveDomainObject(addFunction, null);
-                                       } catch(Exception e){
-                                               logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to add function", e);
+                               String code = permsDetail.getInstance();
+                               CentralRoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
+                               if (null == getFunctionCodeKey) {
+                                       String finalFunctionCodeVal = "";
+                                       if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
+                                               int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
+                                               if (count == 2)
+                                                       finalFunctionCodeVal = permsDetail.getInstance().substring(
+                                                                       permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
+                                                                       permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
+                                               else
+                                                       finalFunctionCodeVal = permsDetail.getInstance()
+                                                                       .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
+                                       } else {
+                                               finalFunctionCodeVal = permsDetail.getInstance();
                                        }
-                               }
+                                       CentralRoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
+                                       if (null == checkIfCodeStillExits) {
+                                               logger.debug(EELFLoggerDelegate.debugLogger,
+                                                               "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
+                                               addFunctionInEcompDB(app, permsDetail, code);
+                                               logger.debug(EELFLoggerDelegate.debugLogger,
+                                                               "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
+
+                                       }
+                               }                               
                                List<EPRole> epRolesList = null;
                                List<String> roles = permsDetail.getRoles();
                                if (roles != null) {
@@ -1372,17 +1481,53 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                                                                                + roleList.substring(app.getNameSpace().length() + 1) + "'",
                                                                                null, null);
                                                        }
+                                                       // Adding new role thats does not exits in Local but exists in external access system
+                                                       if (epRolesList.isEmpty()) {
+                                                               Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
+                                                               addIfRoleDescriptionNotExitsInExtSystem(role, app);
+                                                               epRolesList = dataAccessService.getList(EPRole.class,
+                                                                               WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '"
+                                                                                               + role.getName() + "'",
+                                                                               null, null);
+                                                       }
                                                }
                                                // save all application role functions
                                                if (!epRolesList.isEmpty()) {
-                                                       try{
-                                                       EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
-                                                       addAppRoleFunc.setAppId(app.getId());
-                                                       addAppRoleFunc.setCode(permsDetail.getInstance());
-                                                       addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
-                                                       dataAccessService.saveDomainObject(addAppRoleFunc, null);
-                                                       } catch(Exception e){
-                                                               logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
+                                                       try {
+                                                               List<CentralRoleFunction> roleFunctionList = null;
+                                                               String functionCode = "";
+                                                               if (permsDetail.getInstance().contains(FUNCTION_PIPE)) {
+                                                                       int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE);
+                                                                       String finalFunctionCodeVal;
+                                                                       if (count == 2)
+                                                                               finalFunctionCodeVal = permsDetail.getInstance().substring(
+                                                                                               permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1,
+                                                                                               permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE));
+                                                                       else
+                                                                               finalFunctionCodeVal = permsDetail.getInstance()
+                                                                                               .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1);
+
+                                                                       functionCode = finalFunctionCodeVal;
+                                                               }
+                                                               roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
+                                                                               " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + functionCode + "'",
+                                                                               null, null);
+                                                               if (roleFunctionList.isEmpty()) {
+                                                                       roleFunctionList = dataAccessService.getList(CentralRoleFunction.class,
+                                                                                       " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'",
+                                                                                       null, null);
+                                                               }
+                                                               if (!roleFunctionList.isEmpty()) {
+                                                                       EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
+                                                                       addAppRoleFunc.setAppId(app.getId());
+                                                                       addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
+                                                                       addAppRoleFunc.setRoleId(epRolesList.get(0).getId());
+                                                                       dataAccessService.saveDomainObject(addAppRoleFunc, null);
+                                                               }
+                                                       } catch (Exception e) {
+                                                               logger.error(EELFLoggerDelegate.errorLogger,
+                                                                               "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
+                                                                               e);
                                                        }
                                                }
                                        }
@@ -1394,6 +1539,97 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
 
                }
        }
+       
+       /**
+        * 
+        * Add function into local DB
+        * 
+        * @param app
+        * @param permsDetail
+        * @param code
+        */
+       private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
+               try{
+               CentralRoleFunction addFunction = new CentralRoleFunction();
+               addFunction.setAppId(app.getId());
+               addFunction.setCode(code);
+               addFunction.setName(permsDetail.getDescription());
+               dataAccessService.saveDomainObject(addFunction, null);
+               } catch(Exception e){
+                       logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
+               }
+       }
+
+       /**
+        * 
+        * It updates description of a role in external auth system
+        * 
+        * @param role
+        * @param app
+        * @throws Exception
+        */
+       private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
+               String addRoleNew = updateExistingRoleInExternalSystem(role, app);
+               HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+               try {
+                       HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
+                       template.exchange(
+                                       SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+                                       HttpMethod.PUT, entity, String.class);
+               } catch (HttpClientErrorException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
+                                       e);
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
+                                       e);
+               }
+       }
+
+       /**
+        * 
+        * While sync functions form external auth system if new role found we should add in local and return Role.class object
+        * 
+        * @param app
+        * @param role
+        * @return
+        */
+       @SuppressWarnings("unchecked")
+       private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
+               Role setNewRole = new Role();
+               EPRole epRoleNew = new EPRole();
+               try {
+                       epRoleNew.setActive(true);
+                       epRoleNew.setName(role);
+                       if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                               epRoleNew.setAppId(null);
+                       } else {
+                               epRoleNew.setAppId(app.getId());
+                       }
+                       dataAccessService.saveDomainObject(epRoleNew, null);
+                       List<EPRole> getRoleCreated = null;
+                       if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                               List<EPRole> roleCreated = dataAccessService.getList(EPRole.class,
+                                               WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
+                               EPRole epUpdateRole = roleCreated.get(0);
+                               epUpdateRole.setAppRoleId(epUpdateRole.getId());
+                               dataAccessService.saveDomainObject(epUpdateRole, null);
+                               getRoleCreated = dataAccessService.getList(EPRole.class,
+                                               WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null);
+                       } else {
+                               getRoleCreated = dataAccessService.getList(EPRole.class,
+                                               WHERE_ROLE_NAME_EQUALS + role + "' and app_id is null", null, null);
+                       }
+                       EPRole roleObject = getRoleCreated.get(0);
+                       setNewRole.setId(roleObject.getId());
+                       setNewRole.setName(roleObject.getName());
+                       setNewRole.setActive(roleObject.getActive());
+                       setNewRole.setPriority(roleObject.getPriority());
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
+               }
+               return setNewRole;
+       }
 
        @Override
        @SuppressWarnings("unchecked")
@@ -1610,28 +1846,27 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                        ObjectMapper mapper = new ObjectMapper();
                        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
                        HttpEntity<String> entity = new HttpEntity<>(headers);
-                       logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+                       logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
+                                       CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
                        response = template
                                        .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
                                                        + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
                        String res = response.getBody();
-                       logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
+                       logger.debug(EELFLoggerDelegate.debugLogger,
+                                       "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
                                        res);
                        JSONObject jsonObj = new JSONObject(res);
                        JSONArray extRole = jsonObj.getJSONArray("role");
                        for (int i = 0; i < extRole.length(); i++) {
-                               if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".admin")
-                                               || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".owner")) {
+                               if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
+                                               || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
+                                               || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
+                                                               && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
                                        extRole.remove(i);
                                        i--;
-                               }
-                               if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get(ROLE_NAME)
-                                               .equals(app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))) {
-                                       extRole.remove(i);
-                                       i--;
-                               }
+                               }                       
                        }
-                       List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>();
+                       dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
                        for (int i = 0; i < extRole.length(); i++) {
                                ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
                                EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
@@ -1664,7 +1899,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                if (ApplicationRole.getActive().equals(IS_NULL_STRING)) {
                                        externalRoleDetail.setActive(false);
                                } else {
-                                       externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString()));
+                                       externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive()));
                                }
                                externalRoleDetail.setName(ApplicationRole.getName());
 
@@ -1673,13 +1908,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) {
                                        externalRoleDetail.setAppId(app.getId());
                                } else {
-                                       externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString()));
+                                       externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId()));
                                }
 
                                if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) {
                                        externalRoleDetail.setPriority(null);
                                } else {
-                                       externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString()));
+                                       externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority()));
                                }
 
                                if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) {
@@ -1687,17 +1922,40 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                }
 
                                if (!externalAccessPermsOfRole.isEmpty()) {
+                                       // Adding functions to roles  
                                        for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
-                                               EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
-                                               apRoleFunction.setAppId(app.getId());
-                                               apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
-                                               apRoleFunction.setCode(externalpermission.getInstance());
-                                               applicationRoleFunctionList.add(apRoleFunction);
+                                               try {
+                                                       logger.debug(EELFLoggerDelegate.debugLogger,
+                                                                       "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
+                                                                       externalpermission.getInstance());
+                                                       List<CentralRoleFunction> roleFunction = null;
+                                                       roleFunction = dataAccessService.getList(
+                                                                       CentralRoleFunction.class, " where function_cd = '"
+                                                                                       + externalpermission.getInstance() + "' and " + APP_ID_EQUALS + app.getId(),
+                                                                       null, null);
+                                                       if (roleFunction.isEmpty()) {
+                                                               String funcCode = externalpermission.getType()
+                                                                               .substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
+                                                                               + externalAccessPerms.getInstance();
+                                                               roleFunction = dataAccessService.getList(CentralRoleFunction.class,
+                                                                               " where function_cd = '" + funcCode + "' and " + APP_ID_EQUALS + app.getId(), null,
+                                                                               null);
+                                                       }
+                                                       if(!roleFunction.isEmpty()){
+                                                       EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
+                                                       apRoleFunction.setAppId(app.getId());
+                                                       apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId()));
+                                                       apRoleFunction.setCode(roleFunction.get(0).getCode());
+                                                       dataAccessService.saveDomainObject(apRoleFunction, null);
+                                                       }
+                                               } catch (Exception e) {
+                                                       logger.error(EELFLoggerDelegate.errorLogger,
+                                                                       "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
+                                               }
                                        }
                                }
                                externalRoleDetailsList.add(externalRoleDetail);
                        }
-
                        for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
                                EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
                                finalRoleList.add(ecompRole);
@@ -1717,32 +1975,37 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                }
                        }
 
-                       // Check if roles exits in external Access system and make it
-                       // inactive
+                       // Check if roles exits in external Access system and make it inactive
                        final Map<String, EPRole> checkRolesInactive = new HashMap<>();
                        for (EPRole extrole : finalRoleList) {
                                checkRolesInactive.put(extrole.getName(), extrole);
                        }
                        for (EPRole role : applicationRolesList) {
-                               final Map<String, String> extRoleParams = new HashMap<>();
-                               List<EPRole> roleList = new ArrayList<>();
-                               extRoleParams.put("appRoleName", role.getName());
-                               if (!checkRolesInactive.containsKey(role.getName())) {
-                                       if (app.getId() == 1) {
-                                               roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
-                                       } else {
-                                               extRoleParams.put(APP_ID, app.getId().toString());
-                                               roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
+                               try {
+                                       final Map<String, String> extRoleParams = new HashMap<>();
+                                       List<EPRole> roleList = null;
+                                       extRoleParams.put("appRoleName", role.getName());
+                                       if (!checkRolesInactive.containsKey(role.getName())) {
+                                               if (app.getId() == 1) {
+                                                       roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null);
+                                               } else {
+                                                       extRoleParams.put(APP_ID, app.getId().toString());
+                                                       roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null);
+                                               }
+                                               EPRole updateRoleInactive = roleList.get(0);
+                                               updateRoleInactive.setActive(false);
+                                               dataAccessService.saveDomainObject(updateRoleInactive, null);
                                        }
-                                       EPRole updateRoleInactive = roleList.get(0);
-                                       updateRoleInactive.setActive(false);
-                                       dataAccessService.saveDomainObject(updateRoleInactive, null);
+                               } catch (Exception e) {
+                                       logger.error(EELFLoggerDelegate.errorLogger,
+                                                       "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
                                }
                        }
 
+                       // It checks properties in the external auth system app role description and updates role in local
                        for (EPRole roleItem : finalRoleList) {
                                final Map<String, String> roleParams = new HashMap<>();
-                               List<EPRole> currentList = new ArrayList<>();
+                               List<EPRole> currentList = null;
                                roleParams.put("appRoleName", roleItem.getName());
                                if (app.getId() == 1) {
                                        currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null);
@@ -1752,65 +2015,71 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                                }
 
                                if (!currentList.isEmpty()) {
-                                       Boolean aafRoleActive;
-                                       Boolean localRoleActive;
-                                       boolean result;
-                                       aafRoleActive = Boolean.valueOf(roleItem.getActive());
-                                       localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
-                                       result = aafRoleActive.equals(localRoleActive);
-                                       EPRole updateRole = currentList.get(0);
-
-                                       if (!result) {
-                                               updateRole.setActive(roleItem.getActive());
-                                               dataAccessService.saveDomainObject(updateRole, null);
-                                       }
-                                       if (roleItem.getPriority() != null
-                                                       && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
-                                               updateRole.setPriority(roleItem.getPriority());
-                                               dataAccessService.saveDomainObject(updateRole, null);
+                                       try {
+                                               Boolean aafRoleActive;
+                                               Boolean localRoleActive;
+                                               boolean result;
+                                               aafRoleActive = Boolean.valueOf(roleItem.getActive());
+                                               localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
+                                               result = aafRoleActive.equals(localRoleActive);
+                                               EPRole updateRole = currentList.get(0);
+
+                                               if (!result) {
+                                                       updateRole.setActive(roleItem.getActive());
+                                                       dataAccessService.saveDomainObject(updateRole, null);
+                                               }
+                                               if (roleItem.getPriority() != null
+                                                               && !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
+                                                       updateRole.setPriority(roleItem.getPriority());
+                                                       dataAccessService.saveDomainObject(updateRole, null);
+                                               }
+                                       } catch (Exception e) {
+                                               logger.error(EELFLoggerDelegate.errorLogger,
+                                                               "syncApplicationRolesWithEcompDB: Failed to update role ", e);
                                        }
                                }
                        }
 
                        EPRole roleToBeAddedInEcompDB = new EPRole();
                        for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
-                               roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
-                               if (app.getId() == 1) {
-                                       roleToBeAddedInEcompDB.setAppRoleId(null);
-                               }
-                               dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
-                               List<EPRole> getRoleCreatedInSync = null;
-                               if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
-                                       getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
-                                                       WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "'", null, null);
-                                       EPRole epUpdateRole = getRoleCreatedInSync.get(0);
-                                       epUpdateRole.setAppRoleId(epUpdateRole.getId());
-                                       dataAccessService.saveDomainObject(epUpdateRole, null);
-                               }
-                               List<EPRole> roleList = new ArrayList<>();
-                               final Map<String, String> params = new HashMap<>();
+                               try {
+                                       roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
+                                       if (app.getId() == 1) {
+                                               roleToBeAddedInEcompDB.setAppRoleId(null);
+                                       }
+                                       dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
+                                       List<EPRole> getRoleCreatedInSync = null;
+                                       if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                                               getRoleCreatedInSync = dataAccessService.getList(EPRole.class,
+                                                               WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "' and app_id = "+app.getId(), null, null);
+                                               EPRole epUpdateRole = getRoleCreatedInSync.get(0);
+                                               epUpdateRole.setAppRoleId(epUpdateRole.getId());
+                                               dataAccessService.saveDomainObject(epUpdateRole, null);
+                                       }
+                                       List<EPRole> roleList = new ArrayList<>();
+                                       final Map<String, String> params = new HashMap<>();
 
-                               params.put("appRoleName", roleToBeAddedInEcompDB.getName());
-                               if (app.getId() == 1) {
-                                       roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
-                               } else {
-                                       params.put(APP_ID, app.getId().toString());
-                                       roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
+                                       params.put("appRoleName", roleToBeAddedInEcompDB.getName());
+                                       if (app.getId() == 1) {
+                                               roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null);
+                                       } else {
+                                               params.put(APP_ID, app.getId().toString());
+                                               roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null);
+                                       }
+                                       EPRole role = roleList.get(0);
+                                       Role aaFrole = new Role();
+                                       aaFrole.setId(role.getId());
+                                       aaFrole.setActive(role.getActive());
+                                       aaFrole.setPriority(role.getPriority());
+                                       aaFrole.setName(role.getName());
+                                       updateRoleInExternalSystem(aaFrole, app);
+                               } catch (Exception e) {
+                                       logger.error(EELFLoggerDelegate.errorLogger,
+                                                       "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
                                }
-                               EPRole role = roleList.get(0);
-                               Role aaFrole = new Role();
-                               aaFrole.setId(role.getId());
-                               aaFrole.setActive(role.getActive());
-                               aaFrole.setPriority(role.getPriority());
-                               aaFrole.setName(role.getName());
-                               updateRoleInExternalSystem(aaFrole, app);
-                       }
-                       dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null);
-                       for (EPAppRoleFunction rolefun : applicationRoleFunctionList) {
-                               dataAccessService.saveDomainObject(rolefun, null);
                        }
                        logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
-               } catch(HttpClientErrorException e){
+               } catch (HttpClientErrorException e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e);
                        EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
                } catch (Exception e) {
@@ -1966,4 +2235,67 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
                }
                return appMenuFunctionsList;
        }
+
+       @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();
+
+                       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;
+       }
 }