2  * ============LICENSE_START==========================================
 
   4  * ===================================================================
 
   5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 
   6  * ===================================================================
 
   8  * Unless otherwise specified, all software contained herein is licensed
 
   9  * under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this software except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *             http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  21  * Unless otherwise specified, all documentation contained herein is licensed
 
  22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 
  23  * you may not use this documentation except in compliance with the License.
 
  24  * You may obtain a copy of the License at
 
  26  *             https://creativecommons.org/licenses/by/4.0/
 
  28  * Unless required by applicable law or agreed to in writing, documentation
 
  29  * distributed under the License is distributed on an "AS IS" BASIS,
 
  30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  31  * See the License for the specific language governing permissions and
 
  32  * limitations under the License.
 
  34  * ============LICENSE_END============================================
 
  39 package org.onap.portalapp.portal.service;
 
  41 import java.io.IOException;
 
  42 import java.util.ArrayList;
 
  43 import java.util.Arrays;
 
  44 import java.util.Collection;
 
  45 import java.util.Date;
 
  46 import java.util.HashMap;
 
  47 import java.util.HashSet;
 
  48 import java.util.LinkedHashSet;
 
  49 import java.util.List;
 
  52 import java.util.SortedSet;
 
  53 import java.util.TreeSet;
 
  54 import java.util.stream.Collectors;
 
  56 import javax.servlet.http.HttpServletResponse;
 
  58 import org.apache.commons.lang.StringUtils;
 
  59 import org.apache.cxf.transport.http.HTTPException;
 
  60 import org.hibernate.SQLQuery;
 
  61 import org.hibernate.Session;
 
  62 import org.hibernate.SessionFactory;
 
  63 import org.hibernate.Transaction;
 
  64 import org.json.JSONArray;
 
  65 import org.json.JSONObject;
 
  66 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
 
  67 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
 
  68 import org.onap.portalapp.portal.domain.EPApp;
 
  69 import org.onap.portalapp.portal.domain.EPRole;
 
  70 import org.onap.portalapp.portal.domain.EPUser;
 
  71 import org.onap.portalapp.portal.domain.EPUserApp;
 
  72 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
 
  73 import org.onap.portalapp.portal.domain.EPUserAppRoles;
 
  74 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
 
  75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
 
  76 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
 
  77 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
 
  78 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
 
  79 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
 
  80 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
 
  81 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
 
  82 import org.onap.portalapp.portal.transport.CentralV2Role;
 
  83 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
 
  84 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
 
  85 import org.onap.portalapp.portal.transport.ExternalAccessUser;
 
  86 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
 
  87 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
 
  88 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
 
  89 import org.onap.portalapp.portal.transport.FieldsValidator;
 
  90 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
 
  91 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
 
  92 import org.onap.portalapp.portal.transport.RemoteRole;
 
  93 import org.onap.portalapp.portal.transport.RemoteRoleV1;
 
  94 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
 
  95 import org.onap.portalapp.portal.transport.RoleInAppForUser;
 
  96 import org.onap.portalapp.portal.transport.RolesInAppForUser;
 
  97 import org.onap.portalapp.portal.transport.UserApplicationRoles;
 
  98 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 
  99 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 
 100 import org.onap.portalapp.portal.utils.PortalConstants;
 
 101 import org.onap.portalapp.util.SystemType;
 
 102 import org.onap.portalsdk.core.domain.Role;
 
 103 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
 104 import org.onap.portalsdk.core.restful.domain.EcompRole;
 
 105 import org.onap.portalsdk.core.service.DataAccessService;
 
 106 import org.onap.portalsdk.core.service.RoleService;
 
 107 import org.onap.portalsdk.core.util.SystemProperties;
 
 108 import org.springframework.beans.factory.annotation.Autowired;
 
 109 import org.springframework.http.HttpEntity;
 
 110 import org.springframework.http.HttpHeaders;
 
 111 import org.springframework.http.HttpMethod;
 
 112 import org.springframework.http.HttpStatus;
 
 113 import org.springframework.http.ResponseEntity;
 
 114 import org.springframework.web.client.RestTemplate;
 
 116 import com.fasterxml.jackson.core.JsonProcessingException;
 
 117 import com.fasterxml.jackson.databind.DeserializationFeature;
 
 118 import com.fasterxml.jackson.databind.ObjectMapper;
 
 121 public class UserRolesCommonServiceImpl  {
 
 123         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
 
 125         private static final Object syncRests = new Object();
 
 128         private DataAccessService dataAccessService;                            
 
 130         private SessionFactory sessionFactory;
 
 132         private SearchService searchService;
 
 134         private EPAppService appsService;
 
 136         private ApplicationsRestClientService applicationsRestClientService;
 
 138         private EPRoleService epRoleService;
 
 140         private RoleService roleService;        
 
 143         private ExternalAccessRolesService externalAccessRolesService;
 
 146         private AppsCacheService appsCacheService;
 
 148         RestTemplate template = new RestTemplate();
 
 153          * @return  HashMap<Long, EcompRole>
 
 155         private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
 
 156                 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
 
 157                 if (ecompRoles != null) {
 
 158                         for (int i = 0; i < ecompRoles.length; i++) {
 
 159                                 if (ecompRoles[i].getId() != null) {
 
 160                                         result.put(ecompRoles[i].getId(), ecompRoles[i]);
 
 171         protected void createLocalUserIfNecessary(String userId) {
 
 172                 if (StringUtils.isEmpty(userId)) {
 
 173                         logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
 
 176                 Session localSession = null;
 
 177                 Transaction transaction = null;
 
 179                         localSession = sessionFactory.openSession();
 
 180                         transaction = localSession.beginTransaction();
 
 181                         @SuppressWarnings("unchecked")
 
 182                         List<EPUser> userList = localSession
 
 183                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
 
 184                         if (userList.size() == 0) {
 
 185                                 EPUser client = searchService.searchUserByUserId(userId);
 
 186                                 if (client == null) {
 
 187                                         String msg = "createLocalUserIfNecessary: cannot create user " + userId
 
 188                                                         + ", because not found in phonebook";
 
 189                                         logger.error(EELFLoggerDelegate.errorLogger, msg);
 
 191                                         client.setLoginId(userId);
 
 192                                         client.setActive(true);
 
 193                                         localSession.save(client);
 
 196                         transaction.commit();
 
 197                 } catch (Exception e) {
 
 198                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 199                         EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
 
 201                         EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
 
 206          * This method return nothing and remove roles before adding any roles for an app
 
 209          * @param localSession
 
 210          * @param userAppRoles
 
 211          * @param newUserAppRolesMap
 
 213         private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
 
 215                 Long userAppRoleId = 0L;
 
 216                 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
 
 217                         userAppRoleId = userRole.getRoleId();
 
 218                 } else { // remote app
 
 219                         userAppRoleId = userRole.getAppRoleId();
 
 222                 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
 
 223                         localSession.delete(userRole);
 
 225                         newUserAppRolesMap.remove(userAppRoleId);
 
 230          * Checks whether the role is inactive
 
 234          *                      if role is inactive, throws exception
 
 236         private void checkIfRoleInactive(EPRole epRole) throws Exception{       
 
 237                 if(!epRole.getActive()){
 
 238                         throw new Exception(epRole.getName()+ " role is unavailable");
 
 244          * @param sessionFactory
 
 247          * @param userAppRoles
 
 248          * @param extRequestValue 
 
 249          *                      set to false if request is from users page otherwise true
 
 252         protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
 
 253                         EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
 
 254                 Session localSession = null;
 
 255                 Transaction transaction = null;
 
 256                 String roleActive = null;
 
 257                 final Map<String, String> userAppParams = new HashMap<>();
 
 258                 final Map<String, String> appParams = new HashMap<>();
 
 259                 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
 
 262                         localSession = sessionFactory.openSession();
 
 263                         transaction = localSession.beginTransaction();
 
 264                         @SuppressWarnings("unchecked")
 
 265                         List<EPUser> userList = localSession
 
 266                                         .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
 
 267                         if (userList.size() > 0) {
 
 268                                 EPUser client = userList.get(0);
 
 269                                 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
 
 270                                 @SuppressWarnings("unchecked")
 
 271                                 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
 
 272                                                 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
 
 274                                 if ("DELETE".equals(reqType)) {
 
 275                                         for (EPUserApp userAppRoleList : userRoles) {
 
 276                                                 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
 
 277                                                 userAppParams.put("appId",  String.valueOf(appId));
 
 278                                                 appParams.put("appRoleName", userAppRoleList.getRole().getName());
 
 279                                                 @SuppressWarnings("unchecked")
 
 280                                                 List<EPRole>  rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);        
 
 281                                                 if(rolesList.size() > 0 || !rolesList.isEmpty()){
 
 282                                                 checkIfRoleInactive(rolesList.get(0));
 
 287                                 for (EPUserApp userRole : userRoles) {
 
 288                                         if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
 
 289                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 291                                         else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
 
 292                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 294                                         else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
 
 295                                                 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
 
 298                                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
 
 299                                 if (newRolesToAdd.size() > 0) {
 
 300                                         EPApp app = (EPApp) localSession.get(EPApp.class, appId);
 
 302                                         HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
 
 303                                         if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
 
 304                                                 String appIdValue = "";
 
 305                                                 if(!extRequestValue){
 
 306                                                         appIdValue = "and id != " +  PortalConstants.SYS_ADMIN_ROLE_ID; 
 
 308                                                 @SuppressWarnings("unchecked")
 
 309                                                 List<EPRole> roles = localSession
 
 310                                                                 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
 
 311                                                 for (EPRole role : roles) {
 
 313                                                         rolesMap.put(role.getId(), role);
 
 315                                         } else { // remote app
 
 316                                                 @SuppressWarnings("unchecked")
 
 317                                                 List<EPRole> roles = localSession
 
 318                                                                 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
 
 319                                                 for (EPRole role : roles) {
 
 320                                                         if (!extRequestValue && app.getCentralAuth()) {
 
 321                                                                 rolesMap.put(role.getId(), role);
 
 323                                                                 rolesMap.put(role.getAppRoleId(), role);
 
 329                                         for (EcompRole userRole : newRolesToAdd) {
 
 330                                                 EPUserApp userApp = new EPUserApp();
 
 331                                                 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
 
 332                                                         role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
 333                                                         userApp.setRole(role);
 
 334                                                 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
 
 336                                                 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
 
 340                                                         userApp.setRole(rolesMap.get(userRole.getId()));
 
 343                                                 userApp.setUserId(client.getId());
 
 345                                                 localSession.save(userApp);
 
 346                                                 localSession.flush();
 
 349                                         if (appId == PortalConstants.PORTAL_APP_ID) {
 
 351                                                  * for local app -- hack - always make sure fn_role
 
 352                                                  * table's app_id is null and not 1 for primary app in
 
 353                                                  * this case being onap portal app; reason: hibernate
 
 354                                                  * is rightly setting this to 1 while persisting to
 
 355                                                  * fn_role as per the mapping but SDK role management
 
 356                                                  * code expects the app_id to be null as there is no
 
 357                                                  * concept of App_id in SDK
 
 359                                                 localSession.flush();
 
 360                                                 SQLQuery sqlQuery = localSession
 
 361                                                                 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
 
 362                                                 sqlQuery.executeUpdate();
 
 367                         transaction.commit();
 
 368                 } catch (Exception e) {
 
 369                         logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
 
 370                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 371                         EcompPortalUtils.rollbackTransaction(transaction,
 
 372                                         "Exception occurred in syncUserRoles, Details: " + e.toString());
 
 373                         if("DELETE".equals(reqType)){
 
 374                                 throw new SyncUserRolesException(e.getMessage());
 
 377                         if(localSession != null)
 
 378                                 localSession.close();
 
 383          * Called when getting the list of roles for the user
 
 386          * @param userAppRoles
 
 387          * @return List<RoleInAppForUser> 
 
 389         protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
 
 390                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
 
 392                 Set<Long> userAppRolesMap = new HashSet<Long>();
 
 393                 if (userAppRoles != null) {
 
 394                         for (EcompRole ecompRole : userAppRoles) {
 
 395                                 userAppRolesMap.add(ecompRole.getId());
 
 398                         logger.error(EELFLoggerDelegate.errorLogger,
 
 399                                         "constructRolesInAppForUserGet has received userAppRoles list empty");
 
 402                 if (appRoles != null) {
 
 403                         for (EcompRole ecompRole : appRoles) {
 
 404                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
 
 405                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
 
 406                                 rolesInAppForUser.add(roleForUser);
 
 409                         logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
 
 411                 return rolesInAppForUser;
 
 415          * Called when getting the list of roles for the user
 
 418          * @param userAppRoles
 
 419          * @param extRequestValue 
 
 420          *                      set to false if request is from users page otherwise true
 
 421          * @return List<RoleInAppForUser>
 
 423         protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
 
 424                 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
 
 426                 Set<Long> userAppRolesMap = new HashSet<Long>();
 
 427                 if (userAppRoles != null) {
 
 428                         for (EPRole ecompRole : userAppRoles) {
 
 429                                 userAppRolesMap.add(ecompRole.getId());
 
 432                         logger.error(EELFLoggerDelegate.errorLogger,
 
 433                                         "constructRolesInAppForUserGet has received userAppRoles list empty.");
 
 436                 if (appRoles != null) {
 
 437                         for (Role ecompRole : appRoles) {
 
 438                                 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
 
 440                                 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
 
 441                                 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
 
 442                                 rolesInAppForUser.add(roleForUser);
 
 445                         logger.error(EELFLoggerDelegate.errorLogger,
 
 446                                         "constructRolesInAppForUser has received appRoles list empty.");
 
 448                 return rolesInAppForUser;
 
 453          * copies of methods in GetAppsWithUserRoleState
 
 455          * @param sessionFactory
 
 460         protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
 
 461                 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
 
 462                 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
 
 463                 Session localSession = null;
 
 464                 Transaction transaction = null;
 
 467                         localSession = sessionFactory.openSession();
 
 468                         transaction = localSession.beginTransaction();
 
 469                         // Attention! All roles from remote application supposed to be
 
 471                         @SuppressWarnings("unchecked")
 
 472                         List<EPRole> currentAppRoles = localSession
 
 473                                         .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
 
 474                         List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
 
 475                         for (int i = 0; i < currentAppRoles.size(); i++) {
 
 476                                 EPRole oldAppRole = currentAppRoles.get(i);
 
 477                                 if (oldAppRole.getAppRoleId() != null) {
 
 478                                         EcompRole role = null;
 
 479                                         role = newRolesMap.get(oldAppRole.getAppRoleId());
 
 481                                                 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
 
 482                                                         oldAppRole.setName(role.getName());
 
 483                                                         localSession.update(oldAppRole);
 
 485                                                 oldAppRole.setActive(true);
 
 486                                                 newRolesMap.remove(oldAppRole.getAppRoleId());
 
 488                                                 obsoleteRoles.add(oldAppRole);
 
 491                                         obsoleteRoles.add(oldAppRole);
 
 494                         Collection<EcompRole> newRolesToAdd = newRolesMap.values();
 
 495                         if (obsoleteRoles.size() > 0) {
 
 496                                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
 
 497                                 for (EPRole role : obsoleteRoles) {
 
 498                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
 
 499                                         Long roleId = role.getId();
 
 500                                         // delete obsolete roles here
 
 501                                         // Must delete all records with foreign key constraints on
 
 503                                         // fn_user_role, fn_role_composite, fn_role_function,
 
 504                                         // fn_user_pseudo_role, fn_menu_functional_roles.
 
 505                                         // And for fn_menu_functional, if no other roles for that
 
 506                                         // menu item, remove the url.
 
 508                                         // Delete from fn_user_role
 
 509                                         @SuppressWarnings("unchecked")
 
 510                                         List<EPUserApp> userRoles = localSession.createQuery(
 
 511                                                         "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
 
 514                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
 
 515                                         for (EPUserApp userRole : userRoles) {
 
 516                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 517                                                                 "syncAppRoles: about to delete userRole: " + userRole.toString());
 
 518                                                 localSession.delete(userRole);
 
 519                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 520                                                                 "syncAppRoles: finished deleting userRole: " + userRole.toString());
 
 523                                         // Delete from fn_menu_functional_roles
 
 524                                         @SuppressWarnings("unchecked")
 
 525                                         List<FunctionalMenuRole> funcMenuRoles = localSession
 
 526                                                         .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
 
 528                                         int numMenuRoles = funcMenuRoles.size();
 
 529                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 530                                                         "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
 
 531                                         for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
 
 532                                                 Long menuId = funcMenuRole.menuId;
 
 533                                                 // If this is the only role for this menu item, then the
 
 534                                                 // app and roles will be gone,
 
 535                                                 // so must null out the url too, to be consistent
 
 536                                                 @SuppressWarnings("unchecked")
 
 537                                                 List<FunctionalMenuRole> funcMenuRoles2 = localSession
 
 538                                                                 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
 
 540                                                 int numMenuRoles2 = funcMenuRoles2.size();
 
 541                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 542                                                                 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
 
 543                                                 localSession.delete(funcMenuRole);
 
 544                                                 if (numMenuRoles2 == 1) {
 
 545                                                         // If this is the only role for this menu item, then
 
 546                                                         // the app and roles will be gone,
 
 547                                                         // so must null out the url too, to be consistent
 
 548                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 549                                                                         "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
 
 550                                                         @SuppressWarnings("unchecked")
 
 551                                                         List<FunctionalMenuItem> funcMenuItems = localSession
 
 553                                                                                         "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
 
 555                                                         if (funcMenuItems.size() > 0) {
 
 556                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
 
 557                                                                 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
 
 558                                                                 funcMenuItem.url = "";
 
 559                                                                 localSession.update(funcMenuItem);
 
 563                                         boolean isPortalRequest = true;
 
 564                                         externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
 
 565                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
 
 566                                         localSession.delete(role);
 
 567                                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
 
 570                         for (EcompRole role : newRolesToAdd) {
 
 571                                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
 
 572                                 EPRole newRole = new EPRole();
 
 573                                 // Attention! All roles from remote application supposed to be
 
 575                                 newRole.setActive(true);
 
 576                                 newRole.setName(role.getName());
 
 577                                 newRole.setAppId(appId);
 
 578                                 newRole.setAppRoleId(role.getId());
 
 579                                 localSession.save(newRole);
 
 581                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
 
 582                         transaction.commit();
 
 583                         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
 
 584                 } catch (Exception e) {
 
 585                         logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
 
 586                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
 
 587                         EcompPortalUtils.rollbackTransaction(transaction,
 
 588                                         "Exception occurred in syncAppRoles, Details: " + e.toString());
 
 589                         throw new Exception(e);
 
 591                         localSession.close();
 
 600          * Called when updating the list of roles for the user
 
 604          * @param userRolesInRemoteApp
 
 605          * @return RolesInAppForUser
 
 607         protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
 
 608                         Set<EcompRole> userRolesInRemoteApp) {
 
 609                 RolesInAppForUser result;
 
 610                 result = new RolesInAppForUser();
 
 611                 result.appId = appId;
 
 612                 result.orgUserId = userId;
 
 613                 for (EcompRole role : userRolesInRemoteApp) {
 
 614                         RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
 
 615                         roleInAppForUser.roleId = role.getId();
 
 616                         roleInAppForUser.roleName = role.getName();
 
 617                         roleInAppForUser.isApplied = new Boolean(true);
 
 618                         result.roles.add(roleInAppForUser);
 
 625          * @param roleInAppForUserList
 
 628         protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
 
 629                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 630                         if (roleInAppForUser.isApplied.booleanValue()) {
 
 638          * Builds JSON and posts it to a remote application to update user roles.
 
 640          * @param roleInAppForUserList
 
 642          * @param applicationsRestClientService
 
 645          * @return Set of roles as sent; NOT the response from the app.
 
 646          * @throws JsonProcessingException
 
 647          * @throws HTTPException
 
 649         protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
 
 650                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
 
 651                         throws JsonProcessingException, HTTPException {
 
 652                 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
 
 653                 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
 
 654                 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
 
 655         EPApp externalApp = null;
 
 656         SystemType type = SystemType.APPLICATION;
 
 657                 externalApp = appsCacheService.getApp(appId);
 
 658                 String appBaseUri = null;
 
 659                 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
 
 660                 if (externalApp != null) {
 
 661                          appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
 
 663                 if(appBaseUri != null && appBaseUri.endsWith("/api")){
 
 664                         for(EcompRole eprole :updatedUserRolesinRemote)
 
 666                                 RemoteRoleV1 role = new RemoteRoleV1();
 
 667                                 role.setId(eprole.getId());
 
 668                                 role.setName(eprole.getName());
 
 669                                 updatedUserRolesinRemoteV1.add(role);
 
 671                         userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
 
 673                 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
 
 674                                 String.format("/user/%s/roles", userId));
 
 675                 // TODO: We should add code that verifies that the post operation did
 
 676                 // succeed. Because the SDK may still return 200 OK with an html page
 
 677                 // even when it fails!
 
 678                 return updateUserRolesInEcomp;
 
 683          * @param roleInAppForUserList
 
 684          * @return Set<EcompRole> 
 
 686         protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
 
 687                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
 
 688                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 689                         if (roleInAppForUser.isApplied) {
 
 690                                 EcompRole ecompRole = new EcompRole();
 
 691                                 ecompRole.setId(roleInAppForUser.roleId);
 
 692                                 ecompRole.setName(roleInAppForUser.roleName);
 
 693                                 existingUserRoles.add(ecompRole);
 
 696                 return existingUserRoles;
 
 700          * Constructs user app roles excluding Account Administrator role
 
 702          * @param roleInAppForUserList
 
 704          *            List of roles with Role name, Role Id
 
 706         protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
 
 707                 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
 
 708                 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
 
 709                         if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
 
 710                                 EcompRole ecompRole = new EcompRole();
 
 711                                 ecompRole.setId(roleInAppForUser.roleId);
 
 712                                 ecompRole.setName(roleInAppForUser.roleName);
 
 713                                 existingUserRoles.add(ecompRole);
 
 716                 return existingUserRoles;
 
 720          * This is for a single app
 
 722          * @param rolesInAppForUser
 
 723          * @param externalSystemRequest  
 
 724          *                      set to false if requests from Users page otherwise true
 
 725          * @return true on success, false otherwise
 
 727         protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
 
 728                 boolean result = false;
 
 729                 String userId = rolesInAppForUser.orgUserId;
 
 730                 Long appId = rolesInAppForUser.appId;
 
 731                 synchronized (syncRests) {
 
 732                         if (rolesInAppForUser != null) {
 
 733                                 createLocalUserIfNecessary(userId);
 
 736                         if (rolesInAppForUser != null) {
 
 737                                 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
 
 738                                 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
 
 739                                         RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
 
 740                                         EcompRole role = new EcompRole();
 
 741                                         role.setId(roleInAppForUser.roleId);
 
 742                                         role.setName(roleInAppForUser.roleName);
 
 743                                         userAppRoles[i] = role;
 
 746                                         syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
 
 748                                 } catch (Exception e) {
 
 749                                         logger.error(EELFLoggerDelegate.errorLogger,
 
 750                                                         "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
 
 751                                         if("DELETE".equals(reqType)){
 
 752                                                 throw new Exception(e.getMessage());
 
 764          * @return UserApplicationRoles
 
 766         protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
 
 767                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
 
 768                 userWithRemoteAppRoles.setAppId(appId);
 
 769                 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
 
 770                 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
 
 771                 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
 
 772                 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
 
 773                 return userWithRemoteAppRoles;
 
 779          * @see org.onap.portalapp.portal.service.UserRolesService#
 
 780          * importRolesFromRemoteApplication(java.lang.Long)
 
 782         public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
 
 783                 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
 
 784                 List<EPRole> rolesList = Arrays.asList(appRolesFull);
 
 785                 for (EPRole externalAppRole : rolesList) {
 
 787                         // Try to find an existing extern role for the app in the local
 
 788                         // onap DB. If so, then use its id to update the existing external
 
 789                         // application role record.
 
 790                         Long externAppId = externalAppRole.getId();
 
 791                         EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
 
 792                         if (existingAppRole != null) {
 
 793                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 794                                                 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
 
 795                                                                 appId, externAppId));
 
 798                         // persistExternalRoleInEcompDb(externalAppRole, appId,
 
 806          * It adds new user for remote application
 
 808          * @param roleInAppForUserList
 
 809          * @param remoteAppUser
 
 813          * @param searchService
 
 814          * @param applicationsRestClientService
 
 818         private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{
 
 819                 EPUser addRemoteUser = null;
 
 820                 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
 
 821                         createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app));
 
 823                 return addRemoteUser;
 
 827          * It checks whether the remote user exists or not
 
 828          * if exits returns user object else null
 
 832          * @param applicationsRestClientService
 
 834          * @throws HTTPException
 
 836         private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
 
 837                 EPUser checkRemoteUser = null;
 
 839                         checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
 
 840                 } catch (HTTPException e) {
 
 841                         // Some apps are returning 400 if user is not found.
 
 842                         if (e.getResponseCode() == 400) {
 
 843                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 844                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
 
 846                         } else if(e.getResponseCode() == 404) {
 
 847                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 848                                                 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
 
 851                                 // Other response code, let it come thru.
 
 855                 return checkRemoteUser;
 
 862          * @see org.onap.portalapp.portal.service.UserRolesService#
 
 863          * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
 
 864          * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
 
 866         public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
 
 867                 boolean result = false;
 
 868                 boolean epRequestValue = false;
 
 870                 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
 
 871                         userId = newAppRolesForUser.orgUserId.trim();
 
 873                 Long appId = newAppRolesForUser.appId;
 
 874                 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
 
 875                 if (userId.length() > 0) {
 
 876                         ObjectMapper mapper = new ObjectMapper();
 
 877                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
 880                                 EPApp app = appsService.getApp(appId);
 
 881                                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
 
 883                                 // if centralized app
 
 884                                 if (app.getCentralAuth()) {
 
 885                                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
 887                                                         addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
 
 888                                                                         applicationsRestClientService);
 
 889                                                 } catch (Exception e) {
 
 890                                                         logger.debug(EELFLoggerDelegate.debugLogger, e.getMessage());
 
 894                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
 895                                                         applicationsRestClientService, appId, userId);
 
 896                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 897                                                         userRolesInLocalApp);
 
 898                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
 
 899                                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
 900                                                 // Apply changes in external Access system
 
 901                                                 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
 
 904                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
 
 906                                 // In case if portal is not centralized then follow existing approach
 
 907                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 908                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
 909                                                         applicationsRestClientService, appId, userId);  
 
 910                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 911                                                         userRolesInLocalApp);
 
 912                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
 
 914                                         EPUser remoteAppUser = null;
 
 915                                         if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
 917                                                 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
 
 919                                                 if (remoteAppUser == null) {
 
 920                                                         remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
 
 922                                                 if (remoteAppUser != null) {
 
 923                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
 
 924                                                                         applicationsRestClientService, appId, userId);
 
 925                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
 
 926                                                                         userRolesInRemoteApp);
 
 927                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
 
 929                                                         // If no roles remain, request app to set user inactive.
 
 930                                                         if (userRolesInRemoteApp.size() == 0) {
 
 931                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
 932                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
 
 934                                                                 remoteAppUser.setActive(false);
 
 935                                                                 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
 
 940                         } catch (Exception e) {
 
 941                                 String message = String.format(
 
 942                                                 "Failed to create user or update user roles for User %s, AppId %s",
 
 943                                                 userId, Long.toString(appId));
 
 944                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
 952          * It adds user roles in External system and also make data consistent in both local and in External System 
 
 956          * @param roleInAppUser Contains list of active roles 
 
 958         @SuppressWarnings("unchecked")
 
 959         private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
 
 962                         // check if user exists
 
 963                         final Map<String, String> userParams = new HashMap<>();
 
 964                         userParams.put("orgUserIdValue", orgUserId);
 
 965                         List<EPUser> userInfo = checkIfUserExists(userParams);
 
 966                         if (userInfo.isEmpty()) {
 
 967                                 createLocalUserIfNecessary(orgUserId);
 
 970                         if (EPCommonSystemProperties
 
 971                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
 
 973                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
 
 975                         ObjectMapper mapper = new ObjectMapper();
 
 976                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
 
 977                         HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
 
 978                         ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
 
 979                         List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
 
 980                         String res = getResponse.getBody();
 
 981                         JSONObject jsonObj = null;
 
 982                         JSONArray extRoles = null;
 
 983                         if (!res.equals("{}")) {
 
 984                                 jsonObj = new JSONObject(res);
 
 985                                 extRoles = jsonObj.getJSONArray("role");
 
 987                         ExternalAccessUserRoleDetail userRoleDetail = null;
 
 988                         if (extRoles != null) {
 
 989                                 for (int i = 0; i < extRoles.length(); i++) {
 
 990                                         if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
 
 991                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
 
 992                                                         && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
 
 993                                                 ObjectMapper descMapper = new ObjectMapper();
 
 994                                                 if (extRoles.getJSONObject(i).has("description") && EcompPortalUtils.isJSONValid(extRoles.getJSONObject(i).getString("description"))) {
 
 995                                                         ExternalRoleDescription desc = descMapper.readValue(
 
 996                                                                         extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class);
 
 997                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
 
 998                                                                         extRoles.getJSONObject(i).getString("name"), desc);
 
 999                                                         userRoleDetailList.add(userRoleDetail);
 
1001                                                         userRoleDetail = new ExternalAccessUserRoleDetail(
 
1002                                                                         extRoles.getJSONObject(i).getString("name"), null);
 
1003                                                         userRoleDetailList.add(userRoleDetail);
 
1010                         List<ExternalAccessUserRoleDetail>  userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
 
1012                         // If request coming from portal not from external role approval system then we have to check if user already 
 
1013                         // have account admin or system admin as GUI will not send these roles 
 
1014                         if (!isPortalRequest) {
 
1015                                 final Map<String, String> loginIdParams = new HashMap<>();
 
1016                                 loginIdParams.put("orgUserIdValue", orgUserId);
 
1017                                 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
 
1018                                 final Map<String, Long> params = new HashMap<>();
 
1019                                 params.put("appId", app.getId());
 
1020                                 params.put("userId", user.getId());
 
1021                                 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
 
1023                                 if (!roleInAppUser.isEmpty()) {
 
1024                                         for (EcompUserAppRoles userApp : userAppList) {
 
1025                                                 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
 
1026                                                                 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
 
1027                                                         RoleInAppForUser addSpecialRole = new RoleInAppForUser();
 
1028                                                         addSpecialRole.setIsApplied(true);
 
1029                                                         addSpecialRole.setRoleId(userApp.getRoleId());
 
1030                                                         addSpecialRole.setRoleName(userApp.getRoleName());
 
1031                                                         roleInAppUser.add(addSpecialRole);
 
1036                         List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
 
1037                                         .collect(Collectors.toList());
 
1038                         final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
 
1039                         for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
 
1040                                 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
 
1042                         final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
 
1043                         for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
 
1044                                 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
 
1046                         // Check if user roles does not exists in local but still there in External Central Auth System delete them all
 
1047                         for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
 
1048                                 if (!(currentUserRolesToUpdate
 
1049                                                 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
 
1050                                         HttpEntity<String> entity = new HttpEntity<>(headers);
 
1051                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1052                                                         "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
 
1053                                                         userRole.getName());
 
1054                                         ResponseEntity<String> deleteResponse = template.exchange(
 
1055                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1056                                                                         + "userRole/" + name + "/" + userRole.getName(),
 
1057                                                         HttpMethod.DELETE, entity, String.class);
 
1058                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1059                                                         "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
 
1060                                                         userRole.getName(), deleteResponse.getBody());
 
1063                         // Check if user roles does not exists in External Central Auth System add them all
 
1064                         for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
 
1065                                 if (!(currentUserRolesInExternalSystem
 
1066                                                 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
 
1067                                         ExternalAccessUser extUser = new ExternalAccessUser(name,
 
1068                                                         app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
1069                                         String formattedUserRole = mapper.writeValueAsString(extUser);
 
1070                                         HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
 
1071                                         logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
 
1072                                                         name , addUserRole.getRoleName());
 
1073                                         ResponseEntity<String> addResponse = template
 
1074                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
 
1075                                                                         + "userRole", HttpMethod.POST, entity, String.class);
 
1076                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1077                                                         "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
 
1078                                                         addResponse.getBody(), addUserRole.getRoleName());
 
1079                                         if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
 
1080                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1081                                                                 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
 
1082                                                                 addUserRole.getRoleName());
 
1083                                                 throw new Exception(addResponse.getBody());
 
1087                 } catch (Exception e) {
 
1088                         logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
 
1089                         EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
 
1095         private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
 
1096                         List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {             
 
1097                 Map<String, EPRole> epRoleList  = externalAccessRolesService.getCurrentRolesInDB(app);  
 
1098                 //Add Account Admin role for partner app to prevent conflict
 
1099                 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1100                 EPRole role =  new EPRole();
 
1101                 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
 
1102                 epRoleList.put(role.getName(), role);
 
1104                 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));              
 
1105                 return userRoleDetailList;
 
1112          * @param applicationsRestClientService
 
1113          * @param searchService
 
1117         protected void createNewUserOnRemoteApp(String userId, EPApp app,
 
1118                         ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
 
1119                         ObjectMapper mapper, boolean postOpenSource) throws Exception {
 
1122                         EPUser client = searchService.searchUserByUserId(userId);
 
1124                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1126                         if (client == null) {
 
1127                                 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
 
1128                                 logger.error(EELFLoggerDelegate.errorLogger, msg);
 
1129                                 throw new Exception(msg);
 
1132                         client.setLoginId(userId);
 
1133                         client.setActive(true);
 
1135                         String userInString = null;
 
1136                         userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
 
1137                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1138                                         "about to post new client to remote application, users json = " + userInString);
 
1139                         applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
 
1143         @SuppressWarnings("unchecked")
 
1144         protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
 
1145                 final Map<String, Long> epRequestParams = new HashMap<>();
 
1147                         EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
 
1148                         epAppRolesRequestData.setUpdatedDate(new Date());
 
1149                         epAppRolesRequestData.setRequestStatus(updateStatus);
 
1150                         HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
 
1151                         addiotonalUpdateParam.put("userId", userId);
 
1152                         dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
 
1153                         epRequestParams.put("reqId", epUserAppRolesRequest.getId());
 
1154                         List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
 
1155                         epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
 
1156                                         epRequestParams, null);
 
1157                         if (epUserAppRolessDetailList.size() > 0) {
 
1158                                 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
 
1159                                         EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
 
1160                                         epAppRoleDetailData.setReqType(updateStatus);
 
1161                                         epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
 
1162                                         HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
 
1163                                         addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
 
1164                                         dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
 
1167                         logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
 
1169                 } catch (Exception e) {
 
1170                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
 
1174         @SuppressWarnings("unchecked")
 
1175         public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
 
1176                 final Map<String, Long> params = new HashMap<>();
 
1177                 final Map<String, Long> epDetailParams = new HashMap<>();
 
1178                 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
 
1179                 params.put("appId", appId);
 
1180                 params.put("userId", user.getId());
 
1182                         epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
 
1183                                         .executeNamedQuery("userAppRolesRequestList", params, null);
 
1184                         if (epRequestIdVal.size() > 0) {
 
1185                                 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
 
1186                                 epAppRolesRequestData.setUpdatedDate(new Date());
 
1187                                 epAppRolesRequestData.setRequestStatus("O");
 
1188                                 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
 
1189                                 addiotonalUpdateParam.put("userId", user.getId());
 
1190                                 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
 
1191                                 epDetailParams.put("reqId", epAppRolesRequestData.getId());
 
1192                                 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
 
1193                                 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
 
1194                                                 epDetailParams, null);
 
1195                                 if (epUserAppRolesDetailList.size() > 0) {
 
1196                                         for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
 
1197                                                 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
 
1198                                                 epAppRoleDetailData.setReqType("O");
 
1199                                                 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
 
1200                                                 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
 
1201                                                 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
 
1202                                                 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
 
1204                                         logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
 
1208                 } catch (Exception e) {
 
1209                         logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
 
1214          * Pushes specified user details to the specified remote app.
 
1217          *            OrgUserId identifying user at remote app in REST endpoint path
 
1219          *            User details to be pushed
 
1222          * @param applicationsRestClientService
 
1223          * @throws HTTPException
 
1225         protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
 
1226                         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
 
1228                  getUser(userId, app, applicationsRestClientService);
 
1233          * It returns user details for single org user id
 
1237          *              if user exists it returns list of user details otherwise empty value
 
1239         @SuppressWarnings("unchecked")
 
1240         private List<EPUser> checkIfUserExists(Map<String, String> userParams){ 
 
1241                 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
 
1245          * It checks whether the new user is valid or not otherwise throws exception
 
1250          *                      Checks if user is valid and returns message otherwise throws exception
 
1253         private String validateNewUser(String orgUserId, EPApp app) throws Exception {
 
1254                 EPUser epUser = searchService.searchUserByUserId(orgUserId);
 
1255                 if (epUser == null) {
 
1256                         throw new Exception("User does not exist");
 
1257                 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
 
1258                         throw new Exception("User does not exist");
 
1259                 } else if (app == null) {
 
1260                         throw new Exception("Application does not exist");
 
1262                 return "Saved Successfully";
 
1266          *   Checks if the fields exists or not
 
1269          *                      contains user information
 
1273          *                      throws exception if the field is not valid
 
1275         private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
 
1276                 if (userList.size() == 0 || userList.isEmpty() ) {
 
1277                         throw new Exception("User does not exist");
 
1278                 } else if(app == null) {
 
1279                         throw new Exception("Application does not exist");
 
1280                 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
 
1281                         throw new Exception(app.getMlAppName()+" application is unavailable");
 
1285         @SuppressWarnings("unchecked")
 
1286         public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
 
1287                 boolean result = false;
 
1288                 boolean externalSystemRequest = true;
 
1289                 final Map<String, Long> params = new HashMap<>();
 
1290                 final Map<String, String> userParams = new HashMap<>();
 
1291                 List<EPUser> userInfo = null;
 
1292                 EPUser userId = null;
 
1293                 List<EPUserAppRolesRequest> epRequestId = null;
 
1294                 String orgUserId = "";
 
1295                 String updateStatus = "";
 
1296                 String reqMessage = "";
 
1298                 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
 
1299                         orgUserId = newAppRolesForUser.getLoginId().trim();
 
1301                 String appName = newAppRolesForUser.getApplicationName();
 
1302                 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
 
1303                 if (orgUserId.length() > 0) {
 
1304                         ObjectMapper mapper = new ObjectMapper();
 
1305                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1306                         int epRequestIdSize = 0;
 
1308                                 app = appsService.getAppDetail(appName);
 
1309                                 userParams.put("orgUserIdValue", orgUserId);
 
1310                                 userInfo = checkIfUserExists(userParams);
 
1311                                 reqMessage = "Updated Successfully";
 
1312                                 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
 
1313                                         reqMessage = validateNewUser(orgUserId, app);
 
1315                                 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
 
1316                                         validateExternalRequestFields(userInfo, app);
 
1317                                         userId = userInfo.get(0);
 
1318                                         params.put("appId", app.getId());
 
1319                                         params.put("userId", userId.getId());
 
1320                                         epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
 
1321                                                         .executeNamedQuery("userAppRolesRequestList", params, null);
 
1322                                         epRequestIdSize = epRequestId.size();
 
1325                                 //If Non-Centralized app make sure you sync app roles before assigning to user
 
1326                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
 
1327                                         logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
 
1328                                         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
 
1329                                         logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
 
1330                                         if (appRoles.length > 0) {
 
1331                                                 syncAppRoles(sessionFactory, app.getId(), appRoles);
 
1334                                 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
 
1335                                                 app.getId(), app.getMlAppName());
 
1336                                 List<EcompUserAppRoles> userRoleList = null;
 
1337                                 if(!userInfo.isEmpty()){
 
1338                                 final Map<String, Long> appParams = new HashMap<>();
 
1339                                 appParams.put("userId", userId.getId());
 
1340                                 appParams.put("appId", app.getId());
 
1341                                 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
 
1343                                 // Check if list contains just account admin role
 
1344                                 boolean checkIfAdminRoleExists = false;
 
1345                                 if (reqType.equals("DELETE") && userRoleList!=null) {
 
1346                                         checkIfAdminRoleExists = userRoleList.stream()
 
1347                                                         .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
1349                                         checkIfAdminRoleExists = roleInAppForUserList.stream()
 
1350                                                         .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
 
1352                                 // if Centralized app
 
1353                                 if (app.getCentralAuth()) {
 
1354                                         // We should add If user does not exist in remote application
 
1356                                                 // If adding just account admin role dont make remote application user call
 
1357                                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists
 
1358                                                                 && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) {
 
1359                                                         EPUser remoteAppUser = null;
 
1360                                                         remoteAppUser = checkIfRemoteUserExits(orgUserId, app,
 
1361                                                                         applicationsRestClientService);
 
1362                                                         if (remoteAppUser == null) {
 
1363                                                                 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
 
1364                                                                                 applicationsRestClientService);
 
1365                                                                 reqMessage = "Saved Successfully";
 
1368                                         } catch (Exception e) {
 
1369                                                 reqMessage = e.getMessage();
 
1370                                                 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
 
1371                                                 throw new Exception(reqMessage);
 
1373                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
1374                                                         applicationsRestClientService, app.getId(), orgUserId);
 
1375                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1376                                                         userRolesInLocalApp);
 
1377                                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
 
1378                                         if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
 
1379                                         // Apply changes in external Access system
 
1380                                         updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
 
1382                                         logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
 
1383                                                         newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
 
1384                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
 
1386                                 // If local application is not centralized 
 
1387                                 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
 
1388                                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
 
1389                                                         applicationsRestClientService, app.getId(), orgUserId); 
 
1390                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1391                                                         userRolesInLocalApp);
 
1392                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
 
1393                                 } else {// remote app
 
1394                                         // If adding just account admin role don't do remote application user call
 
1395                                         if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){
 
1396                                         EPUser remoteAppUser = null;
 
1397                                                 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
 
1398                                         if (remoteAppUser == null) {
 
1399                                                 remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService);
 
1400                                                 reqMessage = "Saved Successfully";
 
1402                                                 if (remoteAppUser != null) {
 
1403                                                         Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList,
 
1404                                                                         mapper, applicationsRestClientService, app.getId(), orgUserId);
 
1406                                                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId,
 
1407                                                                         app.getId(), userRolesInRemoteApp);
 
1408                                                         logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
 
1409                                                                         logMessage, newAppRolesForUser.getApplicationName(),
 
1410                                                                         newAppRolesForUser.getLoginId());
 
1411                                                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
 
1413                                                         // If no roles remain, request app to set user inactive.
 
1414                                                         /*if (userRolesInRemoteApp.size() == 0) {
 
1415                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
 
1416                                                                                 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
 
1418                                                                 //TODO Need  to fix the logged in user is not set to inactive
 
1419                                                                 remoteAppUser.setActive(false);
 
1420                                                                 postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService);
 
1424                                                 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote 
 
1425                                                 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
 
1426                                                         reqMessage = "Saved Successfully";
 
1428                                                 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
 
1430                                                 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
 
1431                                                                 userRolesInRemoteApp);
 
1432                                                 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
 
1433                                                                 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
 
1434                                                 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
 
1438                                                 reqMessage = "Failed to save the user app role(s)";
 
1440                                         if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
 
1442                                                 applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0));
 
1445                         } catch (Exception e) {
 
1446                                 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
 
1447                                                 orgUserId, appName);
 
1448                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1450                                 reqMessage = e.getMessage();
 
1451                                  if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
 
1453                                  applyChangesToAppRolesRequest(app.getId(), userId.getId(),
 
1454                                  updateStatus, epRequestId.get(0));
 
1459                 return new ExternalRequestFieldsValidator(result, reqMessage);
 
1464          * @param roleInAppForUserList
 
1466          * @param applicationsRestClientService
 
1469          * @return  Set<EcompRole>
 
1470          * @throws JsonProcessingException
 
1471          * @throws HTTPException
 
1473         private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
 
1474                         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
 
1475                         throws JsonProcessingException, HTTPException {
 
1476                 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
 
1477                 return updatedUserRoles;
 
1481          * It constructs and returns list of user app roles when the external API role approval system calls
 
1484          * @param roleInAppForUserList
 
1486          * @return list of user app roles
 
1488          *                 throws exceptions if role id does not exits 
 
1490         private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
 
1491                         Long appId, String appName) throws Exception {
 
1492                 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
 
1493                 EPRole existingAppRole = null;
 
1494                 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
 
1495                         RoleInAppForUser ecompRole = new RoleInAppForUser();
 
1496                         existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
 
1497                         if (existingAppRole == null) {
 
1498                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
 
1499                                                 roleInAppForUserList);
 
1500                                 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
 
1502                         if (!existingAppRole.getActive()) {
 
1503                                 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
 
1504                                                 roleInAppForUserList);
 
1505                                 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
 
1507                                 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
 
1508                                 ecompRole.roleName = roleInAppForUser.getRoleName();
 
1509                                 ecompRole.isApplied = true;
 
1510                                 existingUserRoles.add(ecompRole);
 
1513                 return existingUserRoles;
 
1522          * @param applicationsRestClientService
 
1524          * @throws HTTPException
 
1526         protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
 
1527                         throws HTTPException {
 
1529                 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
 
1530                         // Map<String,String> params = new HashMap<String,String>();
 
1531                         // params.put("sbcid",userId);
 
1532                         @SuppressWarnings("unchecked")
 
1533                         List<EPUser> userList = (List<EPUser>) dataAccessService
 
1534                                         .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
 
1535                         if (userList != null && !userList.isEmpty())
 
1536                                 return userList.get(0);
 
1542                 return getUser(userId, app, applicationsRestClientService);
 
1545         protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
 
1546                         throws HTTPException {
 
1547                 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
 
1551         protected boolean isAppUpgradeVersion(EPApp app){
 
1556         public ExternalSystemAccess getExternalRequestAccess(){
 
1557                 ExternalSystemAccess res = null; 
 
1559                         res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
 
1560                                         Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
 
1561                 } catch (Exception e) {
 
1562                         logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
 
1570          * @see org.onap.portalapp.portal.service.UserRolesService#
 
1571          * getAppRolesForUser(java.lang.Long, java.lang.String)
 
1573         @SuppressWarnings("unchecked")
 
1574         public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) {
 
1576                 List<RoleInAppForUser> rolesInAppForUser = null;
 
1577                 EPApp app = appsService.getApp(appId);
 
1579                         // for onap portal app, no need to make a remote call
 
1580                         List<Role> roleList = new ArrayList<>();
 
1581                         if (appId == PortalConstants.PORTAL_APP_ID) {           
 
1582                                 if(app.getCentralAuth()){
 
1583                                         List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
 
1584                                         for(CentralV2Role cenRole : cenRoleList){
 
1585                                                 Role role = new Role();
 
1586                                                 role.setActive(cenRole.getActive());
 
1587                                                 role.setId(cenRole.getId());
 
1588                                                 role.setName(cenRole.getName());
 
1589                                                 role.setPriority(cenRole.getPriority());
 
1593                                         roleList = roleService.getAvailableRoles(userId);
 
1595                                 List<Role> activeRoleList = new ArrayList<Role>();
 
1596                                 for(Role role: roleList) {
 
1597                                         if(role.getActive()) {
 
1598                                                 if(role.getId() != 1){ // prevent portal admin from being added
 
1599                                                         activeRoleList.add(role);
 
1600                                                 } else if(extRequestValue){
 
1601                                                         activeRoleList.add(role);
 
1606                                 EPUser localUser  = getUserFromApp(userId, app, applicationsRestClientService);
 
1607                                 // If localUser does not exists return roles
 
1608                                 Set<EPRole> roleSet = null;
 
1609                                 EPRole[] roleSetList = null;
 
1610                                 if(localUser != null){
 
1611                                         roleSet = localUser.getAppEPRoles(app);
 
1612                                         roleSetList = roleSet.toArray(new EPRole[0]);
 
1614                                 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
 
1615                                 return rolesInAppForUser;
 
1618                         EcompRole[] appRoles = null;
 
1619                         List<EcompRole> roles = new ArrayList<>();
 
1620                         if(app.getCentralAuth()){
 
1621                                 final Map<String, Long> appParams =  new HashMap<>();
 
1622                                 appParams.put("appId", app.getId());
 
1623                                 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null);
 
1624                                 for(EPRole role : applicationRoles){
 
1625                                         EcompRole ecompRole = new EcompRole();
 
1626                                         ecompRole.setId(role.getId());
 
1627                                         ecompRole.setName(role.getName());
 
1628                                         roles.add(ecompRole);
 
1630                                 appRoles = roles.toArray(new EcompRole[roles.size()]);
 
1632                                 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
 
1634                         // Test this error case, for generating an internal ONAP Portal
 
1636                         // EcompRole[] appRoles = null;
 
1637                         // If there is an exception in the rest client api, then null will
 
1639                         if (appRoles != null) {
 
1640                                 if(!app.getCentralAuth()) {
 
1641                                 syncAppRoles(sessionFactory, appId, appRoles);
 
1643                                 EcompRole[] userAppRoles = null;
 
1646                                                 if(app.getCentralAuth()){
 
1647                                                         final Map<String, String> params = new HashMap<>();
 
1648                                                         final Map<String, Long> userParams = new HashMap<>();
 
1649                                                         params.put("orgUserIdValue", userId);
 
1650                                                         List<EPUser> user = dataAccessService.executeNamedQuery("epUserAppId", params, null);
 
1651                                                         userParams.put("appId", app.getId());
 
1652                                                         userParams.put("userId", user.get(0).getId());  
 
1653                                                         List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
 
1654                                                                 List<EcompRole> setUserRoles = new ArrayList<>();
 
1655                                                                 for(EPUserAppCurrentRoles role : userAppsRolesList){
 
1656                                                                         EcompRole ecompRole = new EcompRole();
 
1657                                                                         ecompRole.setId(role.getRoleId());
 
1658                                                                         ecompRole.setName(role.getRoleName());
 
1659                                                                         setUserRoles.add(ecompRole);
 
1661                                                                 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
 
1662                                                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
 
1663                                                                 return rolesInAppForUser;
 
1665                                                         userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
 
1666                                                                         String.format("/user/%s/roles", userId));
 
1668                                         } catch (HTTPException e) {
 
1669                                                 // Some apps are returning 400 if user is not found.
 
1670                                                 if (e.getResponseCode() == 400) {
 
1671                                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1672                                                                         "getAppRolesForUser caught exception with response code 400; continuing", e);
 
1674                                                         // Other response code, let it come thru.
 
1678                                         if (userAppRoles == null) {
 
1679                                                 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
 
1680                                                         EcompPortalUtils.setExternalAppResponseCode(200);
 
1681                                                         String message = String.format(
 
1682                                                                         "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
 
1683                                                                                         + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
 
1684                                                                                         + "Overriding to 200 until framework SDK returns a useful response.",
 
1685                                                                         Long.toString(appId), userId);
 
1686                                                         logger.warn(EELFLoggerDelegate.applicationLogger, message);
 
1690                                          HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
 
1691                                                 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
 
1692                                                 if(userAppRoles != null){
 
1693                                                         for (int i = 0; i < userAppRoles.length; i++) {
 
1694                                                                 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
 
1695                                                                         EcompRole role = new EcompRole();
 
1696                                                                         role.setId(userAppRoles[i].getId());
 
1697                                                                         role.setName(userAppRoles[i].getName());
 
1698                                                                         activeRoles.add(role);
 
1702                                                 EcompRole[]     userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
 
1704                                         // If the remote application isn't down we MUST sync user
 
1705                                         // roles here in case we have this user here!
 
1706                                         syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
 
1707                                 } catch (Exception e) {
 
1708                                         // TODO: we may need to check if user exists, maybe remote
 
1710                                         String message = String.format(
 
1711                                                         "getAppRolesForUser: user %s does not exist in remote application %s", userId,
 
1712                                                         Long.toString(appId));
 
1713                                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1714                                         userAppRoles = new EcompRole[0];
 
1716                                 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
 
1718                 } catch (Exception e) {
 
1719                         String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
 
1720                                         Long.toString(appId));
 
1721                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
 
1723                 return rolesInAppForUser;
 
1727         private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
 
1728                         ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
 
1729                         throws JsonProcessingException, HTTPException {
 
1730                 boolean result = false;
 
1731                 ObjectMapper mapper = new ObjectMapper();
 
1732                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1733                 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
 
1734                 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
 
1735                 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
 
1739         @SuppressWarnings("unchecked")
 
1740         public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
 
1741                 FieldsValidator fieldsValidator = new FieldsValidator();
 
1742                 final Map<String, Long> params = new HashMap<>();
 
1743                 List<EPUserAppRoles>  appRole= null;
 
1745                         logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
 
1746                         boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
 
1747                         logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
 
1749                         params.put("appId", userAppRolesData.appId);
 
1750                         EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
 
1751                         epAppRolesRequestData.setCreatedDate(new Date());
 
1752                         epAppRolesRequestData.setUpdatedDate(new Date());
 
1753                         epAppRolesRequestData.setUserId(user.getId());
 
1754                         epAppRolesRequestData.setAppId(userAppRolesData.appId);
 
1755                         epAppRolesRequestData.setRequestStatus("P");
 
1756                         List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
 
1757                         Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
 
1758                         dataAccessService.saveDomainObject(epAppRolesRequestData, null);
 
1759                         for (RoleInAppForUser userAppRoles : appRoleIdList) {
 
1760                                 Boolean isAppliedVal = userAppRoles.isApplied;
 
1761                                 params.put("appRoleId", userAppRoles.roleId);                           
 
1763                                         appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
 
1764                                         if (!appRole.isEmpty()) {
 
1765                                                 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
 
1766                                                 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
 
1767                                                 epAppRoleDetail.setReqType("P");
 
1768                                                 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
 
1769                                                 dataAccessService.saveDomainObject(epAppRoleDetail, null);
 
1773                         epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
 
1774                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
 
1776                 } catch (Exception e) {
 
1777                         logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
 
1778                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
 
1780                 return fieldsValidator;
 
1783         public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {      
 
1784                 Map<String, String> params = new HashMap<>();
 
1785                 params.put("userid", userid.getId().toString());
 
1786                 //params.put("appid", appid);
 
1787                 params.put("appName", appName);
 
1789                 @SuppressWarnings("unchecked")
 
1790                 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
 
1791                                 .executeNamedQuery("userAppCatalogRoles", params, null);
 
1792                 return userAppRoles;    
 
1795         public String updateRemoteUserProfile(String orgUserId, Long appId) {
 
1796                 ObjectMapper mapper = new ObjectMapper();
 
1797                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
1798                 EPUser client = searchService.searchUserByUserId(orgUserId);
 
1799                 EPUser newUser = new EPUser();
 
1800                 newUser.setActive(client.getActive());
 
1801                 newUser.setFirstName(client.getFirstName());
 
1802                 newUser.setLastName(client.getLastName());
 
1803                 newUser.setLoginId(client.getLoginId());
 
1804                 newUser.setLoginPwd(client.getLoginPwd());
 
1805                 newUser.setMiddleInitial(client.getMiddleInitial());
 
1806                 newUser.setEmail(client.getEmail());
 
1807                 newUser.setOrgUserId(client.getLoginId());
 
1809                         String userAsString = mapper.writeValueAsString(newUser);
 
1810                         List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
 
1811                         // applicationsRestClientService.post(EPUser.class, appId,
 
1812                         // userAsString, String.format("/user", orgUserId));
 
1813                         for (EPApp eachApp : appList) {
 
1815                                         applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
 
1816                                                         String.format("/user/%s", orgUserId));
 
1817                                 } catch (Exception e) {
 
1818                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
 
1819                                                         + " in remote app. appId = " + eachApp.getId());
 
1822                 } catch (Exception e) {
 
1823                         logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
 
1834          * @see org.onap.portalapp.portal.service.UserRolesService#
 
1835          * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
 
1837         @SuppressWarnings("deprecation")
 
1838         public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
 
1839                 // Find the records for this user-app combo, if any
 
1840                 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
 
1841                 @SuppressWarnings("unchecked")
 
1842                 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
 
1843                 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
 
1848          * It retrieves and returns list of user app roles for local and remote applications based app id
 
1851          * @return list of user app roles
 
1852          * @throws HTTPException 
 
1854         public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
 
1855                 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
 
1857                 EPApp app = appsService.getApp(appId);
 
1858                 //If local or centralized application
 
1859                 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
 
1860                         @SuppressWarnings("unchecked")
 
1861                         List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
 
1862                         for (EPUser user : userList) {
 
1863                                 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
 
1864                                 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
 
1865                                         userApplicationRoles.add(userWithAppRoles);
 
1871                         RemoteUserWithRoles[] remoteUsers = null;
 
1872                         String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
 
1874                         remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
 
1876                         userApplicationRoles = new ArrayList<UserApplicationRoles>();
 
1877                         for (RemoteUserWithRoles remoteUser : remoteUsers) {
 
1878                                 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
 
1879                                 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
 
1880                                         userApplicationRoles.add(userWithRemoteAppRoles);
 
1882                                         logger.debug(EELFLoggerDelegate.debugLogger,
 
1883                                                         "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
 
1888                 return userApplicationRoles;
 
1895          * @param appgetUsersFromAppEndpoint
 
1898         private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
 
1899                 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
 
1900                 userWithRemoteAppRoles.setAppId(appId);
 
1901                 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
 
1902                 userWithRemoteAppRoles.setFirstName(user.getFirstName());
 
1903                 userWithRemoteAppRoles.setLastName(user.getLastName());
 
1904                 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
 
1905                 return userWithRemoteAppRoles;
 
1914         private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
 
1915                 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
 
1916                 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
 
1917                 for (EPRole role : roleSet) {
 
1918                         RemoteRole rRole = new RemoteRole();
 
1919                         rRole.setId(role.getId());
 
1920                         rRole.setName(role.getName());
 
1921                         roleList.add(rRole);
 
1926         public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
 
1928                 ObjectMapper mapper = new ObjectMapper();
 
1930                         return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
 
1931                 } catch (IOException e) {
 
1932                         logger.error(EELFLoggerDelegate.errorLogger,
 
1933                                         "doGetUsers : Failed : Unexpected property in incoming JSON",
 
1935                         logger.error(EELFLoggerDelegate.errorLogger,
 
1936                                         "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
 
1939                 return new RemoteUserWithRoles[0];
 
1942         @SuppressWarnings("unchecked")
 
1943         public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
 
1944                 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
 
1945                 final Map<String, Long> params = new HashMap<>();
 
1946                 params.put("appId", appId);
 
1947                 params.put("userId", userId);
 
1948                 params.put("roleId", roleId);
 
1949                 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
 
1950                 return userRoleList;