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.CentralV2RoleFunction;
69 import org.onap.portalapp.portal.domain.EPApp;
70 import org.onap.portalapp.portal.domain.EPRole;
71 import org.onap.portalapp.portal.domain.EPUser;
72 import org.onap.portalapp.portal.domain.EPUserApp;
73 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
74 import org.onap.portalapp.portal.domain.EPUserAppRoles;
75 import org.onap.portalapp.portal.domain.EPUserAppRolesRequest;
76 import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail;
77 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
78 import org.onap.portalapp.portal.exceptions.SyncUserRolesException;
79 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
80 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
81 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
82 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
83 import org.onap.portalapp.portal.transport.CentralV2Role;
84 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
85 import org.onap.portalapp.portal.transport.EcompUserAppRoles;
86 import org.onap.portalapp.portal.transport.ExternalAccessUser;
87 import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
89 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
90 import org.onap.portalapp.portal.transport.FieldsValidator;
91 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
92 import org.onap.portalapp.portal.transport.FunctionalMenuRole;
93 import org.onap.portalapp.portal.transport.RemoteRole;
94 import org.onap.portalapp.portal.transport.RemoteRoleV1;
95 import org.onap.portalapp.portal.transport.RemoteUserWithRoles;
96 import org.onap.portalapp.portal.transport.RoleInAppForUser;
97 import org.onap.portalapp.portal.transport.RolesInAppForUser;
98 import org.onap.portalapp.portal.transport.UserApplicationRoles;
99 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
100 import org.onap.portalapp.portal.utils.EcompPortalUtils;
101 import org.onap.portalapp.portal.utils.PortalConstants;
102 import org.onap.portalapp.util.EPUserUtils;
103 import org.onap.portalapp.util.SystemType;
104 import org.onap.portalsdk.core.domain.Role;
105 import org.onap.portalsdk.core.domain.RoleFunction;
106 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
107 import org.onap.portalsdk.core.restful.domain.EcompRole;
108 import org.onap.portalsdk.core.service.DataAccessService;
109 import org.onap.portalsdk.core.service.RoleService;
110 import org.onap.portalsdk.core.util.SystemProperties;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.springframework.http.HttpEntity;
113 import org.springframework.http.HttpHeaders;
114 import org.springframework.http.HttpMethod;
115 import org.springframework.http.HttpStatus;
116 import org.springframework.http.ResponseEntity;
117 import org.springframework.web.client.RestTemplate;
119 import com.fasterxml.jackson.core.JsonProcessingException;
120 import com.fasterxml.jackson.databind.DeserializationFeature;
121 import com.fasterxml.jackson.databind.ObjectMapper;
124 public class UserRolesCommonServiceImpl {
126 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class);
128 private static final Object syncRests = new Object();
130 private static final String APP_ID = "appId";
133 private DataAccessService dataAccessService;
135 private SessionFactory sessionFactory;
137 private SearchService searchService;
139 private EPAppService appsService;
141 private ApplicationsRestClientService applicationsRestClientService;
143 private EPRoleService epRoleService;
145 private RoleService roleService;
147 private AdminRolesService adminRolesService;
149 private EPAppService appService;
151 private ExternalAccessRolesService externalAccessRolesService;
154 private AppsCacheService appsCacheService;
156 RestTemplate template = new RestTemplate();
161 * @return HashMap<Long, EcompRole>
163 private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
164 HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
165 if (ecompRoles != null) {
166 for (int i = 0; i < ecompRoles.length; i++) {
167 if (ecompRoles[i].getId() != null) {
168 result.put(ecompRoles[i].getId(), ecompRoles[i]);
179 protected void createLocalUserIfNecessary(String userId) {
180 if (StringUtils.isEmpty(userId)) {
181 logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
184 Session localSession = null;
185 Transaction transaction = null;
187 localSession = sessionFactory.openSession();
188 transaction = localSession.beginTransaction();
189 @SuppressWarnings("unchecked")
190 List<EPUser> userList = localSession
191 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
192 if (userList.size() == 0) {
193 EPUser client = searchService.searchUserByUserId(userId);
194 if (client == null) {
195 String msg = "createLocalUserIfNecessary: cannot create user " + userId
196 + ", because not found in phonebook";
197 logger.error(EELFLoggerDelegate.errorLogger, msg);
199 client.setLoginId(userId);
200 client.setActive(true);
201 localSession.save(client);
204 transaction.commit();
205 } catch (Exception e) {
206 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
207 EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
209 EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
214 * This method return nothing and remove roles before adding any roles for an app
217 * @param localSession
218 * @param userAppRoles
219 * @param newUserAppRolesMap
221 private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) {
223 Long userAppRoleId = 0L;
224 if (appId == PortalConstants.PORTAL_APP_ID) { // local app
225 userAppRoleId = userRole.getRoleId();
226 } else { // remote app
227 userAppRoleId = userRole.getAppRoleId();
230 if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
231 localSession.delete(userRole);
233 newUserAppRolesMap.remove(userAppRoleId);
238 * Checks whether the role is inactive
242 * if role is inactive, throws exception
244 private void checkIfRoleInactive(EPRole epRole) throws Exception{
245 if(!epRole.getActive()){
246 throw new Exception(epRole.getName()+ " role is unavailable");
252 * @param sessionFactory
255 * @param userAppRoles
256 * @param extRequestValue
257 * set to false if request is from users page otherwise true
260 protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId,
261 EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception {
262 Session localSession = null;
263 Transaction transaction = null;
264 String roleActive = null;
265 final Map<String, String> userAppParams = new HashMap<>();
266 final Map<String, String> appParams = new HashMap<>();
267 HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
270 localSession = sessionFactory.openSession();
271 transaction = localSession.beginTransaction();
272 @SuppressWarnings("unchecked")
273 List<EPUser> userList = localSession
274 .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list();
275 if (userList.size() > 0) {
276 EPUser client = userList.get(0);
277 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
278 @SuppressWarnings("unchecked")
279 List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName()
280 + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list();
282 if ("DELETE".equals(reqType)) {
283 for (EPUserApp userAppRoleList : userRoles) {
284 userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName()));
285 userAppParams.put("appId", String.valueOf(appId));
286 appParams.put("appRoleName", userAppRoleList.getRole().getName());
287 @SuppressWarnings("unchecked")
288 List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null);
289 if(rolesList.size() > 0 || !rolesList.isEmpty()){
290 checkIfRoleInactive(rolesList.get(0));
295 for (EPUserApp userRole : userRoles) {
296 if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){
297 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
299 else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType) || "DELETE".equals(reqType))){
300 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
302 else if (extRequestValue && !userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)){
303 syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap);
306 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
307 if (newRolesToAdd.size() > 0) {
308 EPApp app = (EPApp) localSession.get(EPApp.class, appId);
310 HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
311 if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
312 String appIdValue = "";
313 if(!extRequestValue){
314 appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
316 @SuppressWarnings("unchecked")
317 List<EPRole> roles = localSession
318 .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list();
319 for (EPRole role : roles) {
321 rolesMap.put(role.getId(), role);
323 } else { // remote app
324 @SuppressWarnings("unchecked")
325 List<EPRole> roles = localSession
326 .createQuery("from :name where appId=:appId")
327 .setParameter("name",EPRole.class.getName())
328 .setParameter("appId",appId)
330 for (EPRole role : roles) {
331 if (!extRequestValue && app.getCentralAuth()) {
332 rolesMap.put(role.getId(), role);
334 rolesMap.put(role.getAppRoleId(), role);
340 for (EcompRole userRole : newRolesToAdd) {
341 EPUserApp userApp = new EPUserApp();
342 if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) {
343 role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
344 userApp.setRole(role);
345 } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){
347 }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){
351 userApp.setRole(rolesMap.get(userRole.getId()));
354 userApp.setUserId(client.getId());
356 localSession.save(userApp);
357 localSession.flush();
360 if (appId == PortalConstants.PORTAL_APP_ID) {
362 * for local app -- hack - always make sure fn_role
363 * table's app_id is null and not 1 for primary app in
364 * this case being onap portal app; reason: hibernate
365 * is rightly setting this to 1 while persisting to
366 * fn_role as per the mapping but SDK role management
367 * code expects the app_id to be null as there is no
368 * concept of App_id in SDK
370 localSession.flush();
371 SQLQuery sqlQuery = localSession
372 .createSQLQuery("update fn_role set app_id = null where app_id = 1 ");
373 sqlQuery.executeUpdate();
378 transaction.commit();
379 } catch (Exception e) {
380 logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
381 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
382 EcompPortalUtils.rollbackTransaction(transaction,
383 "Exception occurred in syncUserRoles, Details: " + e.toString());
384 if("DELETE".equals(reqType)){
385 throw new SyncUserRolesException(e.getMessage());
388 if(localSession != null)
389 localSession.close();
394 * Called when getting the list of roles for the user
397 * @param userAppRoles
398 * @return List<RoleInAppForUser>
400 protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
401 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
403 Set<Long> userAppRolesMap = new HashSet<Long>();
404 if (userAppRoles != null) {
405 for (EcompRole ecompRole : userAppRoles) {
406 userAppRolesMap.add(ecompRole.getId());
409 logger.error(EELFLoggerDelegate.errorLogger,
410 "constructRolesInAppForUserGet has received userAppRoles list empty");
413 if (appRoles != null) {
414 for (EcompRole ecompRole : appRoles) {
415 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
416 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
417 rolesInAppForUser.add(roleForUser);
420 logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty");
422 return rolesInAppForUser;
426 * Called when getting the list of roles for the user
429 * @param userAppRoles
430 * @param extRequestValue
431 * set to false if request is from users page otherwise true
432 * @return List<RoleInAppForUser>
434 protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) {
435 List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
437 Set<Long> userAppRolesMap = new HashSet<Long>();
438 if (userAppRoles != null) {
439 for (EPRole ecompRole : userAppRoles) {
440 userAppRolesMap.add(ecompRole.getId());
442 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - userAppRolesMap = {}", userAppRolesMap);
445 logger.error(EELFLoggerDelegate.errorLogger,
446 "constructRolesInAppForUserGet has received userAppRoles list empty.");
449 if (appRoles != null) {
451 for (Role ecompRole : appRoles) {
452 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - appRoles not null = {}", ecompRole);
454 if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue)
456 RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
457 roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
458 rolesInAppForUser.add(roleForUser);
459 logger.debug(EELFLoggerDelegate.debugLogger, "In constructRolesInAppForUserGet() - rolesInAppForUser = {}", rolesInAppForUser);
463 logger.error(EELFLoggerDelegate.errorLogger,
464 "constructRolesInAppForUser has received appRoles list empty.");
466 return rolesInAppForUser;
471 * copies of methods in GetAppsWithUserRoleState
473 * @param sessionFactory
478 protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
479 logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
480 HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
481 Session localSession = null;
482 Transaction transaction = null;
485 localSession = sessionFactory.openSession();
486 transaction = localSession.beginTransaction();
487 // Attention! All roles from remote application supposed to be
489 @SuppressWarnings("unchecked")
490 List<EPRole> currentAppRoles = localSession
491 .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
492 List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
493 for (int i = 0; i < currentAppRoles.size(); i++) {
494 EPRole oldAppRole = currentAppRoles.get(i);
495 if (oldAppRole.getAppRoleId() != null) {
496 EcompRole role = null;
497 role = newRolesMap.get(oldAppRole.getAppRoleId());
499 if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
500 oldAppRole.setName(role.getName());
501 localSession.update(oldAppRole);
503 oldAppRole.setActive(true);
504 newRolesMap.remove(oldAppRole.getAppRoleId());
506 obsoleteRoles.add(oldAppRole);
509 obsoleteRoles.add(oldAppRole);
512 Collection<EcompRole> newRolesToAdd = newRolesMap.values();
513 if (obsoleteRoles.size() > 0) {
514 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
515 for (EPRole role : obsoleteRoles) {
516 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
517 Long roleId = role.getId();
518 // delete obsolete roles here
519 // Must delete all records with foreign key constraints on
521 // fn_user_role, fn_role_composite, fn_role_function,
522 // fn_user_pseudo_role, fn_menu_functional_roles.
523 // And for fn_menu_functional, if no other roles for that
524 // menu item, remove the url.
526 // Delete from fn_user_role
527 @SuppressWarnings("unchecked")
528 List<EPUserApp> userRoles = localSession.createQuery(
529 "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId)
532 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: number of userRoles to delete: " + userRoles.size());
533 for (EPUserApp userRole : userRoles) {
534 logger.debug(EELFLoggerDelegate.debugLogger,
535 "syncAppRoles: about to delete userRole: " + userRole.toString());
536 localSession.delete(userRole);
537 logger.debug(EELFLoggerDelegate.debugLogger,
538 "syncAppRoles: finished deleting userRole: " + userRole.toString());
541 // Delete from fn_menu_functional_roles
542 @SuppressWarnings("unchecked")
543 List<FunctionalMenuRole> funcMenuRoles = localSession
544 .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId)
546 int numMenuRoles = funcMenuRoles.size();
547 logger.debug(EELFLoggerDelegate.debugLogger,
548 "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
549 for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
550 Long menuId = funcMenuRole.menuId;
551 // If this is the only role for this menu item, then the
552 // app and roles will be gone,
553 // so must null out the url too, to be consistent
554 @SuppressWarnings("unchecked")
555 List<FunctionalMenuRole> funcMenuRoles2 = localSession
556 .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId)
558 int numMenuRoles2 = funcMenuRoles2.size();
559 logger.debug(EELFLoggerDelegate.debugLogger,
560 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
561 localSession.delete(funcMenuRole);
562 if (numMenuRoles2 == 1) {
563 // If this is the only role for this menu item, then
564 // the app and roles will be gone,
565 // so must null out the url too, to be consistent
566 logger.debug(EELFLoggerDelegate.debugLogger,
567 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
568 @SuppressWarnings("unchecked")
569 List<FunctionalMenuItem> funcMenuItems = localSession
571 "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId)
573 if (funcMenuItems.size() > 0) {
574 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
575 FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
576 funcMenuItem.url = "";
577 localSession.update(funcMenuItem);
581 boolean isPortalRequest = true;
582 externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId, isPortalRequest);
583 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
584 localSession.delete(role);
585 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
588 for (EcompRole role : newRolesToAdd) {
589 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
590 EPRole newRole = new EPRole();
591 // Attention! All roles from remote application supposed to be
593 newRole.setActive(true);
594 newRole.setName(role.getName());
595 newRole.setAppId(appId);
596 newRole.setAppRoleId(role.getId());
597 localSession.save(newRole);
599 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
600 transaction.commit();
601 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
602 } catch (Exception e) {
603 logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
604 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
605 EcompPortalUtils.rollbackTransaction(transaction,
606 "Exception occurred in syncAppRoles, Details: " + e.toString());
607 throw new Exception(e);
609 localSession.close();
618 * Called when updating the list of roles for the user
622 * @param userRolesInRemoteApp
623 * @return RolesInAppForUser
625 protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
626 Set<EcompRole> userRolesInRemoteApp) {
627 RolesInAppForUser result;
628 result = new RolesInAppForUser();
629 result.appId = appId;
630 result.orgUserId = userId;
631 for (EcompRole role : userRolesInRemoteApp) {
632 RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
633 roleInAppForUser.roleId = role.getId();
634 roleInAppForUser.roleName = role.getName();
635 roleInAppForUser.isApplied = new Boolean(true);
636 result.roles.add(roleInAppForUser);
643 * @param roleInAppForUserList
646 protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
647 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
648 if (roleInAppForUser.isApplied.booleanValue()) {
656 * Builds JSON and posts it to a remote application to update user roles.
658 * @param roleInAppForUserList
660 * @param applicationsRestClientService
663 * @return Set of roles as sent; NOT the response from the app.
664 * @throws JsonProcessingException
665 * @throws HTTPException
667 protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
668 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
669 throws JsonProcessingException, HTTPException {
670 Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
671 Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
672 String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
673 EPApp externalApp = null;
674 SystemType type = SystemType.APPLICATION;
675 externalApp = appsCacheService.getApp(appId);
676 String appBaseUri = null;
677 Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
678 if (externalApp != null) {
679 appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
681 if(appBaseUri != null && appBaseUri.endsWith("/api")){
682 for(EcompRole eprole :updatedUserRolesinRemote)
684 RemoteRoleV1 role = new RemoteRoleV1();
685 role.setId(eprole.getId());
686 role.setName(eprole.getName());
687 updatedUserRolesinRemoteV1.add(role);
689 userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
691 applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
692 String.format("/user/%s/roles", userId));
693 // TODO: We should add code that verifies that the post operation did
694 // succeed. Because the SDK may still return 200 OK with an html page
695 // even when it fails!
696 return updateUserRolesInEcomp;
701 * @param roleInAppForUserList
702 * @return Set<EcompRole>
704 protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
705 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
706 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
707 if (roleInAppForUser.isApplied) {
708 EcompRole ecompRole = new EcompRole();
709 ecompRole.setId(roleInAppForUser.roleId);
710 ecompRole.setName(roleInAppForUser.roleName);
711 existingUserRoles.add(ecompRole);
714 return existingUserRoles;
718 * Constructs user app roles excluding Account Administrator role
720 * @param roleInAppForUserList
722 * List of roles with Role name, Role Id
724 protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
725 Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
726 for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
727 if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
728 EcompRole ecompRole = new EcompRole();
729 ecompRole.setId(roleInAppForUser.roleId);
730 ecompRole.setName(roleInAppForUser.roleName);
731 existingUserRoles.add(ecompRole);
734 return existingUserRoles;
738 * This is for a single app
740 * @param rolesInAppForUser
741 * @param externalSystemRequest
742 * set to false if requests from Users page otherwise true
743 * @return true on success, false otherwise
745 protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception {
746 boolean result = false;
747 String userId = rolesInAppForUser.orgUserId;
748 Long appId = rolesInAppForUser.appId;
749 synchronized (syncRests) {
750 if (rolesInAppForUser != null) {
751 createLocalUserIfNecessary(userId);
754 if (rolesInAppForUser != null) {
755 EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()];
756 for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) {
757 RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
758 EcompRole role = new EcompRole();
759 role.setId(roleInAppForUser.roleId);
760 role.setName(roleInAppForUser.roleName);
761 userAppRoles[i] = role;
764 syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType);
766 } catch (Exception e) {
767 logger.error(EELFLoggerDelegate.errorLogger,
768 "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId " + userId, e);
769 if("DELETE".equals(reqType)){
770 throw new Exception(e.getMessage());
782 * @return UserApplicationRoles
784 protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
785 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
786 userWithRemoteAppRoles.setAppId(appId);
787 userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId());
788 userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName());
789 userWithRemoteAppRoles.setLastName(remoteUser.getLastName());
790 userWithRemoteAppRoles.setRoles(remoteUser.getRoles());
791 return userWithRemoteAppRoles;
797 * @see org.onap.portalapp.portal.service.UserRolesService#
798 * importRolesFromRemoteApplication(java.lang.Long)
800 public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
801 EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
802 List<EPRole> rolesList = Arrays.asList(appRolesFull);
803 for (EPRole externalAppRole : rolesList) {
805 // Try to find an existing extern role for the app in the local
806 // onap DB. If so, then use its id to update the existing external
807 // application role record.
808 Long externAppId = externalAppRole.getId();
809 EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
810 if (existingAppRole != null) {
811 logger.debug(EELFLoggerDelegate.debugLogger,
812 String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.",
813 appId, externAppId));
816 // persistExternalRoleInEcompDb(externalAppRole, appId,
824 * It adds new user for remote application
826 * @param roleInAppForUserList
827 * @param remoteAppUser
831 * @param searchService
832 * @param applicationsRestClientService
836 private EPUser addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
837 ObjectMapper mapper, SearchService searchService,
838 ApplicationsRestClientService applicationsRestClientService) throws Exception {
839 EPUser addRemoteUser = null;
840 if (remoteUserShouldBeCreated(roleInAppForUserList)) {
841 createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
842 isAppUpgradeVersion(app));
844 return addRemoteUser;
847 private EPUser pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, EPApp app,
848 ObjectMapper mapper, SearchService searchService,
849 ApplicationsRestClientService applicationsRestClientService,boolean appRoleIdUsed) throws Exception {
850 EPUser addRemoteUser = null;
851 // if (remoteUserShouldBeCreated(roleInAppForUserList)) {
852 pushUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper,
853 isAppUpgradeVersion(app), roleInAppForUserList, appRoleIdUsed);
855 return addRemoteUser;
858 protected void pushUserOnRemoteApp(String userId, EPApp app,
859 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
860 ObjectMapper mapper, boolean postOpenSource, List<RoleInAppForUser> roleInAppForUserList,boolean appRoleIdUsed) throws Exception {
862 EPUser client = searchService.searchUserByUserId(userId);
864 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
866 if (client == null) {
867 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
868 logger.error(EELFLoggerDelegate.errorLogger, msg);
869 throw new Exception(msg);
872 client.setLoginId(userId);
873 client.setActive(true);
874 roleInAppForUserList.removeIf(role -> role.isApplied.equals(false));
875 SortedSet<Role> roles = new TreeSet<>();
877 List<EPRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
878 List<EPApp> appList = new ArrayList<>();
880 List<CentralV2Role> roleList = new ArrayList<>();
881 Map<String, Long> params = new HashMap<>();
883 List<EPRole> userRoles = new ArrayList<>();
885 for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
886 EPRole role = new EPRole();
887 role.setId(roleInappForUser.getRoleId());
888 role.setName(roleInappForUser.getRoleName());
893 List<EPRole> userAppRoles = new ArrayList<>();
894 for (EPRole role : userRoles) {
895 EPRole appRole = getAppRoles.stream()
896 .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
898 EPRole epRole = new EPRole();
899 if (appRole != null) {
900 epRole.setId(appRole.getId());
901 epRole.setName(appRole.getName());
903 userAppRoles.add(epRole);
905 userRoles = new ArrayList<>();
906 userRoles.addAll(userAppRoles);
908 roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList, params);
910 for (CentralV2Role epRole : roleList) {
911 Role role = new Role();
912 EPRole appRole = getAppRoles.stream()
913 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
914 if (appRole != null){
915 role.setId(appRole.getAppRoleId());
916 role.setName(epRole.getName());
917 role.setRoleFunctions(epRole.getRoleFunctions());
921 client.setRoles(roles);
922 String userInString = null;
923 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
924 logger.debug(EELFLoggerDelegate.debugLogger,
925 "about to post a client to remote application, users json = " + userInString);
926 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user/%s", userId));
930 * It checks whether the remote user exists or not
931 * if exits returns user object else null
935 * @param applicationsRestClientService
937 * @throws HTTPException
939 private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{
940 EPUser checkRemoteUser = null;
942 checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
943 } catch (HTTPException e) {
944 // Some apps are returning 400 if user is not found.
945 if (e.getResponseCode() == 400) {
946 logger.debug(EELFLoggerDelegate.debugLogger,
947 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
949 } else if(e.getResponseCode() == 404) {
950 logger.debug(EELFLoggerDelegate.debugLogger,
951 "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
954 // Other response code, let it come thru.
958 return checkRemoteUser;
965 * @see org.onap.portalapp.portal.service.UserRolesService#
966 * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain.
967 * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser)
969 public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
970 boolean result = false;
971 boolean epRequestValue = false;
973 String reqMessage = "";
974 if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
975 userId = newAppRolesForUser.orgUserId.trim();
977 Long appId = newAppRolesForUser.appId;
978 List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
979 if (userId.length() > 0) {
980 ObjectMapper mapper = new ObjectMapper();
981 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
984 EPApp app = appsService.getApp(appId);
985 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
987 // if centralized app
988 if (app.getCentralAuth()) {
989 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
990 pushRemoteUser(roleInAppForUserList, userId, app, mapper, searchService,
991 applicationsRestClientService,false);
994 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
995 applicationsRestClientService, appId, userId);
996 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
997 userRolesInLocalApp);
998 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
999 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1000 // Apply changes in external Access system
1001 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList,
1004 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
1006 // In case if portal is not centralized then follow existing approach
1007 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1008 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1009 applicationsRestClientService, appId, userId);
1010 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1011 userRolesInLocalApp);
1012 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal");
1013 } else{// remote app
1014 EPUser remoteAppUser = null;
1015 if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1017 remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService);
1019 if (remoteAppUser == null) {
1020 remoteAppUser = addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService);
1022 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1023 applicationsRestClientService, appId, userId);
1024 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
1025 userRolesInRemoteApp);
1026 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null);
1028 // If no roles remain, request app to set user inactive.
1029 if (userRolesInRemoteApp.size() == 0) {
1030 logger.debug(EELFLoggerDelegate.debugLogger,
1031 "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app,
1033 //remoteAppUser.setActive(false);
1034 postUserToRemoteApp(userId, user, app, applicationsRestClientService);
1038 } catch (Exception e) {
1039 /*String message = String.format(
1040 "Failed to create user or update user roles for User %s, AppId %s",
1041 userId, Long.toString(appId));
1042 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1045 String message = String.format(
1046 "Failed to create user or update user roles for User %s, AppId %s",
1047 userId, Long.toString(appId));
1048 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1050 reqMessage = e.getMessage();
1057 return new ExternalRequestFieldsValidator(result, reqMessage);
1061 * It adds user roles in External system and also make data consistent in both local and in External System
1063 * @param app details
1065 * @param roleInAppUser Contains list of active roles
1067 @SuppressWarnings("unchecked")
1068 private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser, boolean isPortalRequest) throws Exception
1071 // check if user exists
1072 final Map<String, String> userParams = new HashMap<>();
1073 userParams.put("orgUserIdValue", orgUserId);
1074 List<EPUser> userInfo = checkIfUserExists(userParams);
1075 if (userInfo.isEmpty()) {
1076 createLocalUserIfNecessary(orgUserId);
1079 if (EPCommonSystemProperties
1080 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1082 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1084 ObjectMapper mapper = new ObjectMapper();
1085 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1086 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
1087 ResponseEntity<String> getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
1088 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
1089 String res = getResponse.getBody();
1090 JSONObject jsonObj = null;
1091 JSONArray extRoles = null;
1092 if (!res.equals("{}")) {
1093 jsonObj = new JSONObject(res);
1094 extRoles = jsonObj.getJSONArray("role");
1096 ExternalAccessUserRoleDetail userRoleDetail = null;
1097 if (extRoles != null) {
1098 for (int i = 0; i < extRoles.length(); i++) {
1099 if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".")
1100 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin")
1101 && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner")) {
1102 if (extRoles.getJSONObject(i).has("description")) {
1103 ExternalRoleDescription desc = new ExternalRoleDescription(extRoles.getJSONObject(i).getString("description"));
1104 userRoleDetail = new ExternalAccessUserRoleDetail(
1105 extRoles.getJSONObject(i).getString("name"), desc);
1106 userRoleDetailList.add(userRoleDetail);
1108 userRoleDetail = new ExternalAccessUserRoleDetail(
1109 extRoles.getJSONObject(i).getString("name"), null);
1110 userRoleDetailList.add(userRoleDetail);
1117 List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = CheckIfRoleAreMatchingInUserRoleDetailList(userRoleDetailList,app);
1119 // If request coming from portal not from external role approval system then we have to check if user already
1120 // have account admin or system admin as GUI will not send these roles
1121 if (!isPortalRequest) {
1122 final Map<String, String> loginIdParams = new HashMap<>();
1123 loginIdParams.put("orgUserIdValue", orgUserId);
1124 EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0);
1125 final Map<String, Long> params = new HashMap<>();
1126 params.put("appId", app.getId());
1127 params.put("userId", user.getId());
1128 List<EcompUserAppRoles> userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles",
1130 if (!roleInAppUser.isEmpty()) {
1131 for (EcompUserAppRoles userApp : userAppList) {
1132 if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
1133 || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
1134 RoleInAppForUser addSpecialRole = new RoleInAppForUser();
1135 addSpecialRole.setIsApplied(true);
1136 addSpecialRole.setRoleId(userApp.getRoleId());
1137 addSpecialRole.setRoleName(userApp.getRoleName());
1138 roleInAppUser.add(addSpecialRole);
1143 List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
1144 .collect(Collectors.toList());
1145 final Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
1146 for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
1147 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), roleInAppUserNew);
1149 final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
1150 for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
1151 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
1153 // Check if user roles does not exists in local but still there in External Central Auth System delete them all
1154 for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
1155 if (!(currentUserRolesToUpdate
1156 .containsKey(userRole.getName().substring(app.getNameSpace().length() + 1)))) {
1157 HttpEntity<String> entity = new HttpEntity<>(headers);
1158 logger.debug(EELFLoggerDelegate.debugLogger,
1159 "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
1160 userRole.getName());
1161 ResponseEntity<String> deleteResponse = template.exchange(
1162 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1163 + "userRole/" + name + "/" + userRole.getName(),
1164 HttpMethod.DELETE, entity, String.class);
1165 logger.debug(EELFLoggerDelegate.debugLogger,
1166 "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
1167 userRole.getName(), deleteResponse.getBody());
1170 // Check if user roles does not exists in External Central Auth System add them all
1171 for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
1172 if (!(currentUserRolesInExternalSystem
1173 .containsKey(app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")))) {
1174 ExternalAccessUser extUser = new ExternalAccessUser(name,
1175 app.getNameSpace() + "." + addUserRole.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1176 String formattedUserRole = mapper.writeValueAsString(extUser);
1177 HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
1178 logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
1179 name , addUserRole.getRoleName());
1180 ResponseEntity<String> addResponse = template
1181 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1182 + "userRole", HttpMethod.POST, entity, String.class);
1183 logger.debug(EELFLoggerDelegate.debugLogger,
1184 "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
1185 addResponse.getBody(), addUserRole.getRoleName());
1186 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 404) {
1187 logger.debug(EELFLoggerDelegate.debugLogger,
1188 "Finished POST operation in external system but unable to save user role", addResponse.getBody(),
1189 addUserRole.getRoleName());
1190 throw new Exception(addResponse.getBody());
1194 } catch (Exception e) {
1195 logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}", app.getId(), e);
1196 EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
1202 private List<ExternalAccessUserRoleDetail> CheckIfRoleAreMatchingInUserRoleDetailList(
1203 List<ExternalAccessUserRoleDetail> userRoleDetailList, EPApp app) {
1204 Map<String, EPRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
1205 //Add Account Admin role for partner app to prevent conflict
1206 if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1207 EPRole role = new EPRole();
1208 role.setName(PortalConstants.ADMIN_ROLE.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1209 epRoleList.put(role.getName(), role);
1211 userRoleDetailList.removeIf(userRoleDetail -> !epRoleList.containsKey(userRoleDetail.getName().substring(app.getNameSpace().length()+1)));
1212 return userRoleDetailList;
1219 * @param applicationsRestClientService
1220 * @param searchService
1224 protected void createNewUserOnRemoteApp(String userId, EPApp app,
1225 ApplicationsRestClientService applicationsRestClientService, SearchService searchService,
1226 ObjectMapper mapper, boolean postOpenSource) throws Exception {
1229 EPUser client = searchService.searchUserByUserId(userId);
1231 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1233 if (client == null) {
1234 String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
1235 logger.error(EELFLoggerDelegate.errorLogger, msg);
1236 throw new Exception(msg);
1239 client.setLoginId(userId);
1240 client.setActive(true);
1242 String userInString = null;
1243 userInString = mapper.writerFor(EPUser.class).writeValueAsString(client);
1244 logger.debug(EELFLoggerDelegate.debugLogger,
1245 "about to post new client to remote application, users json = " + userInString);
1246 applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId));
1250 @SuppressWarnings("unchecked")
1251 protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) {
1252 final Map<String, Long> epRequestParams = new HashMap<>();
1254 EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest;
1255 epAppRolesRequestData.setUpdatedDate(new Date());
1256 epAppRolesRequestData.setRequestStatus(updateStatus);
1257 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1258 addiotonalUpdateParam.put("userId", userId);
1259 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1260 epRequestParams.put("reqId", epUserAppRolesRequest.getId());
1261 List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1262 epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1263 epRequestParams, null);
1264 if (epUserAppRolessDetailList.size() > 0) {
1265 for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) {
1266 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData;
1267 epAppRoleDetailData.setReqType(updateStatus);
1268 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1269 HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>();
1270 addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId());
1271 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam);
1274 logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
1276 } catch (Exception e) {
1277 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
1281 @SuppressWarnings("unchecked")
1282 public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) {
1283 final Map<String, Long> params = new HashMap<>();
1284 final Map<String, Long> epDetailParams = new HashMap<>();
1285 List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>();
1286 params.put("appId", appId);
1287 params.put("userId", user.getId());
1289 epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService
1290 .executeNamedQuery("userAppRolesRequestList", params, null);
1291 if (epRequestIdVal.size() > 0) {
1292 EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
1293 epAppRolesRequestData.setUpdatedDate(new Date());
1294 epAppRolesRequestData.setRequestStatus("O");
1295 HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>();
1296 addiotonalUpdateParam.put("userId", user.getId());
1297 dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam);
1298 epDetailParams.put("reqId", epAppRolesRequestData.getId());
1299 List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>();
1300 epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList",
1301 epDetailParams, null);
1302 if (epUserAppRolesDetailList.size() > 0) {
1303 for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) {
1304 EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList;
1305 epAppRoleDetailData.setReqType("O");
1306 epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData);
1307 HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>();
1308 addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId());
1309 dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams);
1311 logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden");
1315 } catch (Exception e) {
1316 logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
1321 * Pushes specified user details to the specified remote app.
1324 * OrgUserId identifying user at remote app in REST endpoint path
1326 * User details to be pushed
1329 * @param applicationsRestClientService
1330 * @throws HTTPException
1332 protected void postUserToRemoteApp(String userId, EPUser user, EPApp app,
1333 ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
1335 getUser(userId, app, applicationsRestClientService);
1340 * It returns user details for single org user id
1344 * if user exists it returns list of user details otherwise empty value
1346 @SuppressWarnings("unchecked")
1347 private List<EPUser> checkIfUserExists(Map<String, String> userParams){
1348 return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null);
1352 * It checks whether the new user is valid or not otherwise throws exception
1357 * Checks if user is valid and returns message otherwise throws exception
1360 private String validateNewUser(String orgUserId, EPApp app) throws Exception {
1361 EPUser epUser = searchService.searchUserByUserId(orgUserId);
1362 if (epUser == null) {
1363 throw new Exception("User does not exist");
1364 } else if (!epUser.getOrgUserId().equals(orgUserId)) {
1365 throw new Exception("User does not exist");
1366 } else if (app == null) {
1367 throw new Exception("Application does not exist");
1369 return "Saved Successfully";
1373 * Checks if the fields exists or not
1376 * contains user information
1380 * throws exception if the field is not valid
1382 private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{
1383 if (userList.size() == 0 || userList.isEmpty() ) {
1384 throw new Exception("User does not exist");
1385 } else if(app == null) {
1386 throw new Exception("Application does not exist");
1387 } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1388 throw new Exception(app.getMlAppName()+" application is unavailable");
1392 @SuppressWarnings("unchecked")
1393 public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) {
1394 boolean result = false;
1395 boolean externalSystemRequest = true;
1396 final Map<String, Long> params = new HashMap<>();
1397 final Map<String, String> userParams = new HashMap<>();
1398 List<EPUser> userInfo = null;
1400 List<EPUserAppRolesRequest> epRequestId = null;
1401 String orgUserId = "";
1402 String updateStatus = "";
1403 String reqMessage = "";
1405 if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
1406 orgUserId = newAppRolesForUser.getLoginId().trim();
1408 String appName = newAppRolesForUser.getApplicationName();
1409 String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ;
1410 if (orgUserId.length() > 0) {
1411 ObjectMapper mapper = new ObjectMapper();
1412 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1413 int epRequestIdSize = 0;
1415 app = appsService.getAppDetail(appName);
1416 userParams.put("orgUserIdValue", orgUserId);
1417 userInfo = checkIfUserExists(userParams);
1418 reqMessage = "Updated Successfully";
1419 if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) {
1420 reqMessage = validateNewUser(orgUserId, app);
1422 if (userInfo.size() != 0 || !userInfo.isEmpty()) {
1423 validateExternalRequestFields(userInfo, app);
1424 user = userInfo.get(0);
1425 params.put("appId", app.getId());
1426 params.put("userId", user.getId());
1427 epRequestId = (List<EPUserAppRolesRequest>) dataAccessService
1428 .executeNamedQuery("userAppRolesRequestList", params, null);
1429 epRequestIdSize = epRequestId.size();
1432 //If Non-Centralized app make sure you sync app roles before assigning to user
1433 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()) {
1434 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Starting GET roles for app {}",app.getId());
1435 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
1436 logger.debug(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}",app.getId(), appRoles);
1437 if (appRoles.length > 0) {
1438 syncAppRoles(sessionFactory, app.getId(), appRoles);
1441 List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
1442 app.getId(), app.getMlAppName());
1443 List<EcompUserAppRoles> userRoleList = null;
1444 if(!userInfo.isEmpty()){
1445 final Map<String, Long> appParams = new HashMap<>();
1446 appParams.put("userId", user.getId());
1447 appParams.put("appId", app.getId());
1448 userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null);
1450 // Check if list contains just account admin role
1451 boolean checkIfAdminRoleExists = false;
1452 if (reqType.equals("DELETE") && userRoleList!=null) {
1453 checkIfAdminRoleExists = userRoleList.stream()
1454 .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1456 checkIfAdminRoleExists = roleInAppForUserList.stream()
1457 .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1459 // if Centralized app
1460 if (app.getCentralAuth()) {
1461 // We should add If user does not exist in remote application
1463 // If adding just account admin role dont make remote application user call or
1464 // if request has only single non admin role then make remote call
1465 if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
1466 && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
1467 || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
1468 // check if admin role exist then delete
1469 List<RoleInAppForUser> remoteUserRoles = roleInAppForUserList.stream()
1470 .collect(Collectors.toList());
1471 remoteUserRoles.removeIf(role -> {
1472 return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
1474 String orgUserIdNewOrExist = (userInfo.size() != 0 || !userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
1475 pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist , app, mapper, searchService,
1476 applicationsRestClientService,true);
1478 } catch (Exception e) {
1479 reqMessage = e.getMessage();
1480 logger.error(EELFLoggerDelegate.errorLogger, "setExternalRequestUserAppRole: Failed to added remote user", e);
1481 throw new Exception(reqMessage);
1483 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1484 applicationsRestClientService, app.getId(), orgUserId);
1485 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1486 userRolesInLocalApp);
1487 List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.roles;
1488 if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1489 // Apply changes in external Access system
1490 updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList, externalSystemRequest);
1492 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1493 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1494 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1496 // If local application is not centralized
1497 else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){
1498 Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper,
1499 applicationsRestClientService, app.getId(), orgUserId);
1500 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1501 userRolesInLocalApp);
1502 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType);
1503 } else {// remote app
1504 // If adding just account admin role don't do remote application user call
1505 if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
1506 EPUser remoteAppUser = null;
1507 remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
1508 if (remoteAppUser == null) {
1509 addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService,
1510 applicationsRestClientService);
1511 reqMessage = "Saved Successfully";
1514 Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
1515 applicationsRestClientService, app.getId(), orgUserId);
1517 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1518 userRolesInRemoteApp);
1519 logger.info(EELFLoggerDelegate.debugLogger,
1520 "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
1521 newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1522 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1524 // If no roles remain, request app to set user inactive.
1526 * if (userRolesInRemoteApp.size() == 0) {
1527 * logger.debug(EELFLoggerDelegate.debugLogger,
1528 * "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive"
1529 * , app, orgUserId); //TODO Need to fix the logged in user is not set to
1530 * inactive remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user,
1531 * app, applicationsRestClientService); }
1535 // Here we are adding only we have single account admin in roleInAppForUserList and this should not add in remote
1536 if(!(reqType.equals("DELETE")) && userInfo.isEmpty()){
1537 reqMessage = "Saved Successfully";
1539 Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
1541 RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
1542 userRolesInRemoteApp);
1543 logger.info(EELFLoggerDelegate.debugLogger, "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
1544 logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
1545 result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
1549 reqMessage = "Failed to save the user app role(s)";
1551 if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
1553 applyChangesToAppRolesRequest(app.getId(), user.getId(), updateStatus, epRequestId.get(0));
1556 } catch (Exception e) {
1557 String message = String.format("setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
1558 orgUserId, appName);
1559 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1561 reqMessage = e.getMessage();
1562 if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){
1564 applyChangesToAppRolesRequest(app.getId(), user.getId(),
1565 updateStatus, epRequestId.get(0));
1570 return new ExternalRequestFieldsValidator(result, reqMessage);
1575 * @param roleInAppForUserList
1577 * @param applicationsRestClientService
1580 * @return Set<EcompRole>
1581 * @throws JsonProcessingException
1582 * @throws HTTPException
1584 private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
1585 ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
1586 throws JsonProcessingException, HTTPException {
1587 Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
1588 return updatedUserRoles;
1592 * It constructs and returns list of user app roles when the external API role approval system calls
1595 * @param roleInAppForUserList
1597 * @return list of user app roles
1599 * throws exceptions if role id does not exits
1601 private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
1602 Long appId, String appName) throws Exception {
1603 List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>();
1604 EPRole existingAppRole = null;
1605 for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
1606 RoleInAppForUser ecompRole = new RoleInAppForUser();
1607 existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId);
1608 if (existingAppRole == null) {
1609 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1610 roleInAppForUserList);
1611 throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for " + appName + " application");
1613 if (!existingAppRole.getActive()) {
1614 logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
1615 roleInAppForUserList);
1616 throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application");
1618 ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId();
1619 ecompRole.roleName = roleInAppForUser.getRoleName();
1620 ecompRole.isApplied = true;
1621 existingUserRoles.add(ecompRole);
1624 return existingUserRoles;
1633 * @param applicationsRestClientService
1635 * @throws HTTPException
1637 protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1638 throws HTTPException {
1640 if (app.getId() == PortalConstants.PORTAL_APP_ID) {
1641 // Map<String,String> params = new HashMap<String,String>();
1642 // params.put("sbcid",userId);
1643 @SuppressWarnings("unchecked")
1644 List<EPUser> userList = (List<EPUser>) dataAccessService
1645 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
1646 if (userList != null && !userList.isEmpty())
1647 return userList.get(0);
1653 return getUser(userId, app, applicationsRestClientService);
1656 protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService)
1657 throws HTTPException {
1658 return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true);
1662 protected boolean isAppUpgradeVersion(EPApp app){
1667 public ExternalSystemAccess getExternalRequestAccess(){
1668 ExternalSystemAccess res = null;
1670 res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE,
1671 Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE)));
1672 } catch (Exception e) {
1673 logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage());
1681 * @see org.onap.portalapp.portal.service.UserRolesService#
1682 * getAppRolesForUser(java.lang.Long, java.lang.String)
1684 @SuppressWarnings("unchecked")
1685 public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue,EPUser user) {
1686 List<RoleInAppForUser> rolesInAppForUser = null;
1687 EPApp app = appsService.getApp(appId);
1688 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1690 // for onap portal app, no need to make a remote call
1691 List<Role> roleList = new ArrayList<>();
1692 if (appId == PortalConstants.PORTAL_APP_ID) {
1693 if(app.getCentralAuth()){
1694 List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1695 for(CentralV2Role cenRole : cenRoleList){
1696 Role role = new Role();
1697 role.setActive(cenRole.getActive());
1698 role.setId(cenRole.getId());
1699 role.setName(cenRole.getName());
1700 role.setPriority(cenRole.getPriority());
1704 roleList = roleService.getAvailableRoles(userId);
1706 List<Role> activeRoleList = new ArrayList<Role>();
1707 for(Role role: roleList) {
1708 if(role.getActive()) {
1709 if(role.getId() != 1){ // prevent portal admin from being added
1710 activeRoleList.add(role);
1711 } else if(extRequestValue){
1712 activeRoleList.add(role);
1717 EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService);
1718 // If localUser does not exists return roles
1719 Set<EPRole> roleSet = null;
1720 EPRole[] roleSetList = null;
1721 if(localUser != null){
1722 roleSet = localUser.getAppEPRoles(app);
1723 roleSetList = roleSet.toArray(new EPRole[0]);
1725 rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1726 return rolesInAppForUser;
1729 EcompRole[] appRoles = null;
1730 List<EcompRole> roles = new ArrayList<>();
1731 if (app.getCentralAuth()) {
1732 final Map<String, Long> appParams = new HashMap<>();
1733 appParams.put("appId", app.getId());
1734 List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication",
1737 EPApp application = appService.getApp(appId);
1738 boolean checkIfUserisApplicationAccAdmin = adminRolesService.isAccountAdminOfApplication(user,
1741 List<EPRole> rolesetwithfunctioncds = new ArrayList<EPRole>();
1742 for (EPRole role : applicationRoles) {
1743 Map<String, Long> params = new HashMap<>();
1744 params.put("roleId", role.getId());
1745 params.put(APP_ID, app.getId());
1746 List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService
1747 .executeNamedQuery("getAppRoleFunctionList", params, null);
1749 // SortedSet<CentralV2RoleFunction> roleFunctionSet =
1751 SortedSet<RoleFunction> roleFunctionSet = new TreeSet<>();
1752 for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1754 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1755 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1756 String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getCode());
1757 String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getCode());
1758 String name = roleFunc.getName();
1760 RoleFunction function = new RoleFunction();
1761 function.setAction(action);
1762 function.setType(type);
1763 function.setCode(functionCode);
1764 function.setName(name);
1765 roleFunctionSet.add(function);
1766 role.setRoleFunctions(roleFunctionSet);
1769 rolesetwithfunctioncds.add(role);
1774 for (EPRole role1 : rolesetwithfunctioncds) {
1775 EcompRole ecompRole = new EcompRole();
1776 ecompRole.setId(role1.getId());
1777 ecompRole.setName(role1.getName());
1778 ecompRole.setRoleFunctions(role1.getRoleFunctions());
1779 roles.add(ecompRole);
1782 if (checkIfUserisApplicationAccAdmin) {
1783 appRoles = roles.toArray(new EcompRole[roles.size()]);
1784 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1785 } else if (adminRolesService.isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin) {
1786 List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1787 List<String> roleAdminAppRolesNames = new ArrayList<>();
1788 final Map<String, Long> userParams = new HashMap<>();
1789 userParams.put("userId", user.getId());
1790 List<String> getUserApproverRoles = dataAccessService.executeNamedQuery("getUserApproverRoles", userParams, null);
1792 List<EcompRole> userapproverRolesList = new ArrayList<>();
1793 for (String str : getUserApproverRoles) {
1794 EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1796 userapproverRolesList.add(epRole);
1798 // roles.removeAll(userapproverRolesList);
1799 for (EcompRole role : userapproverRolesList) {
1801 List<RoleFunction> roleFunList = new ArrayList<>();
1802 roleFunList.addAll(role.getRoleFunctions());
1803 boolean checkIfFunctionsExits = roleFunList.stream()
1804 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1805 if (checkIfFunctionsExits) {
1806 roleAdminAppRoles.add(role);
1807 List<RoleFunction> filteredList = roleFunList.stream()
1808 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1809 roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1810 .collect(Collectors.toList()));
1811 // roleAdminAppRolesNames = filteredList.stream().map(RoleFunction::getCode)
1812 // .collect(Collectors.toList());
1815 for (String name : roleAdminAppRolesNames) {
1816 EcompRole ecompRole = roles.stream().filter(x -> name.equals(x.getName())).findAny()
1818 if (ecompRole != null)
1819 roleAdminAppRoles.add(ecompRole);
1822 appRoles = roleAdminAppRoles.toArray(new EcompRole[roleAdminAppRoles.size()]);
1826 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1828 // Test this error case, for generating an internal ONAP Portal
1830 // EcompRole[] appRoles = null;
1831 // If there is an exception in the rest client api, then null will
1833 if (appRoles != null) {
1834 if(!app.getCentralAuth()) {
1835 syncAppRoles(sessionFactory, appId, appRoles);
1837 EcompRole[] userAppRoles = null;
1841 if(app.getCentralAuth()){
1842 final Map<String, String> params = new HashMap<>();
1843 final Map<String, Long> userParams = new HashMap<>();
1844 params.put("orgUserIdValue", userId);
1845 List<EPUser> actualUser = dataAccessService.executeNamedQuery("epUserAppId", params, null);
1846 userParams.put("appId", app.getId());
1847 userParams.put("userId", actualUser.get(0).getId());
1848 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null);
1850 List<EcompRole> setUserRoles = new ArrayList<>();
1851 for(EPUserAppCurrentRoles role : userAppsRolesList){
1852 logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1853 EcompRole ecompRole = new EcompRole();
1854 ecompRole.setId(role.getRoleId());
1855 ecompRole.setName(role.getRoleName());
1856 setUserRoles.add(ecompRole);
1859 boolean checkIfUserisAccAdmin = setUserRoles.stream()
1860 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1862 if (!checkIfUserisAccAdmin) {
1863 List<EcompRole> userApplicationRolesList = setUserRoles;
1864 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1865 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1867 List<String> roleNames = new ArrayList<>();
1868 for (EcompRole role : userApplicationRolesList) {
1869 EcompRole epRole = appRolesList.stream()
1870 .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1871 List<RoleFunction> roleFunList = new ArrayList<>();
1872 if(epRole.getRoleFunctions().size()>0)
1873 roleFunList.addAll(epRole.getRoleFunctions());
1874 boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1875 roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1876 if (checkIfFunctionsExits) {
1877 finalUserAppRolesList.add(role);
1878 List<RoleFunction> filteredList = roleFunList.stream()
1879 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1880 .collect(Collectors.toList());
1881 roleNames = filteredList.stream().map(RoleFunction::getCode)
1882 .collect(Collectors.toList());
1885 for (String name : roleNames) {
1886 EcompRole ecompRole = appRolesList.stream()
1887 .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1888 if (ecompRole != null)
1889 finalUserAppRolesList.add(ecompRole);
1894 for (String name : roleNames) {
1896 boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1897 role -> role.getRoleName().equalsIgnoreCase(name));
1898 if(checkIfFunctionsExits)
1900 EcompRole epRole = appRolesList.stream().filter(x -> name.equals(x.getName()))
1901 .findAny().orElse(null);
1903 setUserRoles.add(epRole);
1907 userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]);
1910 userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1911 String.format("/user/%s/roles", userId));
1913 } catch (HTTPException e) {
1914 // Some apps are returning 400 if user is not found.
1915 if (e.getResponseCode() == 400) {
1916 logger.debug(EELFLoggerDelegate.debugLogger,
1917 "getAppRolesForUser caught exception with response code 400; continuing", e);
1919 // Other response code, let it come thru.
1923 if (userAppRoles == null) {
1924 if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1925 EcompPortalUtils.setExternalAppResponseCode(200);
1926 String message = String.format(
1927 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1928 + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1929 + "Overriding to 200 until framework SDK returns a useful response.",
1930 Long.toString(appId), userId);
1931 logger.warn(EELFLoggerDelegate.applicationLogger, message);
1935 HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles);
1936 ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>();
1937 if(userAppRoles != null){
1938 for (int i = 0; i < userAppRoles.length; i++) {
1939 if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) {
1940 EcompRole role = new EcompRole();
1941 role.setId(userAppRoles[i].getId());
1942 role.setName(userAppRoles[i].getName());
1943 activeRoles.add(role);
1947 EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]);
1949 // If the remote application isn't down we MUST sync user
1950 // roles here in case we have this user here!
1951 syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null);
1952 } catch (Exception e) {
1953 // TODO: we may need to check if user exists, maybe remote
1955 String message = String.format(
1956 "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1957 Long.toString(appId));
1958 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1959 userAppRoles = new EcompRole[0];
1961 rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
1963 } catch (Exception e) {
1964 String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1965 Long.toString(appId));
1966 logger.error(EELFLoggerDelegate.errorLogger, message, e);
1968 return rolesInAppForUser;
1971 private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData,
1972 ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId)
1973 throws JsonProcessingException, HTTPException {
1974 boolean result = false;
1975 ObjectMapper mapper = new ObjectMapper();
1976 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1977 String userRolesAsString = mapper.writeValueAsString(userAppRolesData);
1978 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins");
1979 applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId));
1983 @SuppressWarnings("unchecked")
1984 public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) {
1985 FieldsValidator fieldsValidator = new FieldsValidator();
1986 final Map<String, Long> params = new HashMap<>();
1987 List<EPUserAppRoles> appRole= null;
1989 logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined");
1990 boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId());
1991 logger.debug(EELFLoggerDelegate.debugLogger,"putUserAppRolesRequest: result {}", result);
1993 params.put("appId", userAppRolesData.appId);
1994 EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest();
1995 epAppRolesRequestData.setCreatedDate(new Date());
1996 epAppRolesRequestData.setUpdatedDate(new Date());
1997 epAppRolesRequestData.setUserId(user.getId());
1998 epAppRolesRequestData.setAppId(userAppRolesData.appId);
1999 epAppRolesRequestData.setRequestStatus("P");
2000 List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles;
2001 Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>();
2002 dataAccessService.saveDomainObject(epAppRolesRequestData, null);
2003 for (RoleInAppForUser userAppRoles : appRoleIdList) {
2004 Boolean isAppliedVal = userAppRoles.isApplied;
2005 params.put("appRoleId", userAppRoles.roleId);
2007 appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null);
2008 if (!appRole.isEmpty()) {
2009 EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail();
2010 epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId());
2011 epAppRoleDetail.setReqType("P");
2012 epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData);
2013 dataAccessService.saveDomainObject(epAppRoleDetail, null);
2017 epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails);
2018 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
2020 } catch (Exception e) {
2021 logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e);
2022 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2024 return fieldsValidator;
2027 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) {
2028 Map<String, String> params = new HashMap<>();
2029 params.put("userid", userid.getId().toString());
2030 //params.put("appid", appid);
2031 params.put("appName", appName);
2033 @SuppressWarnings("unchecked")
2034 List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService
2035 .executeNamedQuery("userAppCatalogRoles", params, null);
2036 return userAppRoles;
2039 public String updateRemoteUserProfile(String orgUserId, Long appId) {
2040 ObjectMapper mapper = new ObjectMapper();
2041 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2042 EPUser client = searchService.searchUserByUserId(orgUserId);
2043 EPUser newUser = new EPUser();
2044 newUser.setActive(client.getActive());
2045 newUser.setFirstName(client.getFirstName());
2046 newUser.setLastName(client.getLastName());
2047 newUser.setLoginId(client.getLoginId());
2048 newUser.setLoginPwd(client.getLoginPwd());
2049 newUser.setMiddleInitial(client.getMiddleInitial());
2050 newUser.setEmail(client.getEmail());
2051 newUser.setOrgUserId(client.getLoginId());
2053 String userAsString = mapper.writeValueAsString(newUser);
2054 List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
2055 // applicationsRestClientService.post(EPUser.class, appId,
2056 // userAsString, String.format("/user", orgUserId));
2057 for (EPApp eachApp : appList) {
2059 applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString,
2060 String.format("/user/%s", orgUserId));
2061 } catch (Exception e) {
2062 logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId()
2063 + " in remote app. appId = " + eachApp.getId());
2066 } catch (Exception e) {
2067 logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
2078 * @see org.onap.portalapp.portal.service.UserRolesService#
2079 * getCachedAppRolesForUser(java.lang.Long, java.lang.Long)
2081 @SuppressWarnings("deprecation")
2082 public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
2083 // Find the records for this user-app combo, if any
2084 String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
2085 @SuppressWarnings("unchecked")
2086 List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
2087 logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size());
2092 * It retrieves and returns list of user app roles for local and remote applications based app id
2095 * @return list of user app roles
2096 * @throws HTTPException
2098 public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
2099 ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
2101 EPApp app = appsService.getApp(appId);
2102 //If local or centralized application
2103 if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
2104 @SuppressWarnings("unchecked")
2105 List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
2106 for (EPUser user : userList) {
2107 UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
2108 if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
2109 userApplicationRoles.add(userWithAppRoles);
2115 RemoteUserWithRoles[] remoteUsers = null;
2116 String remoteUsersString = applicationsRestClientService.getIncomingJsonString(appId, "/users");
2118 remoteUsers = doGetUsers(isAppUpgradeVersion(app), remoteUsersString);
2120 userApplicationRoles = new ArrayList<UserApplicationRoles>();
2121 for (RemoteUserWithRoles remoteUser : remoteUsers) {
2122 UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
2123 if (userWithRemoteAppRoles.getRoles() != null && userWithRemoteAppRoles.getRoles().size() > 0) {
2124 userApplicationRoles.add(userWithRemoteAppRoles);
2126 logger.debug(EELFLoggerDelegate.debugLogger,
2127 "User " + userWithRemoteAppRoles.getOrgUserId() + " doesn't have any roles assigned to any app.");
2132 return userApplicationRoles;
2139 * @param appgetUsersFromAppEndpoint
2142 private UserApplicationRoles convertToUserApplicationRoles(Long appId, EPUser user, EPApp app) {
2143 UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
2144 userWithRemoteAppRoles.setAppId(appId);
2145 userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
2146 userWithRemoteAppRoles.setFirstName(user.getFirstName());
2147 userWithRemoteAppRoles.setLastName(user.getLastName());
2148 userWithRemoteAppRoles.setRoles(convertToRemoteRoleList(user, app));
2149 return userWithRemoteAppRoles;
2158 @SuppressWarnings("unchecked")
2159 private List<RemoteRole> convertToRemoteRoleList(EPUser user, EPApp app) {
2160 List<RemoteRole> roleList = new ArrayList<RemoteRole>();
2161 SortedSet<EPRole> roleSet = user.getAppEPRoles(app);
2162 for (EPRole role : roleSet) {
2163 logger.debug(EELFLoggerDelegate.debugLogger, "In convertToRemoteRoleList() - for user {}, found Name {}", user.getOrgUserId(), role.getName());
2164 RemoteRole rRole = new RemoteRole();
2165 rRole.setId(role.getId());
2166 rRole.setName(role.getName());
2167 roleList.add(rRole);
2170 //Get the active roles of user for that application using query
2171 List<EPRole> userEpRoleList = new ArrayList<>();
2172 final Map<String, Long> params = new HashMap<>();
2173 params.put("appId", app.getId());
2174 params.put("userId", user.getId());
2175 userEpRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndAppId", params, null);
2177 for (EPRole remoteUserRoleList : userEpRoleList) {
2179 RemoteRole remoteRoleListId = roleList.stream().filter(x -> remoteUserRoleList.getId().equals(x.getId()))
2180 .findAny().orElse(null);
2181 if (remoteRoleListId == null) {
2182 logger.debug(EELFLoggerDelegate.debugLogger,
2183 "Adding the role to the rolelist () - for user {}, found Name {}", user.getOrgUserId(),
2185 remoteUserRoleList.getName());
2186 RemoteRole role = new RemoteRole();
2187 role.setId(remoteUserRoleList.getId());
2188 role.setName(remoteUserRoleList.getName());
2195 logger.debug(EELFLoggerDelegate.debugLogger, "rolelist size of the USER() - for user {}, found RoleListSize {}", user.getOrgUserId(), roleList.size());
2203 public RemoteUserWithRoles[] doGetUsers(boolean postOpenSource, String remoteUsersString) {
2205 ObjectMapper mapper = new ObjectMapper();
2207 return mapper.readValue(remoteUsersString, RemoteUserWithRoles[].class);
2208 } catch (IOException e) {
2209 logger.error(EELFLoggerDelegate.errorLogger,
2210 "doGetUsers : Failed : Unexpected property in incoming JSON",
2212 logger.error(EELFLoggerDelegate.errorLogger,
2213 "doGetUsers : Incoming JSON that caused it --> " + remoteUsersString);
2216 return new RemoteUserWithRoles[0];
2219 @SuppressWarnings("unchecked")
2220 public List<EPUserApp> getEPUserAppList(Long appId, Long userId, Long roleId) {
2221 List<EPUserApp> userRoleList = new ArrayList<EPUserApp>();
2222 final Map<String, Long> params = new HashMap<>();
2223 params.put("appId", appId);
2224 params.put("userId", userId);
2225 params.put("roleId", roleId);
2226 userRoleList = dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null);
2227 return userRoleList;
2231 /*public static void main(String[] args) {
2232 List<EcompRole> str1 = new ArrayList<String>();
2238 List<String> str2 = new ArrayList<String>();
2242 List<EcompRole> userApplicationRolesList = setUserRoles;
2243 List<EcompRole> appRolesList = Arrays.asList(appRoles);