Merge "Fix sql injection vulnerability"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / UserRolesCommonServiceImpl.java
index c65b4af..1d9ed57 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START==========================================
  * ONAP Portal
  * ===================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
  * ===================================================================
  *
  * Unless otherwise specified, all software contained herein is licensed
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * 
  */
 
 package org.onap.portalapp.portal.service;
@@ -63,9 +63,9 @@ import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.json.JSONArray;
 import org.json.JSONObject;
-import org.onap.portalapp.portal.service.SearchService;
 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
+import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
 import org.onap.portalapp.portal.domain.EPApp;
 import org.onap.portalapp.portal.domain.EPRole;
 import org.onap.portalapp.portal.domain.EPUser;
@@ -75,6 +75,7 @@ import org.onap.portalapp.portal.domain.EPUserAppRoles;
 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
+import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
@@ -90,6 +91,7 @@ import org.onap.portalapp.portal.transport.FieldsValidator;
 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
 import org.onap.portalapp.portal.transport.RemoteRole;
+import org.onap.portalapp.portal.transport.RemoteRoleV1;
 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
 import org.onap.portalapp.portal.transport.RoleInAppForUser;
 import org.onap.portalapp.portal.transport.RolesInAppForUser;
@@ -97,7 +99,10 @@ import org.onap.portalapp.portal.transport.UserApplicationRoles;
 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 import org.onap.portalapp.portal.utils.PortalConstants;
+import org.onap.portalapp.util.EPUserUtils;
+import org.onap.portalapp.util.SystemType;
 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.service.DataAccessService;
@@ -109,6 +114,7 @@ import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.HttpClientErrorException;
 import org.springframework.web.client.RestTemplate;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -121,6 +127,8 @@ public class UserRolesCommonServiceImpl  {
        private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
 
        private static final Object syncRests = new Object();
+
+       private static final String APP_ID = "appId";
                
        @Autowired
        private DataAccessService dataAccessService;                            
@@ -136,10 +144,16 @@ public class UserRolesCommonServiceImpl  {
        private EPRoleService epRoleService;
        @Autowired
        private RoleService roleService;        
-       
+       @Autowired
+       private AdminRolesService adminRolesService;
+       @Autowired
+       private EPAppService appService;
        @Autowired
        private ExternalAccessRolesService externalAccessRolesService;
        
+       @Autowired
+       private AppsCacheService appsCacheService;
+       
        RestTemplate template = new RestTemplate();
        
        /**
@@ -163,7 +177,7 @@ public class UserRolesCommonServiceImpl  {
         * 
         * @param userId
         */
-       protected void createLocalUserIfNecessary(String userId) {
+       protected void createLocalUserIfNecessary(String userId,boolean isSystemUser) {
                if (StringUtils.isEmpty(userId)) {
                        logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
                        return;
@@ -175,9 +189,20 @@ public class UserRolesCommonServiceImpl  {
                        transaction = localSession.beginTransaction();
                        @SuppressWarnings("unchecked")
                        List<EPUser> userList = localSession
-                                       .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
+                                       .createQuery("from :name where orgUserId=:userId")
+                                       .setParameter("name",EPUser.class.getName())
+                                       .setParameter("userId",userId)
+                                       .list();
                        if (userList.size() == 0) {
-                               EPUser client = searchService.searchUserByUserId(userId);
+                               EPUser client = null;
+                               if (!isSystemUser) {
+                                       client = searchService.searchUserByUserId(userId);
+                               } else {
+                                       client = new EPUser();
+                                       client.setOrgUserId(userId);
+                                       client.setSystemUser(true);
+                                       client.setFirstName(userId.substring(0,userId.indexOf("@")));
+                               }
                                if (client == null) {
                                        String msg = "createLocalUserIfNecessary: cannot create user " + userId
                                                        + ", because not found in phonebook";
@@ -246,7 +271,6 @@ public class UserRolesCommonServiceImpl  {
         */
        protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
                        EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
-               boolean result = false;
                Session localSession = null;
                Transaction transaction = null;
                String roleActive = null;
@@ -346,7 +370,7 @@ public class UserRolesCommonServiceImpl  {
                                                /*
                                                 * for local app -- hack - always make sure fn_role
                                                 * table's app_id is null and not 1 for primary app in
-                                                * this case being ecomp portal app; reason: hibernate
+                                                * this case being onap portal app; reason: hibernate
                                                 * is rightly setting this to 1 while persisting to
                                                 * fn_role as per the mapping but SDK role management
                                                 * code expects the app_id to be null as there is no
@@ -361,23 +385,17 @@ public class UserRolesCommonServiceImpl  {
                                }
                        }
                        transaction.commit();
-                       result = true;
                } catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
                        EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
                        EcompPortalUtils.rollbackTransaction(transaction,
                                        "Exception occurred in syncUserRoles, Details: " + e.toString());
                        if("DELETE".equals(reqType)){
-                               throw new Exception(e.getMessage());
+                               throw new SyncUserRolesException(e.getMessage());
                        }
                } finally {
-                       if (localSession != null) {
-                               localSession.close();           
-                       }                               
-                       if (!result && !"DELETE".equals(reqType)) {
-                               throw new Exception(
-                                               "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
-                       }
+                       if(localSession != null)
+                               localSession.close();
                }
        }
        
@@ -430,18 +448,25 @@ public class UserRolesCommonServiceImpl  {
                        for (EPRole ecompRole : userAppRoles) {
                                userAppRolesMap.add(ecompRole.getId());
                        }
+                       logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
+
                } else {
                        logger.error(EELFLoggerDelegate.errorLogger,
                                        "constructRolesInAppForUserGet has received userAppRoles list empty.");
                }
 
                if (appRoles != null) {
+
                        for (Role ecompRole : appRoles) {
+                               logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
+
                                if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
                                        continue;
                                RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
                                roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
                                rolesInAppForUser.add(roleForUser);
+                               logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
+
                        }
                } else {
                        logger.error(EELFLoggerDelegate.errorLogger,
@@ -470,9 +495,13 @@ public class UserRolesCommonServiceImpl  {
                        transaction = localSession.beginTransaction();
                        // Attention! All roles from remote application supposed to be
                        // active!
+
                        @SuppressWarnings("unchecked")
-                       List<EPRole> currentAppRoles = localSession
-                                       .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
+                       List<EPRole> currentAppRoles = localSession.createQuery("from :name where appId = :appId")
+                                       .setParameter("name",EPRole.class.getName())
+                                       .setParameter("appId",appId)
+                                       .list();
+
                        List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
                        for (int i = 0; i < currentAppRoles.size(); i++) {
                                EPRole oldAppRole = currentAppRoles.get(i);
@@ -484,6 +513,7 @@ public class UserRolesCommonServiceImpl  {
                                                        oldAppRole.setName(role.getName());
                                                        localSession.update(oldAppRole);
                                                }
+                                               oldAppRole.setActive(true);
                                                newRolesMap.remove(oldAppRole.getAppRoleId());
                                        } else {
                                                obsoleteRoles.add(oldAppRole);
@@ -509,7 +539,10 @@ public class UserRolesCommonServiceImpl  {
                                        // Delete from fn_user_role
                                        @SuppressWarnings("unchecked")
                                        List<EPUserApp> userRoles = localSession.createQuery(
-                                                       "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
+                                                       "from :name where app.id=:appId and role_id=:roleId")
+                                                       .setParameter("name",EPUserApp.class.getName())
+                                                       .setParameter("appId",appId)
+                                                       .setParameter("roleId",roleId)
                                                        .list();
 
                                        logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
@@ -524,7 +557,9 @@ public class UserRolesCommonServiceImpl  {
                                        // Delete from fn_menu_functional_roles
                                        @SuppressWarnings("unchecked")
                                        List<FunctionalMenuRole> funcMenuRoles = localSession
-                                                       .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
+                                                       .createQuery("from :name where roleId=:roleId")
+                                                       .setParameter("name",FunctionalMenuRole.class.getName())
+                                                       .setParameter("roleId",roleId)
                                                        .list();
                                        int numMenuRoles = funcMenuRoles.size();
                                        logger.debug(EELFLoggerDelegate.debugLogger,
@@ -536,7 +571,9 @@ public class UserRolesCommonServiceImpl  {
                                                // so must null out the url too, to be consistent
                                                @SuppressWarnings("unchecked")
                                                List<FunctionalMenuRole> funcMenuRoles2 = localSession
-                                                               .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
+                                                               .createQuery("from :name where menuId=:menuId")
+                                                               .setParameter("name",FunctionalMenuRole.class.getName())
+                                                               .setParameter("menuId",menuId)
                                                                .list();
                                                int numMenuRoles2 = funcMenuRoles2.size();
                                                logger.debug(EELFLoggerDelegate.debugLogger,
@@ -550,8 +587,9 @@ public class UserRolesCommonServiceImpl  {
                                                                        "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
                                                        @SuppressWarnings("unchecked")
                                                        List<FunctionalMenuItem> funcMenuItems = localSession
-                                                                       .createQuery(
-                                                                                       "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
+                                                                       .createQuery("from :name where menuId=:menuId")
+                                                                       .setParameter("name",FunctionalMenuItem.class.getName())
+                                                                       .setParameter("menuId",menuId)
                                                                        .list();
                                                        if (funcMenuItems.size() > 0) {
                                                                logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
@@ -611,6 +649,7 @@ public class UserRolesCommonServiceImpl  {
                result = new RolesInAppForUser();
                result.appId = appId;
                result.orgUserId = userId;
+
                for (EcompRole role : userRolesInRemoteApp) {
                        RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
                        roleInAppForUser.roleId = role.getId();
@@ -648,11 +687,29 @@ public class UserRolesCommonServiceImpl  {
         * @throws HTTPException
         */
        protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
-                       ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
+                       ApplicationsRestClientService applicationsRestClientService, Long appId, String userId,boolean systemUser)
                        throws JsonProcessingException, HTTPException {
                Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
                Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
                String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
+        EPApp externalApp = null;
+        SystemType type = SystemType.APPLICATION;
+               externalApp = appsCacheService.getApp(appId);
+               String appBaseUri = null;
+               Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
+               if (externalApp != null) {
+                        appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
+               }
+               if(appBaseUri != null && appBaseUri.endsWith("/api")){
+                       for(EcompRole eprole :updatedUserRolesinRemote)
+                       {
+                               RemoteRoleV1 role = new RemoteRoleV1();
+                               role.setId(eprole.getId());
+                               role.setName(eprole.getName());
+                               updatedUserRolesinRemoteV1.add(role);
+                       }
+                       userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
+               }
                applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
                                String.format("/user/%s/roles", userId));
                // TODO: We should add code that verifies that the post operation did
@@ -707,13 +764,13 @@ public class UserRolesCommonServiceImpl  {
         *                      set to false if requests from Users page otherwise true
         * @return true on success, false otherwise
         */
-       protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
+       protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType,boolean isSystemUser) throws Exception {
                boolean result = false;
                String userId = rolesInAppForUser.orgUserId;
                Long appId = rolesInAppForUser.appId;
                synchronized (syncRests) {
                        if (rolesInAppForUser != null) {
-                               createLocalUserIfNecessary(userId);
+                               createLocalUserIfNecessary(userId, isSystemUser);
                        }
 
                        if (rolesInAppForUser != null) {
@@ -759,7 +816,7 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
+        * @see org.onap.portalapp.portal.service.UserRolesService#
         * importRolesFromRemoteApplication(java.lang.Long)
         */
        public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
@@ -768,7 +825,7 @@ public class UserRolesCommonServiceImpl  {
                for (EPRole externalAppRole : rolesList) {
 
                        // Try to find an existing extern role for the app in the local
-                       // ecomp DB. If so, then use its id to update the existing external
+                       // onap DB. If so, then use its id to update the existing external
                        // application role record.
                        Long externAppId = externalAppRole.getId();
                        EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
@@ -798,23 +855,119 @@ public class UserRolesCommonServiceImpl  {
         * @return 
         * @throws Exception
         */
-       private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
+       private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
+                       ObjectMapper mapper, SearchService searchService,
+                       ApplicationsRestClientService applicationsRestClientService) throws Exception {
                EPUser addRemoteUser = null;
                if (remoteUserShouldBeCreated(roleInAppForUserList)) {
-                       
-                       createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
-                       // If we succeed, we know that the new user was
-                       // persisted on remote app.
-                       addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
-                       if (addRemoteUser == null) {
-                               logger.error(EELFLoggerDelegate.errorLogger,
-                                               "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId());
-                               // return null;
-                       }
+                       createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
+                                       isAppUpgradeVersion(app));
                }
                return addRemoteUser;
        }
        
+       private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
+                       ObjectMapper mapper, SearchService searchService,
+                       ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
+               EPUser addRemoteUser = null;
+//             if (remoteUserShouldBeCreated(roleInAppForUserList)) {
+                       pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
+                                       isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
+//             }
+               return addRemoteUser;
+       }
+
+       @SuppressWarnings("unchecked")
+       protected void pushUserOnRemoteApp(String userId, EPApp app,
+                       ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
+                       ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
+
+               EPUser client  = null;
+                       client = searchService.searchUserByUserId(userId);
+
+                       mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+                       if (client == null) {
+                               String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
+                               logger.error(EELFLoggerDelegate.errorLogger, msg);
+                               // throw new Exception(msg);
+                               final Map<String, String> loginIdParams = new HashMap<>();
+                               loginIdParams.put("orgUserIdValue", userId);
+                               List<EPUser> userList = new ArrayList<>();
+                               userList = dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null);
+                               if (userList.size() > 0) {
+                                       logger.debug(EELFLoggerDelegate.debugLogger,
+                                                       userList.get(0).getOrgUserId() + " User was found in Portal");
+                                       client = userList.get(0);
+                                       SortedSet<EPUserApp> userApps = new TreeSet<>();
+                                       client.setEPUserApps(userApps);
+                                       client.setSystemUser(false);
+                               } else {
+                                       logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
+                                       throw new Exception(msg);
+                               }
+
+                       }
+               
+               client.setLoginId(userId);
+           client.setActive(true);
+           client.setOrgUserId(userId);
+       
+               
+               roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
+               SortedSet<Role> roles = new TreeSet<>();
+
+               List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
+               List<EPApp> appList = new ArrayList<>();
+               appList.add(app);
+               List<CentralV2Role> roleList = new ArrayList<>();
+               Map<String, Long> params = new HashMap<>();
+
+               List<EPRole> userRoles = new ArrayList<>();
+
+               for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
+                       EPRole role = new EPRole();
+                       role.setId(roleInappForUser.getRoleId());
+                       role.setName(roleInappForUser.getRoleName());
+                       userRoles.add(role);
+               }
+
+               if (appRoleIdUsed) {
+                       List<EPRole> userAppRoles = new ArrayList<>();
+                       for (EPRole role : userRoles) {
+                               EPRole appRole = getAppRoles.stream()
+                                               .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
+                                               .orElse(null);
+                               EPRole epRole = new EPRole();
+                               if (appRole != null) {
+                                       epRole.setId(appRole.getId());
+                                       epRole.setName(appRole.getName());
+                               }
+                               userAppRoles.add(epRole);
+                       }
+                       userRoles = new ArrayList<>();
+                       userRoles.addAll(userAppRoles);
+               }
+               roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
+
+               for (CentralV2Role epRole : roleList) {
+                       Role role = new Role();
+                       EPRole appRole = getAppRoles.stream()
+                                       .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
+                       if (appRole != null){
+                               role.setId(appRole.getAppRoleId());
+                       role.setName(epRole.getName());
+                       role.setRoleFunctions(epRole.getRoleFunctions());
+                       }
+                       roles.add(role);
+               }
+               client.setRoles(roles);
+               String userInString = null;
+               userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
+               logger.debug(EELFLoggerDelegate.debugLogger,
+                               "about to post a client to remote application, users json = " + userInString);
+               applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
+       }
+
        /**
         * It checks whether the remote user exists or not
         * if exits returns user object else null
@@ -851,20 +1004,21 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
-        * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain.
-        * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser)
+        * @see org.onap.portalapp.portal.service.UserRolesService#
+        * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
+        * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
         */
-       public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
+       public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
                boolean result = false;
                boolean epRequestValue = false;
                String userId = "";
-               if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
-                       userId = newAppRolesForUser.orgUserId.trim();
+               String reqMessage = "";
+               if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
+                       userId = newAppRolesForUser.getOrgUserId().trim();
                }
-               Long appId = newAppRolesForUser.appId;
-               List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
-               if (userId.length() > 0) {
+               Long appId = newAppRolesForUser.getAppId();
+               List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
+               if (userId.length() > 0 ) {
                        ObjectMapper mapper = new ObjectMapper();
                        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
@@ -872,20 +1026,34 @@ public class UserRolesCommonServiceImpl  {
                                EPApp app = appsService.getApp(appId);
                                applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
 
-                               // if centralized app
+                               boolean systemUser = newAppRolesForUser.isSystemUser();
+                               if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
+
+                                       Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
+                                                       applicationsRestClientService, appId, userId);
+                                       RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
+                                                       userRolesInLocalApp);
+                                       List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
+                                       if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                                               // Apply changes in external Access system
+                                               updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
+                                                               epRequestValue, systemUser);
+                                       }
+                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",
+                                                       systemUser);
+
+                               }else if (!app.getCentralAuth() && systemUser)
+                               {
+                                       throw new Exception("For non-centralized application we cannot add systemUser");
+                               }
+                               else{   // if centralized app
                                if (app.getCentralAuth()) {
-                                       // We should add If user does not exist in remote application
                                        if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
-                                               EPUser remoteAppUser = null;
-                                               remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
-
-                                               if (remoteAppUser == null) {
-                                                       addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
-                                                                       applicationsRestClientService);
-                                               }
+                                               pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
+                                                                       applicationsRestClientService,false);
                                        }
                                        
-                                       Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
+                                       Set<EcompRole>  userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
                                                        applicationsRestClientService, appId, userId);
                                        RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
                                                        userRolesInLocalApp);
@@ -893,9 +1061,9 @@ public class UserRolesCommonServiceImpl  {
                                        if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
                                                // Apply changes in external Access system
                                                updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
-                                                               epRequestValue);
+                                                               epRequestValue,false);
                                        }
-                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
+                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal", systemUser);
                                } 
                                // In case if portal is not centralized then follow existing approach
                                else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
@@ -903,7 +1071,7 @@ public class UserRolesCommonServiceImpl  {
                                                        applicationsRestClientService, appId, userId);  
                                        RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
                                                        userRolesInLocalApp);
-                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
+                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal",false);
                                } else{// remote app
                                        EPUser remoteAppUser = null;
                                        if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
@@ -913,34 +1081,44 @@ public class UserRolesCommonServiceImpl  {
                                                if (remoteAppUser == null) {
                                                        remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
                                                }
-                                               if (remoteAppUser != null) {
-                                                       Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
-                                                                       applicationsRestClientService, appId, userId);
+                                               Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
+                                                                       applicationsRestClientService, appId, userId,systemUser);
                                                        RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
                                                                        userRolesInRemoteApp);
-                                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
+                                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null,false);
 
                                                        // If no roles remain, request app to set user inactive.
                                                        if (userRolesInRemoteApp.size() == 0) {
                                                                logger.debug(EELFLoggerDelegate.debugLogger,
                                                                                "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
                                                                                userId);
-                                                               remoteAppUser.setActive(false);
+                                                               //remoteAppUser.setActive(false);
                                                                postUserToRemoteApp(userId, user, app, applicationsRestClientService);
-                                                       }
                                                }
                                        }
                                }
+                       }
                        } catch (Exception e) {
+                               /*String message = String.format(
+                                               "Failed to create user or update user roles for User %s, AppId %s",
+                                               userId, Long.toString(appId));
+                               logger.error(EELFLoggerDelegate.errorLogger, message, e);
+                               result = false;*/
+
                                String message = String.format(
                                                "Failed to create user or update user roles for User %s, AppId %s",
                                                userId, Long.toString(appId));
                                logger.error(EELFLoggerDelegate.errorLogger, message, e);
                                result = false;
+                               reqMessage = e.getMessage();
+                                                        
+                       
                        }
 
                }
-               return result;
+               //return result;
+               return new ExternalRequestFieldsValidator(result, reqMessage);
+
        }
        /**
         * It adds user roles in External system and also make data consistent in both local and in External System 
@@ -950,7 +1128,7 @@ public class UserRolesCommonServiceImpl  {
         * @param roleInAppUser Contains list of active roles 
         */
        @SuppressWarnings("unchecked")
-       private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
+       private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest,boolean isSystemUser) throws Exception
        {
                try {
                        // check if user exists
@@ -958,29 +1136,20 @@ public class UserRolesCommonServiceImpl  {
                        userParams.put("orgUserIdValue", orgUserId);
                        List<EPUser> userInfo = checkIfUserExists(userParams);
                        if (userInfo.isEmpty()) {
-                               createLocalUserIfNecessary(orgUserId);
+                               createLocalUserIfNecessary(orgUserId, isSystemUser);
                        }
                        String name = "";
                        if (EPCommonSystemProperties
-                                       .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                                       .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) && !isSystemUser) {
                                name = orgUserId
                                                + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+                       } else {
+                               name = orgUserId;
                        }
                        ObjectMapper mapper = new ObjectMapper();
                        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
                        HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
-                       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, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}",
-                                               getResponse.getBody());
-
-                       }else{
-                               logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
-                               EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
-                       }
+                       ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
                        List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
                        String res = getResponse.getBody();
                        JSONObject jsonObj = null;
@@ -995,10 +1164,8 @@ public class UserRolesCommonServiceImpl  {
                                        if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
                                                        && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
                                                        && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
-                                               ObjectMapper descMapper = new ObjectMapper();
-                                               if (extRoles.getJSONObject(i).has("description") && EcompPortalUtils.isJSONValid(extRoles.getJSONObject(i).getString("description"))) {
-                                                       ExternalRoleDescription desc = descMapper.readValue(
-                                                                       extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
+                                               if (extRoles.getJSONObject(i).has("description")) {
+                                                       ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
                                                        userRoleDetail = new ExternalAccessUserRoleDetail(
                                                                        extRoles.getJSONObject(i).getString("name"), desc);
                                                        userRoleDetailList.add(userRoleDetail);
@@ -1069,7 +1236,7 @@ public class UserRolesCommonServiceImpl  {
                        for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
                                if (!(currentUserRolesInExternalSystem
                                                .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
-                                       ExternalAccessUser extUser = new ExternalAccessUser(name,
+                                       ExternalAccessUser extUser = new ExternalAccessUser(name,
                                                        app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
                                        String formattedUserRole = mapper.writeValueAsString(extUser);
                                        HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
@@ -1089,7 +1256,23 @@ public class UserRolesCommonServiceImpl  {
                                        }
                                }
                        }
-               } catch (Exception e) {
+               } catch (HttpClientErrorException e) {
+                       logger.error(EELFLoggerDelegate.errorLogger,
+                                       "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
+                                       app.getId(), e);
+                       if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
+                               logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser", orgUserId);
+                               throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Please enter the valid systemUser");
+                       }
+                       if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
+                               logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
+                               throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
+                       }
+                       EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
+                       throw e;
+               }
+
+               catch (Exception e) {
                        logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
                        EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
                        throw e;
@@ -1099,7 +1282,7 @@ public class UserRolesCommonServiceImpl  {
 
        private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
                        List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {             
-               Map<String, EPRole> epRoleList  = externalAccessRolesService.getCurrentRolesInDB(app);  
+               Map<String, EPRole> epRoleList  = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);     
                //Add Account Admin role for partner app to prevent conflict
                if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
                EPRole role =  new EPRole();
@@ -1294,7 +1477,7 @@ public class UserRolesCommonServiceImpl  {
                final Map<String, Long> params = new HashMap<>();
                final Map<String, String> userParams = new HashMap<>();
                List<EPUser> userInfo = null;
-               EPUser userId = null;
+               EPUser user = null;
                List<EPUserAppRolesRequest> epRequestId = null;
                String orgUserId = "";
                String updateStatus = "";
@@ -1319,9 +1502,9 @@ public class UserRolesCommonServiceImpl  {
                                }
                                if (userInfo.size() != 0 || !userInfo.isEmpty()) {
                                        validateExternalRequestFields(userInfo, app);
-                                       userId = userInfo.get(0);
+                                       user = userInfo.get(0);
                                        params.put("appId", app.getId());
-                                       params.put("userId", userId.getId());
+                                       params.put("userId", user.getId());
                                        epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
                                                        .executeNamedQuery("userAppRolesRequestList", params, null);
                                        epRequestIdSize = epRequestId.size();
@@ -1341,7 +1524,7 @@ public class UserRolesCommonServiceImpl  {
                                List<EcompUserAppRoles> userRoleList = null;
                                if(!userInfo.isEmpty()){
                                final Map<String, Long> appParams = new HashMap<>();
-                               appParams.put("userId", userId.getId());
+                               appParams.put("userId", user.getId());
                                appParams.put("appId", app.getId());
                                userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
                                }
@@ -1358,17 +1541,20 @@ public class UserRolesCommonServiceImpl  {
                                if (app.getCentralAuth()) {
                                        // We should add If user does not exist in remote application
                                        try {
-                                               // If adding just account admin role dont make remote application user call
-                                               if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
-                                                               && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
-                                                       EPUser remoteAppUser = null;
-                                                       remoteAppUser = checkIfRemoteUserExits(orgUserId, app,
-                                                                       applicationsRestClientService);
-                                                       if (remoteAppUser == null) {
-                                                               addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
-                                                                               applicationsRestClientService);
-                                                               reqMessage = "Saved Successfully";
-                                                       }
+                                               // If adding just account admin role dont make remote application user call or
+                                               // if request has only single non admin role then make remote call
+                                               if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
+                                                               && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
+                                                                               || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
+                                                       // check if admin role exist then delete
+                                                       List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
+                                                                         .collect(Collectors.toList());
+                                                       remoteUserRoles.removeIf(role -> {
+                                                               return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
+                                                       });
+                                                       String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
+                                                       pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
+                                                                       applicationsRestClientService,true);
                                                }
                                        } catch (Exception e) {
                                                reqMessage = e.getMessage();
@@ -1382,11 +1568,11 @@ public class UserRolesCommonServiceImpl  {
                                        List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
                                        if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
                                        // Apply changes in external Access system
-                                       updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
+                                       updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest,false);
                                        }
                                        logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
                                                        newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
-                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
+                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
                                } 
                                // If local application is not centralized 
                                else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
@@ -1394,37 +1580,38 @@ public class UserRolesCommonServiceImpl  {
                                                        applicationsRestClientService, app.getId(), orgUserId); 
                                        RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
                                                        userRolesInLocalApp);
-                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
+                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,false);
                                } else {// remote app
                                        // If adding just account admin role don't do remote application user call
-                                       if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
-                                       EPUser remoteAppUser = null;
+                                       if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
+                                               EPUser remoteAppUser = null;
                                                remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
-                                       if (remoteAppUser == null) {
-                                               remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService);
-                                               reqMessage = "Saved Successfully";
-                                       }
-                                               if (remoteAppUser != null) {
-                                                       Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
-                                                                       mapper, applicationsRestClientService, app.getId(), orgUserId);
-
-                                                       RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
-                                                                       app.getId(), userRolesInRemoteApp);
-                                                       logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
-                                                                       logMessage, newAppRolesForUser.getApplicationName(),
-                                                                       newAppRolesForUser.getLoginId());
-                                                       result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
-                                                                       reqType);
-                                                       // If no roles remain, request app to set user inactive.
-                                                       /*if (userRolesInRemoteApp.size() == 0) {
-                                                               logger.debug(EELFLoggerDelegate.debugLogger,
-                                                                               "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
-                                                                               orgUserId);
-                                                               //TODO Need  to fix the logged in user is not set to inactive
-                                                               remoteAppUser.setActive(false);
-                                                               postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
-                                                       }*/
+                                               if (remoteAppUser == null) {
+                                                       addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
+                                                                       applicationsRestClientService);
+                                                       reqMessage = "Saved Successfully";
                                                }
+
+                                               Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
+                                                               applicationsRestClientService, app.getId(), orgUserId,false);
+
+                                               RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
+                                                               userRolesInRemoteApp);
+                                               logger.info(EELFLoggerDelegate.debugLogger,
+                                                               "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
+                                                               newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
+                                               result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
+                                                               reqType,false);
+                                               // If no roles remain, request app to set user inactive.
+                                               /*
+                                                * if (userRolesInRemoteApp.size() == 0) {
+                                                * logger.debug(EELFLoggerDelegate.debugLogger,
+                                                * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
+                                                * , app, orgUserId); //TODO Need to fix the logged in user is not set to
+                                                * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
+                                                * app, applicationsRestClientService); }
+                                                */
+
                                        } else {
                                                // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote 
                                                if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
@@ -1437,14 +1624,14 @@ public class UserRolesCommonServiceImpl  {
                                                logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
                                                                logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
                                                result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
-                                                               reqType);
+                                                               reqType,false);
                                        }
                                        if(!result){
                                                reqMessage = "Failed to save the user app role(s)";
                                        }
                                        if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
                                                updateStatus = "C";
-                                               applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
+                                               applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
                                        }
                                }
                        } catch (Exception e) {
@@ -1455,7 +1642,7 @@ public class UserRolesCommonServiceImpl  {
                                reqMessage = e.getMessage();
                                 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
                                 updateStatus = "F";
-                                applyChangesToAppRolesRequest(app.getId(), userId.getId(),
+                                applyChangesToAppRolesRequest(app.getId(), user.getId(),
                                 updateStatus, epRequestId.get(0));
                                 }
                        }
@@ -1572,159 +1759,294 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
+        * @see org.onap.portalapp.portal.service.UserRolesService#
         * getAppRolesForUser(java.lang.Long, java.lang.String)
         */
        @SuppressWarnings("unchecked")
-       public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
-
-               List<RoleInAppForUser> rolesInAppForUser = null;
-               EPApp app = appsService.getApp(appId);
-               try {
-                       // for ecomp portal app, no need to make a remote call
-                       List<Role> roleList = new ArrayList<>();
-                       if (appId == PortalConstants.PORTAL_APP_ID) {           
-                               if(app.getCentralAuth()){
-                                       List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
-                                       for(CentralV2Role cenRole : cenRoleList){
-                                               Role role = new Role();
-                                               role.setActive(cenRole.isActive());
-                                               role.setId(cenRole.getId());
-                                               role.setName(cenRole.getName());
-                                               role.setPriority(cenRole.getPriority());
-                                               roleList.add(role);
-                                       }
-                               }else{
-                                       roleList = roleService.getAvailableRoles(userId);
+       public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
+       List<RoleInAppForUser> rolesInAppForUser = null;
+       EPApp app = appsService.getApp(appId);
+       logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
+       try {
+               // for onap portal app, no need to make a remote call
+               List<Role> roleList = new ArrayList<>();
+               if (appId == PortalConstants.PORTAL_APP_ID) {           
+                       if(app.getCentralAuth()){
+                               List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
+                               for(CentralV2Role cenRole : cenRoleList){
+                                       Role role = new Role();
+                                       role.setActive(cenRole.getActive());
+                                       role.setId(cenRole.getId());
+                                       role.setName(cenRole.getName());
+                                       role.setPriority(cenRole.getPriority());
+                                       roleList.add(role);
                                }
-                               List<Role> activeRoleList = new ArrayList<Role>();
-                               for(Role role: roleList) {
-                                       if(role.getActive()) {
-                                               if(role.getId() != 1){ // prevent portal admin from being added
-                                                       activeRoleList.add(role);
-                                               } else if(extRequestValue){
-                                                       activeRoleList.add(role);
-                                               }
+                       }else{
+                               roleList = roleService.getAvailableRoles(userId);
+                       }
+                       List<Role> activeRoleList = new ArrayList<Role>();
+                       for(Role role: roleList) {
+                               if(role.getActive()) {
+                                       if(role.getId() != 1){ // prevent portal admin from being added
+                                               activeRoleList.add(role);
+                                       } else if(extRequestValue){
+                                               activeRoleList.add(role);
                                        }
-                                               
                                }
-                               EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
-                               // If localUser does not exists return roles
-                               Set<EPRole> roleSet = null;
-                               EPRole[] roleSetList = null;
-                               if(localUser != null){
-                                       roleSet = localUser.getAppEPRoles(app);
-                                       roleSetList = roleSet.toArray(new EPRole[0]);
-                               }
-                               rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
-                               return rolesInAppForUser;
+                                       
                        }
-                       
-                       EcompRole[] appRoles = null;
-                       List<EcompRole> roles = new ArrayList<>();
-                       if(app.getCentralAuth()){
-                               List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);;
-                               for(EPRole role : applicationRoles){
+                       EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
+                       // If localUser does not exists return roles
+                       Set<EPRole> roleSet = null;
+                       EPRole[] roleSetList = null;
+                       if(localUser != null){
+                               roleSet = localUser.getAppEPRoles(app);
+                               roleSetList = roleSet.toArray(new EPRole[0]);
+                       }
+                       rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
+                       return rolesInAppForUser;
+               }
+               
+               EcompRole[] appRoles = null;
+               List<EcompRole> roles = new ArrayList<>();
+                       if (app.getCentralAuth()) {
+                               final Map<String, Long> appParams = new HashMap<>();
+                               appParams.put("appId", app.getId());
+                               List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
+                                               appParams, null);
+
+                               EPApp application = appService.getApp(appId);
+                               boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
+                                               application);
+
+                               List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
+                               for (EPRole role : applicationRoles) {
+                                       Map<String, Long> params = new HashMap<>();
+                                       params.put("roleId", role.getId());
+                                       params.put(APP_ID, app.getId());
+                                       List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
+                                                       .executeNamedQuery("getAppRoleFunctionList", params, null);
+
+                                       // SortedSet<CentralV2RoleFunction> roleFunctionSet =
+                                       // new TreeSet<>();
+                                       SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
+                                       for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
+
+                                               String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+                                               functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+                                               String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
+                                               String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
+                                               String name = roleFunc.getName();
+
+                                               RoleFunction function = new RoleFunction();
+                                               function.setAction(action);
+                                               function.setType(type);
+                                               function.setCode(functionCode);
+                                               function.setName(name);
+                                               roleFunctionSet.add(function);
+                                               role.setRoleFunctions(roleFunctionSet);
+
+                                       }
+                                       rolesetwithfunctioncds.add(role);
+
+
+                               }
+
+                               for (EPRole role1 : rolesetwithfunctioncds) {
                                        EcompRole ecompRole = new EcompRole();
-                                       ecompRole.setId(role.getId());
-                                       ecompRole.setName(role.getName());
+                                       ecompRole.setId(role1.getId());
+                                       ecompRole.setName(role1.getName());
+                                       ecompRole.setRoleFunctions(role1.getRoleFunctions());
                                        roles.add(ecompRole);
+
+                               }
+                                       if (checkIfUserisApplicationAccAdmin) {
+                                       appRoles = roles.toArray(new EcompRole[roles.size()]);
+                                       logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
+                               } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
+                                       List<EcompRole> roleAdminAppRoles = new ArrayList<>();
+                                       List<String> roleAdminAppRolesNames = new ArrayList<>();
+                                       final Map<String, Long> userParams = new HashMap<>();
+                                       userParams.put("userId", user.getId()); 
+                                       List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
+
+                                       List<EcompRole> userapproverRolesList = new ArrayList<>();
+                                       for (String str : getUserApproverRoles) {
+                                               EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
+                                               if (epRole != null)
+                                                       userapproverRolesList.add(epRole);
+                                       }
+//                                     roles.removeAll(userapproverRolesList);
+                                       for (EcompRole role : userapproverRolesList) {
+
+                                               List<RoleFunction> roleFunList = new ArrayList<>();
+                                               roleFunList.addAll(role.getRoleFunctions());
+                                               boolean checkIfFunctionsExits = roleFunList.stream()
+                                                               .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
+                                               if (checkIfFunctionsExits) {
+                                                       roleAdminAppRoles.add(role);
+                                                       List<RoleFunction> filteredList = roleFunList.stream()
+                                                                       .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
+                                                       roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
+                                                                       .collect(Collectors.toList()));
+//                                                     roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
+//                                                                     .collect(Collectors.toList());
+                                               }
+                                       }
+                                               for (String name : roleAdminAppRolesNames) {
+                                                       EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
+                                                                       .orElse(null);
+                                                       if (ecompRole != null)
+                                                               roleAdminAppRoles.add(ecompRole);
+                                               
+                                       }
+                                       appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
+
                                }
-                               appRoles = roles.toArray(new EcompRole[roles.size()]);
                        } else{
-                               appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+                       appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+               }
+               // Test this error case, for generating an internal ONAP Portal
+               // error
+               // EcompRole[] appRoles = null;
+               // If there is an exception in the rest client api, then null will
+               // be returned.
+               if (appRoles != null) {
+                       if(!app.getCentralAuth()) {
+                       syncAppRoles(sessionFactory, appId, appRoles);
                        }
-                       // Test this error case, for generating an internal Ecomp Portal
-                       // error
-                       // EcompRole[] appRoles = null;
-                       // If there is an exception in the rest client api, then null will
-                       // be returned.
-                       if (appRoles != null) {
-                               if(!app.getCentralAuth()) {
-                               syncAppRoles(sessionFactory, appId, appRoles);
-                               }
-                               EcompRole[] userAppRoles = null;
+                       EcompRole[] userAppRoles = null;
+                       try {
                                try {
-                                       try {
-                                               if(app.getCentralAuth()){
-                                                       final Map<String, String> params = new HashMap<>();
-                                                       final Map<String, Long> userParams = new HashMap<>();
-                                                       params.put("orgUserIdValue", userId);
-                                                       List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
-                                                       userParams.put("appId", app.getId());
-                                                       userParams.put("userId", user.get(0).getId());  
-                                                       List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
-                                                               List<EcompRole> setUserRoles = new ArrayList<>();
-                                                               for(EPUserAppCurrentRoles role : userAppsRolesList){
-                                                                       EcompRole ecompRole = new EcompRole();
-                                                                       ecompRole.setId(role.getRoleId());
-                                                                       ecompRole.setName(role.getRoleName());
-                                                                       setUserRoles.add(ecompRole);
+                                       
+                                       if(app.getCentralAuth()){
+                                               final Map<String, String> params = new HashMap<>();
+                                               final Map<String, Long> userParams = new HashMap<>();
+                                               params.put("orgUserIdValue", userId);
+                                               List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
+                                               userParams.put("appId", app.getId());
+                                               userParams.put("userId", actualUser.get(0).getId());    
+                                               List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
+                                                       
+                                               List<EcompRole> setUserRoles = new ArrayList<>();
+                                                       for(EPUserAppCurrentRoles role : userAppsRolesList){
+                                                               logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
+                                                               EcompRole ecompRole = new EcompRole();
+                                                               ecompRole.setId(role.getRoleId());
+                                                               ecompRole.setName(role.getRoleName());
+                                                               setUserRoles.add(ecompRole);
+                                                       }
+                                               
+                                                       boolean checkIfUserisAccAdmin = setUserRoles.stream()
+                                                                       .anyMatch(ecompRole -> ecompRole.getId() == 999L);
+                                                       
+                                               if (!checkIfUserisAccAdmin) {
+                                                       List<EcompRole> userApplicationRolesList = setUserRoles;
+                                                       List<EcompRole> appRolesList = Arrays.asList(appRoles);
+                                                        Set<EcompRole> finalUserAppRolesList = new HashSet<>();
+
+                                                       List<String> roleNames = new ArrayList<>();
+                                                               for (EcompRole role : userApplicationRolesList) {
+                                                                       EcompRole epRole = appRolesList.stream()
+                                                                                       .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
+                                                                       List<RoleFunction> roleFunList = new ArrayList<>();
+                                                                       if(epRole.getRoleFunctions().size()>0)
+                                                                       roleFunList.addAll(epRole.getRoleFunctions());
+                                                                       boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
+                                                                                       roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
+                                                                       if (checkIfFunctionsExits) {
+                                                                               finalUserAppRolesList.add(role);
+                                                                               List<RoleFunction> filteredList = roleFunList.stream()
+                                                                                               .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
+                                                                                               .collect(Collectors.toList());
+                                                                               roleNames = filteredList.stream().map(RoleFunction::getCode)
+                                                                                               .collect(Collectors.toList());
+                                                                       }
+
+                                                                       for (String name : roleNames) {
+                                                                               EcompRole ecompRole = appRolesList.stream()
+                                                                                               .filter(x -> name.equals(x.getName())).findAny().orElse(null);
+                                                                               if (ecompRole != null)
+                                                                                       finalUserAppRolesList.add(ecompRole);
+                                                                       }
                                                                }
-                                                               userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
-                                                               rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
-                                                               return rolesInAppForUser;
-                                               }else{
-                                                       userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
-                                                                       String.format("/user/%s/roles", userId));
-                                               }
-                                       } catch (HTTPException e) {
-                                               // Some apps are returning 400 if user is not found.
-                                               if (e.getResponseCode() == 400) {
-                                                       logger.debug(EELFLoggerDelegate.debugLogger,
-                                                                       "getAppRolesForUser caught exception with response code 400; continuing", e);
-                                               } else {
-                                                       // Other response code, let it come thru.
-                                                       throw e;
-                                               }
+                                                               
+                                                               
+                                                       for (String name : roleNames) {
+                                                               
+                                                               boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
+                                                                               role -> role.getRoleName().equalsIgnoreCase(name));             
+                                                               if(checkIfFunctionsExits)
+                                                               {
+                                                                       EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
+                                                                                       .findAny().orElse(null);
+                                                                       if(epRole != null)
+                                                                       setUserRoles.add(epRole);
+                                                               }
+                                                               
+                                                       }
+                                                       userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
+                                               } 
+                                       }else{
+                                               userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
+                                                               String.format("/user/%s/roles", userId));
                                        }
-                                       if (userAppRoles == null) {
-                                               if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
-                                                       EcompPortalUtils.setExternalAppResponseCode(200);
-                                                       String message = String.format(
-                                                                       "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
-                                                                                       + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
-                                                                                       + "Overriding to 200 until framework SDK returns a useful response.",
-                                                                       Long.toString(appId), userId);
-                                                       logger.warn(EELFLoggerDelegate.applicationLogger, message);
-                                               }
+                               } catch (HTTPException e) {
+                                       // Some apps are returning 400 if user is not found.
+                                       if (e.getResponseCode() == 400) {
+                                               logger.debug(EELFLoggerDelegate.debugLogger,
+                                                               "getAppRolesForUser caught exception with response code 400; continuing", e);
+                                       } else {
+                                               // Other response code, let it come thru.
+                                               throw e;
                                        }
-                                       
-                                        HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
-                                               ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
-                                               if(userAppRoles != null){
-                                                       for (int i = 0; i < userAppRoles.length; i++) {
-                                                               if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
-                                                                       EcompRole role = new EcompRole();
-                                                                       role.setId(userAppRoles[i].getId());
-                                                                       role.setName(userAppRoles[i].getName());
-                                                                       activeRoles.add(role);
-                                                               }
+                               }
+                               if (userAppRoles == null) {
+                                       if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
+                                               EcompPortalUtils.setExternalAppResponseCode(200);
+                                               String message = String.format(
+                                                               "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
+                                                                               + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
+                                                                               + "Overriding to 200 until framework SDK returns a useful response.",
+                                                               Long.toString(appId), userId);
+                                               logger.warn(EELFLoggerDelegate.applicationLogger, message);
+                                       }
+                               }
+                               
+                                HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
+                                       ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
+                                       if(userAppRoles != null){
+                                               for (int i = 0; i < userAppRoles.length; i++) {
+                                                       if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
+                                                               EcompRole role = new EcompRole();
+                                                               role.setId(userAppRoles[i].getId());
+                                                               role.setName(userAppRoles[i].getName());
+                                                               activeRoles.add(role);
                                                        }
                                                }
-                                               EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
-                                       
-                                       // If the remote application isn't down we MUST sync user
-                                       // roles here in case we have this user here!
-                                       syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
-                               } catch (Exception e) {
-                                       // TODO: we may need to check if user exists, maybe remote
-                                       // app is down.
-                                       String message = String.format(
-                                                       "getAppRolesForUser: user %s does not exist in remote application %s", userId,
-                                                       Long.toString(appId));
-                                       logger.error(EELFLoggerDelegate.errorLogger, message, e);
-                                       userAppRoles = new EcompRole[0];
-                               }
-                               rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
+                                       }
+                                       EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
+                               
+                               // If the remote application isn't down we MUST sync user
+                               // roles here in case we have this user here!
+                               syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
+                       } catch (Exception e) {
+                               // TODO: we may need to check if user exists, maybe remote
+                               // app is down.
+                               String message = String.format(
+                                               "getAppRolesForUser: user %s does not exist in remote application %s", userId,
+                                               Long.toString(appId));
+                               logger.error(EELFLoggerDelegate.errorLogger, message, e);
+                               userAppRoles = new EcompRole[0];
                        }
-               } catch (Exception e) {
-                       String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
-                                       Long.toString(appId));
-                       logger.error(EELFLoggerDelegate.errorLogger, message, e);
+                       rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
                }
-               return rolesInAppForUser;
-
+       } catch (Exception e) {
+               String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
+                               Long.toString(appId));
+               logger.error(EELFLoggerDelegate.errorLogger, message, e);
+       }
+       return rolesInAppForUser;
        }
        
        private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
@@ -1739,36 +2061,40 @@ public class UserRolesCommonServiceImpl  {
                return result;
        }
 
+       @SuppressWarnings("unchecked")
        public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
                FieldsValidator fieldsValidator = new FieldsValidator();
                final Map<String, Long> params = new HashMap<>();
-               EPUserAppRoles  appRole= new EPUserAppRoles();
+               List<EPUserAppRoles>  appRole= null;
                try {
                        logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
-                       boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
+                       boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService,
+                               userAppRolesData.getAppId(), user.getId());
                        logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
                                                
-                       params.put("appId", userAppRolesData.appId);
+                       params.put("appId", userAppRolesData.getAppId());
                        EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
                        epAppRolesRequestData.setCreatedDate(new Date());
                        epAppRolesRequestData.setUpdatedDate(new Date());
                        epAppRolesRequestData.setUserId(user.getId());
-                       epAppRolesRequestData.setAppId(userAppRolesData.appId);
+                       epAppRolesRequestData.setAppId(userAppRolesData.getAppId());
                        epAppRolesRequestData.setRequestStatus("P");
-                       List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
+                       List<RoleInAppForUser> appRoleIdList = userAppRolesData.getAppRoles();
                        Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
                        dataAccessService.saveDomainObject(epAppRolesRequestData, null);
                        for (RoleInAppForUser userAppRoles : appRoleIdList) {
                                Boolean isAppliedVal = userAppRoles.isApplied;
                                params.put("appRoleId", userAppRoles.roleId);                           
                                if (isAppliedVal) {
-                                       appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0);
-                                       EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
-                                       epAppRoleDetail.setReqRoleId(appRole.getRoleId());
-                                       epAppRoleDetail.setReqType("P");
-                                       epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
-                                       dataAccessService.saveDomainObject(epAppRoleDetail, null);
-                                       }                       
+                                       appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
+                                       if (!appRole.isEmpty()) {
+                                               EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
+                                               epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
+                                               epAppRoleDetail.setReqType("P");
+                                               epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
+                                               dataAccessService.saveDomainObject(epAppRoleDetail, null);
+                                       }
+                               }                       
                        }
                        epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
                        fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
@@ -1831,9 +2157,10 @@ public class UserRolesCommonServiceImpl  {
        /*
         * (non-Javadoc)
         * 
-        * @see org.openecomp.portalapp.portal.service.UserRolesService#
+        * @see org.onap.portalapp.portal.service.UserRolesService#
         * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
         */
+       @SuppressWarnings("deprecation")
        public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
                // Find the records for this user-app combo, if any
                String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
@@ -1910,16 +2237,49 @@ public class UserRolesCommonServiceImpl  {
         * @param app
         * @return
         */
+       @SuppressWarnings("unchecked")
        private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
                List<RemoteRole> roleList = new ArrayList<RemoteRole>();
                SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
                for (EPRole role : roleSet) {
+                       logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
                        RemoteRole rRole = new RemoteRole();
                        rRole.setId(role.getId());
                        rRole.setName(role.getName());
                        roleList.add(rRole);
                }
+               
+               //Get the active roles of user for that application using query
+               List<EPRole> userEpRoleList = new ArrayList<>();
+               final Map<String, Long> params = new HashMap<>();
+               params.put("appId", app.getId());
+               params.put("userId", user.getId());
+               userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
+
+               for (EPRole remoteUserRoleList : userEpRoleList) {
+
+                       RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
+                                       .findAny().orElse(null);
+                       if (remoteRoleListId == null) {
+                               logger.debug(EELFLoggerDelegate.debugLogger,
+                                               "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
+
+                                               remoteUserRoleList.getName());
+                               RemoteRole role = new RemoteRole();
+                               role.setId(remoteUserRoleList.getId());
+                               role.setName(remoteUserRoleList.getName());
+
+                               roleList.add(role);
+                       }
+
+               }
+
+               logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
+
                return roleList;
+               
+               
+               
        }
 
        public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
@@ -1949,4 +2309,20 @@ public class UserRolesCommonServiceImpl  {
                return userRoleList;
        }
        
+       
+       /*public static void main(String[] args) {
+               List<EcompRole> str1 = new ArrayList<String>();
+               str1.add("A");
+               str1.add("B");
+               str1.add("C");
+               str1.add("D");
+
+               List<String> str2 = new ArrayList<String>();
+               str2.add("D");
+               str2.add("E");
+
+               List<EcompRole> userApplicationRolesList = setUserRoles;
+               List<EcompRole> appRolesList = Arrays.asList(appRoles);
+               
+       }*/
 }