f8ef4a991b8cd9ffb5becc633ee639580d75a3f4
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / AdminRolesService.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.service;
42
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.DeserializationFeature;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import java.time.LocalDateTime;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.List;
54 import java.util.Map;
55 import java.util.Optional;
56 import java.util.Set;
57 import java.util.SortedSet;
58 import java.util.TreeSet;
59 import java.util.stream.Collectors;
60 import javax.persistence.EntityManager;
61 import javax.persistence.Query;
62 import javax.persistence.Tuple;
63 import org.apache.commons.lang.StringUtils;
64 import org.apache.cxf.transport.http.HTTPException;
65 import org.hibernate.Session;
66 import org.hibernate.Transaction;
67 import org.json.JSONArray;
68 import org.json.JSONObject;
69 import org.onap.portal.domain.db.DomainVo;
70 import org.onap.portal.domain.db.ep.EpAppFunction;
71 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
72 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
73 import org.onap.portal.domain.db.fn.FnApp;
74 import org.onap.portal.domain.db.fn.FnFunction;
75 import org.onap.portal.domain.db.fn.FnMenuFunctional;
76 import org.onap.portal.domain.db.fn.FnMenuFunctionalRoles;
77 import org.onap.portal.domain.db.fn.FnRole;
78 import org.onap.portal.domain.db.fn.FnRoleFunction;
79 import org.onap.portal.domain.db.fn.FnUser;
80 import org.onap.portal.domain.db.fn.FnUserRole;
81 import org.onap.portal.domain.dto.ecomp.EPUserApp;
82 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
83 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
84 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
85 import org.onap.portal.domain.dto.transport.CentralV2Role;
86 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
87 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
88 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
89 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
90 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
91 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
92 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
93 import org.onap.portal.domain.dto.transport.Role;
94 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
95 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
96 import org.onap.portal.exception.DeleteDomainObjectFailedException;
97 import org.onap.portal.exception.RoleFunctionException;
98 import org.onap.portal.exception.SyncUserRolesException;
99 import org.onap.portal.logging.format.EPAppMessagesEnum;
100 import org.onap.portal.logging.logic.EPLogUtil;
101 import org.onap.portal.service.appFunction.EpAppFunctionService;
102 import org.onap.portal.service.roleFunction.FnRoleFunctionService;
103 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
104 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
105 import org.onap.portal.service.app.FnAppService;
106 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
107 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
108 import org.onap.portal.service.role.FnRoleService;
109 import org.onap.portal.service.userRole.FnUserRoleService;
110 import org.onap.portal.service.user.FnUserService;
111 import org.onap.portal.utils.EPCommonSystemProperties;
112 import org.onap.portal.utils.EPUserUtils;
113 import org.onap.portal.utils.EcompPortalUtils;
114 import org.onap.portal.utils.PortalConstants;
115 import org.onap.portalsdk.core.domain.RoleFunction;
116 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
117 import org.onap.portalsdk.core.restful.domain.EcompRole;
118 import org.onap.portalsdk.core.util.SystemProperties;
119 import org.springframework.beans.factory.annotation.Autowired;
120 import org.springframework.http.HttpEntity;
121 import org.springframework.http.HttpHeaders;
122 import org.springframework.http.HttpMethod;
123 import org.springframework.http.HttpStatus;
124 import org.springframework.http.ResponseEntity;
125 import org.springframework.stereotype.Service;
126 import org.springframework.transaction.annotation.Transactional;
127 import org.springframework.web.client.HttpClientErrorException;
128 import org.springframework.web.client.RestTemplate;
129
130 @Service
131 @Transactional
132 public class AdminRolesService {
133
134     private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
135     private static final Object syncRests = new Object();
136     private final RestTemplate template = new RestTemplate();
137
138     private Long SYS_ADMIN_ROLE_ID = 38L;
139     private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
140     private final Long ECOMP_APP_ID = 1L;
141     private final String ADMIN_ACCOUNT = "Is account admin for user {}";
142
143     private final AppsCacheService appsCacheService;
144     private final EntityManager entityManager;
145     private final FnUserService fnUserService;
146     private final FnRoleService fnRoleService;
147     private final FnAppService fnAppService;
148     private final FnRoleFunctionService fnRoleFunctionService;
149     private final FnMenuFunctionalService fnMenuFunctionalService;
150     private final FnUserRoleService fnUserRoleService;
151     private final EpAppFunctionService epAppFunctionService;
152     private final EcompUserAppRolesService ecompUserAppRolesService;
153     private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
154     private final ApplicationsRestClientService applicationsRestClientService;
155     private final EpUserRolesRequestDetService epUserRolesRequestDetService;
156     private final ExternalAccessRolesService externalAccessRolesService;
157     private final EpUserRolesRequestService epUserRolesRequestService;
158
159     @Autowired
160     public AdminRolesService(AppsCacheService appsCacheService,
161         final EntityManager entityManager,
162         final FnUserService fnUserService, FnRoleService fnRoleService,
163         FnAppService fnAppService,
164         FnRoleFunctionService fnRoleFunctionService, FnMenuFunctionalService fnMenuFunctionalService,
165         final FnUserRoleService fnUserRoleService,
166         EpAppFunctionService epAppFunctionService,
167         EcompUserAppRolesService ecompUserAppRolesService,
168         FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
169         ApplicationsRestClientService applicationsRestClientService,
170         EpUserRolesRequestDetService epUserRolesRequestDetService,
171         ExternalAccessRolesService externalAccessRolesService,
172         EpUserRolesRequestService epUserRolesRequestService) {
173         this.appsCacheService = appsCacheService;
174         this.entityManager = entityManager;
175         this.fnUserService = fnUserService;
176         this.fnRoleService = fnRoleService;
177         this.fnAppService = fnAppService;
178         this.fnRoleFunctionService = fnRoleFunctionService;
179         this.fnMenuFunctionalService = fnMenuFunctionalService;
180         this.fnUserRoleService = fnUserRoleService;
181         this.epAppFunctionService = epAppFunctionService;
182         this.ecompUserAppRolesService = ecompUserAppRolesService;
183         this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
184         this.applicationsRestClientService = applicationsRestClientService;
185         this.epUserRolesRequestDetService = epUserRolesRequestDetService;
186         this.externalAccessRolesService = externalAccessRolesService;
187         this.epUserRolesRequestService = epUserRolesRequestService;
188     }
189
190     public boolean isSuperAdmin(final String loginId) {
191         boolean isSuperAdmin;
192         try {
193             isSuperAdmin = fnUserRoleService
194                 .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
195         } catch (Exception e) {
196             logger.error("isSuperAdmin exception: " + e.toString());
197             throw e;
198         }
199         logger.info("isSuperAdmin " + isSuperAdmin);
200         return isSuperAdmin;
201     }
202
203     public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
204         try {
205             logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
206             List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
207             logger.debug(EELFLoggerDelegate.debugLogger,
208                 "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
209                 orgUserId, userAdminApps.size());
210
211             for (FnUserRole userApp : userApps) {
212                 if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
213                     userAdminApps.size() > 1)) {
214                     logger.debug(EELFLoggerDelegate.debugLogger,
215                         "Is account admin for userAdminApps() - for user {}, found Id {}",
216                         orgUserId, userApp.getRoleId().getId());
217                     return true;
218                 }
219             }
220         } catch (Exception e) {
221             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
222             logger.error(EELFLoggerDelegate.errorLogger,
223                 "Exception occurred while executing isAccountAdmin operation",
224                 e);
225         }
226         return false;
227     }
228
229     public boolean isUser(final long userId) {
230         try {
231             FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
232             if (currentUser != null && currentUser.getId() != null) {
233                 for (FnUserRole userApp : currentUser.getUserApps()) {
234                     if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
235                         FnRole role = userApp.getRoleId();
236                         if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
237                             .equals(ACCOUNT_ADMIN_ROLE_ID)) {
238                             if (role.getActiveYn()) {
239                                 return true;
240                             }
241                         }
242                     }
243                 }
244             }
245         } catch (Exception e) {
246             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
247             logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
248                 e);
249         }
250         return false;
251     }
252
253     public boolean isRoleAdmin(Long userId) {
254         try {
255             logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
256             List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
257             logger.debug(EELFLoggerDelegate.debugLogger,
258                 "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
259             Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
260             Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
261             Set<String> roleFunSet;
262             roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
263                 .collect(Collectors.toSet());
264             if (!roleFunSet.isEmpty()) {
265                 for (String roleFunction : roleFunSet) {
266                     String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
267                     getRoleFuncListOfPortalSet1.add(type);
268                 }
269             }
270
271             boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
272                 .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
273             logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
274                 checkIfFunctionsExits);
275
276             return checkIfFunctionsExits;
277
278         } catch (Exception e) {
279             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
280             logger.error(EELFLoggerDelegate.errorLogger,
281                 "Exception occurred while executing isRoleAdmin operation",
282                 e);
283         }
284         return false;
285     }
286
287     private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
288         boolean isApplicationAccountAdmin = false;
289         try {
290             logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
291             List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
292             if (!userAdminApps.isEmpty()) {
293                 isApplicationAccountAdmin = userAdminApps.contains(app.getId());
294                 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
295                     app.getId());
296             }
297         } catch (Exception e) {
298             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
299             logger.error(EELFLoggerDelegate.errorLogger,
300                 "Exception occurred while executing isAccountAdminOfApplication operation", e);
301         }
302         logger.debug(EELFLoggerDelegate.debugLogger,
303             "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
304             userId);
305         return isApplicationAccountAdmin;
306
307     }
308
309     private List<Integer> getAdminAppsForTheUser(final Long userId) {
310         String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)";
311         return entityManager.createQuery(query, Integer.class)
312             .setParameter("userId", userId).getResultList();
313     }
314
315     public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
316         AppWithRolesForUser newAppRolesForUser) {
317         boolean result = false;
318         boolean epRequestValue = false;
319         String userId = "";
320         String reqMessage = "";
321         if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
322             userId = newAppRolesForUser.getOrgUserId().trim();
323         }
324         Long appId = newAppRolesForUser.getAppId();
325         List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
326
327         if (userId.length() > 0) {
328             ObjectMapper mapper = new ObjectMapper();
329             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
330
331             try {
332                 FnApp app = fnAppService.getById(appId);
333
334                 boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
335                     app);
336                 Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
337
338                 boolean checkIfUserIsOnlyRoleAdmin =
339                     isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
340                 if (checkIfUserIsOnlyRoleAdmin) {
341                     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
342                         if (!roleInAppForUser.getIsApplied()) {
343                             EcompRole ecompRole = new EcompRole();
344                             ecompRole.setId(roleInAppForUser.getRoleId());
345                             ecompRole.setName(roleInAppForUser.getRoleName());
346                             rolesGotDeletedFromApprover.add(ecompRole);
347                         }
348                     }
349                 }
350
351                 applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
352
353                 boolean systemUser = newAppRolesForUser.isSystemUser();
354
355                 if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
356                     && systemUser) {
357
358                     Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
359                     RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
360                         userRolesInLocalApp);
361                     List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
362                     Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
363                     if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
364                         // Apply changes in external Access system
365
366                         updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
367                             roleAppUserList,
368                             epRequestValue, systemUser, rolesGotDeletedByApprover, false);
369                     }
370                     result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
371                         "Portal",
372                         systemUser, rolesGotDeletedByApprover, false);
373
374                 } else if (!app.getAuthCentral() && systemUser) {
375                     throw new Exception("For non-centralized application we cannot add systemUser");
376                 } else {    // if centralized app
377                     if (app.getAuthCentral()) {
378                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
379                             pushRemoteUser(roleInAppForUserList, userId, app, mapper,
380                                 applicationsRestClientService, false);
381                         }
382
383                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
384                             roleInAppForUserList);
385                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
386                             appId,
387                             userRolesInLocalApp);
388                         List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
389                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
390
391                             // Apply changes in external Access system
392                             updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
393                                 roleAppUserList,
394                                 epRequestValue, false, rolesGotDeletedFromApprover,
395                                 checkIfUserIsOnlyRoleAdmin);
396                         }
397                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
398                             epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
399                             checkIfUserIsOnlyRoleAdmin);
400                     }
401                     // In case if portal is not centralized then follow existing approach
402                     else if (!app.getAuthCentral() && app.getId()
403                         .equals(PortalConstants.PORTAL_APP_ID)) {
404                         Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
405                             roleInAppForUserList);
406                         RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
407                             appId,
408                             userRolesInLocalApp);
409                         Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
410                         result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
411                             epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
412                     } else {// remote app
413                         FnUser remoteAppUser;
414                         if (!app.getAuthCentral() && !app.getId()
415                             .equals(PortalConstants.PORTAL_APP_ID)) {
416
417                             remoteAppUser = checkIfRemoteUserExits(userId, app,
418                                 applicationsRestClientService);
419
420                             if (remoteAppUser == null) {
421                                 addRemoteUser(roleInAppForUserList, userId, app,
422                                     mapper, applicationsRestClientService);
423                             }
424                             Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
425                                 roleInAppForUserList, mapper,
426                                 applicationsRestClientService, appId, userId);
427                             RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
428                                 userId, appId,
429                                 userRolesInRemoteApp);
430                             Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
431                             result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
432                                 epRequestValue, null, false, rolesGotDeletedByApprover, false);
433
434                             // If no roles remain, request app to set user inactive.
435                             if (userRolesInRemoteApp.size() == 0) {
436                                 logger.debug(EELFLoggerDelegate.debugLogger,
437                                     "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
438                                     app,
439                                     userId);
440                                 postUserToRemoteApp(userId, app,
441                                     applicationsRestClientService);
442                             }
443                         }
444                     }
445                 }
446             } catch (Exception e) {
447                 String message = String.format(
448                     "Failed to create user or update user roles for User %s, AppId %s",
449                     userId, Long.toString(appId));
450                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
451                 result = false;
452                 reqMessage = e.getMessage();
453             }
454         }
455         return new ExternalRequestFieldsValidator(result, reqMessage);
456
457     }
458
459     private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
460         ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
461         throws Exception {
462         pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
463             roleInAppForUserList, appRoleIdUsed);
464     }
465
466
467     private void postUserToRemoteApp(String userId, FnApp app,
468         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
469
470         getUser(userId, app, applicationsRestClientService);
471
472     }
473
474     private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
475         throws HTTPException {
476         return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
477
478     }
479
480     private void pushUserOnRemoteApp(String userId, FnApp app,
481         ApplicationsRestClientService applicationsRestClientService,
482         ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
483         throws Exception {
484
485         FnUser client;
486         client = fnUserService.loadUserByUsername(userId);
487
488         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
489         if (client == null) {
490             String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
491             logger.error(EELFLoggerDelegate.errorLogger, msg);
492             List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
493             if (!userList.isEmpty()) {
494                 logger.debug(EELFLoggerDelegate.debugLogger,
495                     userList.get(0).getOrgUserId() + " User was found in Portal");
496                 client = userList.get(0);
497                 client.setUserApps(Collections.EMPTY_SET);
498                 client.setIsSystemUser(false);
499             } else {
500                 logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
501                 throw new Exception(msg);
502             }
503
504         }
505
506         client.setLoginId(userId);
507         client.setActiveYn(true);
508         client.setOrgUserId(userId);
509
510         roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
511         SortedSet<Role> roles = new TreeSet<>();
512
513         List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
514         List<FnApp> appList = new ArrayList<>();
515         appList.add(app);
516         List<CentralV2Role> roleList = new ArrayList<>();
517
518         List<FnRole> userRoles = new ArrayList<>();
519
520         for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
521             FnRole role = new FnRole();
522             role.setId(roleInappForUser.getRoleId());
523             role.setRoleName(roleInappForUser.getRoleName());
524             userRoles.add(role);
525         }
526
527         if (appRoleIdUsed) {
528             List<FnRole> userAppRoles = new ArrayList<>();
529             for (FnRole role : userRoles) {
530                 FnRole appRole = getAppRoles.stream()
531                     .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
532                     .orElse(null);
533                 FnRole epRole = new FnRole();
534                 if (appRole != null) {
535                     epRole.setId(appRole.getId());
536                     epRole.setRoleName(appRole.getRoleName());
537                 }
538                 userAppRoles.add(epRole);
539             }
540             userRoles = new ArrayList<>(userAppRoles);
541         }
542         roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
543
544         for (CentralV2Role epRole : roleList) {
545             Role role = new Role();
546             FnRole appRole = getAppRoles.stream()
547                 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
548             List<FnRoleFunction> fnRoleFunctions = new ArrayList<>();
549             for (DomainVo vo: epRole.getRoleFunctions()){
550                 Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
551                 roleFunction.ifPresent(fnRoleFunctions::add);
552             }
553             if (appRole != null) {
554                 role.setId(appRole.getAppRoleId());
555                 role.setRoleName(epRole.getName());
556                 role.setFnRoleFunctions(new HashSet<>(fnRoleFunctions));
557             }
558             roles.add(role);
559         }
560         client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
561         String userInString;
562         userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
563         logger.debug(EELFLoggerDelegate.debugLogger,
564             "about to post a client to remote application, users json = " + userInString);
565         applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
566     }
567
568     private FnRole roleToFnRole(Role role) {
569         return FnRole.builder()
570             .id(role.getId())
571             .roleName(role.getRoleName())
572             .activeYn(role.getActiveYn())
573             .priority(role.getPriority())
574             .fnRoleFunctions(role.getFnRoleFunctions())
575             .childRoles(role.getChildRoles())
576             .parentRoles(role.getParentRoles())
577             .build();
578     }
579
580     private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
581         ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
582         throws JsonProcessingException, HTTPException {
583         Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
584         Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
585         String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
586         FnApp externalApp;
587         externalApp = appsCacheService.getApp(appId);
588         String appBaseUri = null;
589         Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
590         if (externalApp != null) {
591             appBaseUri = externalApp.getAppRestEndpoint();
592         }
593         if (appBaseUri != null && appBaseUri.endsWith("/api")) {
594             for (EcompRole eprole : updatedUserRolesinRemote) {
595                 RemoteRoleV1 role = new RemoteRoleV1();
596                 role.setId(eprole.getId());
597                 role.setName(eprole.getName());
598                 updatedUserRolesinRemoteV1.add(role);
599             }
600             userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
601         }
602         applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
603             String.format("/user/%s/roles", userId));
604         return updateUserRolesInEcomp;
605     }
606
607     private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
608         ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
609         if (remoteUserShouldBeCreated(roleInAppForUserList)) {
610             createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
611         }
612     }
613
614     private void createNewUserOnRemoteApp(String userId, FnApp app,
615         ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
616         throws Exception {
617
618         FnUser client = fnUserService.loadUserByUsername(userId);
619
620         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
621
622         if (client == null) {
623             String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
624             logger.error(EELFLoggerDelegate.errorLogger, msg);
625             throw new Exception(msg);
626         }
627
628         client.setLoginId(userId);
629         client.setActiveYn(true);
630
631         String userInString;
632         userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
633         logger.debug(EELFLoggerDelegate.debugLogger,
634             "about to post new client to remote application, users json = " + userInString);
635         applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
636
637     }
638
639     private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
640         for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
641             if (roleInAppForUser.getIsApplied()) {
642                 return true;
643             }
644         }
645         return false;
646     }
647
648     private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
649         Set<EcompRole> existingUserRoles = new TreeSet<>();
650         for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
651             if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
652                 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
653                 EcompRole ecompRole = new EcompRole();
654                 ecompRole.setId(roleInAppForUser.getRoleId());
655                 ecompRole.setName(roleInAppForUser.getRoleName());
656                 existingUserRoles.add(ecompRole);
657             }
658         }
659         return existingUserRoles;
660     }
661
662     private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
663         List<EpUserRolesRequest> epRequestIdVal;
664         try {
665             epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
666             if (epRequestIdVal.size() > 0) {
667                 EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
668                 epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
669                 epAppRolesRequestData.setRequestStatus("O");
670                 epAppRolesRequestData.setUserId(user);
671                 epUserRolesRequestService.saveOne(epAppRolesRequestData);
672                 List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
673                     .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
674                 if (epUserAppRolesDetailList.size() > 0) {
675                     for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
676                         epRequestUpdateList.setRequestType("O");
677                         epRequestUpdateList.setReqId(epAppRolesRequestData);
678                         epRequestUpdateList.setReqId(epAppRolesRequestData);
679                         epUserRolesRequestDetService.saveOne(epRequestUpdateList);
680                     }
681                     logger.debug(EELFLoggerDelegate.debugLogger,
682                         "User App roles request from User Page is overridden");
683                 }
684             }
685
686         } catch (Exception e) {
687             logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
688         }
689     }
690
691     private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
692         return constructUsersEcompRoles(roleInAppForUserList);
693     }
694
695     private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
696         Set<EcompRole> existingUserRoles = new TreeSet<>();
697         for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
698             if (roleInAppForUser.getIsApplied()) {
699                 EcompRole ecompRole = new EcompRole();
700                 ecompRole.setId(roleInAppForUser.getRoleId());
701                 ecompRole.setName(roleInAppForUser.getRoleName());
702                 existingUserRoles.add(ecompRole);
703             }
704         }
705         return existingUserRoles;
706     }
707
708     public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
709         Set<EcompRole> userRolesInRemoteApp) {
710         RolesInAppForUser result;
711         result = new RolesInAppForUser();
712         result.setAppId(appId);
713         result.setOrgUserId(userId);
714
715         for (EcompRole role : userRolesInRemoteApp) {
716             RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
717             roleInAppForUser.setRoleId(role.getId());
718             roleInAppForUser.setRoleName(role.getName());
719             roleInAppForUser.setIsApplied(true);
720             result.getRoles().add(roleInAppForUser);
721         }
722         return result;
723     }
724
725     private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
726         boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
727         boolean isLoggedInUserRoleAdminofApp) throws Exception {
728         try {
729             List<FnUser> userInfo = checkIfUserExists(orgUserId);
730             if (userInfo.isEmpty()) {
731                 createLocalUserIfNecessary(orgUserId, isSystemUser);
732             }
733             String name;
734             if (EPCommonSystemProperties
735                 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
736                 && !isSystemUser) {
737                 name = orgUserId
738                     + SystemProperties
739                     .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
740             } else {
741                 name = orgUserId;
742             }
743             ObjectMapper mapper = new ObjectMapper();
744             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
745             HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
746             ResponseEntity<String> getResponse = externalAccessRolesService
747                 .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
748
749             List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
750             String res = getResponse.getBody();
751             JSONObject jsonObj;
752             JSONArray extRoles = null;
753             if (!res.equals("{}")) {
754                 jsonObj = new JSONObject(res);
755                 extRoles = jsonObj.getJSONArray("role");
756             }
757             ExternalAccessUserRoleDetail userRoleDetail;
758             if (extRoles != null) {
759                 for (int i = 0; i < extRoles.length(); i++) {
760                     if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
761                         && !extRoles.getJSONObject(i).getString("name")
762                         .equals(app.getAuthNamespace() + ".admin")
763                         && !extRoles.getJSONObject(i).getString("name")
764                         .equals(app.getAuthNamespace() + ".owner")) {
765                         if (extRoles.getJSONObject(i).has("description")) {
766                             ExternalRoleDescription desc = new ExternalRoleDescription(
767                                 extRoles.getJSONObject(i).getString("description"));
768                             userRoleDetail = new ExternalAccessUserRoleDetail(
769                                 extRoles.getJSONObject(i).getString("name"), desc);
770                             userRoleDetailList.add(userRoleDetail);
771                         } else {
772                             userRoleDetail = new ExternalAccessUserRoleDetail(
773                                 extRoles.getJSONObject(i).getString("name"), null);
774                             userRoleDetailList.add(userRoleDetail);
775                         }
776
777                     }
778                 }
779             }
780
781             List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
782                 userRoleDetailList, app);
783
784             List<EcompUserAppRoles> userAppList;
785             // If request coming from portal not from external role approval system then we have to check if user already
786             // have account admin or system admin as GUI will not send these roles
787             if (!isPortalRequest) {
788                 FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
789                 userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
790                 if (!roleInAppUser.isEmpty()) {
791                     for (EcompUserAppRoles userApp : userAppList) {
792                         if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
793                             || userApp.getRoleId()
794                             .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
795                             RoleInAppForUser addSpecialRole = new RoleInAppForUser();
796                             addSpecialRole.setIsApplied(true);
797                             addSpecialRole.setRoleId(userApp.getRoleId());
798                             addSpecialRole.setRoleName(userApp.getRoleName());
799                             roleInAppUser.add(addSpecialRole);
800                         }
801                     }
802                 }
803             }
804             List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
805                 .collect(Collectors.toList());
806             Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
807             for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
808                 currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
809                     .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
810                         "_"), roleInAppUserNew);
811             }
812             final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
813             for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
814                 currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
815             }
816
817             if (isLoggedInUserRoleAdminofApp) {
818                 if (deletedRolesByApprover.size() > 0) {
819                     List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
820                     for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
821                         for (EcompRole role : deletedRolesByApprover) {
822                             if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
823                                 .equals(role.getName())) {
824                                 newUpdatedRoles.add(userRole);
825                             }
826                         }
827                     }
828                     if (newUpdatedRoles.size() > 0) {
829                         userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
830                     } else {
831                         userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
832                         currentUserRolesToUpdate = new HashMap<>();
833
834                     }
835
836                 } else {
837                     userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
838                     currentUserRolesToUpdate = new HashMap<>();
839
840                 }
841             }
842
843             // Check if user roles does not exists in local but still there in External Central Auth System delete them all
844             for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
845                 if (!(currentUserRolesToUpdate
846                     .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
847                     HttpEntity<String> entity = new HttpEntity<>(headers);
848                     logger.debug(EELFLoggerDelegate.debugLogger,
849                         "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
850                         userRole.getName());
851                     ResponseEntity<String> deleteResponse = template.exchange(
852                         SystemProperties
853                             .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
854                             + "userRole/" + name + "/" + userRole.getName(),
855                         HttpMethod.DELETE, entity, String.class);
856                     logger.debug(EELFLoggerDelegate.debugLogger,
857                         "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
858                         userRole.getName(), deleteResponse.getBody());
859                 }
860             }
861             // Check if user roles does not exists in External Central Auth System add them all
862             for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
863                 if (!(currentUserRolesInExternalSystem
864                     .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
865                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
866                         "_")))) {
867                     ExternalAccessUser extUser = new ExternalAccessUser(name,
868                         app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
869                             EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
870                             "_"));
871                     String formattedUserRole = mapper.writeValueAsString(extUser);
872                     HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
873                     logger.debug(EELFLoggerDelegate.debugLogger,
874                         "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
875                         name, addUserRole.getRoleName());
876                     ResponseEntity<String> addResponse = template
877                         .exchange(SystemProperties
878                             .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
879                             + "userRole", HttpMethod.POST, entity, String.class);
880                     logger.debug(EELFLoggerDelegate.debugLogger,
881                         "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
882                         addResponse.getBody(), addUserRole.getRoleName());
883                     if (addResponse.getStatusCode().value() != 201
884                         && addResponse.getStatusCode().value() != 404) {
885                         logger.debug(EELFLoggerDelegate.debugLogger,
886                             "Finished POST operation in external system but unable to save user role",
887                             addResponse.getBody(),
888                             addUserRole.getRoleName());
889                         throw new Exception(addResponse.getBody());
890                     }
891                 }
892             }
893         } catch (HttpClientErrorException e) {
894             logger.error(EELFLoggerDelegate.errorLogger,
895                 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
896                 app.getId(), e);
897             if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
898                 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
899                     orgUserId);
900                 throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
901                     "Please enter the valid systemUser");
902             }
903             if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
904                 logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
905                 throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
906             }
907             EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
908             throw e;
909         } catch (Exception e) {
910             logger.error(EELFLoggerDelegate.errorLogger,
911                 "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
912                 app.getId(), e);
913             EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
914             throw e;
915         }
916     }
917
918     private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
919         List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
920         Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
921         //Add Account Admin role for partner app to prevent conflict
922         if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
923             FnRole role = new FnRole();
924             role.setRoleName(PortalConstants.ADMIN_ROLE
925                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
926             epRoleList.put(role.getRoleName(), role);
927         }
928         userRoleDetailList.removeIf(
929             userRoleDetail -> !epRoleList
930                 .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
931         return userRoleDetailList;
932     }
933
934     private List<FnUser> checkIfUserExists(String userParams) {
935         return fnUserService.getUserWithOrgUserId(userParams);
936     }
937
938     @Transactional
939     private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
940         if (StringUtils.isEmpty(userId)) {
941             logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
942             return;
943         }
944         try {
945             List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
946             if (userList.size() == 0) {
947                 FnUser client;
948                 if (!isSystemUser) {
949                     client = fnUserService.loadUserByUsername(userId);
950                 } else {
951                     client = new FnUser();
952                     client.setOrgUserId(userId);
953                     client.setIsSystemUser(true);
954                     client.setFirstName(userId.substring(0, userId.indexOf("@")));
955                 }
956                 if (client == null) {
957                     String msg = "createLocalUserIfNecessary: cannot create user " + userId
958                         + ", because not found in phonebook";
959                     logger.error(EELFLoggerDelegate.errorLogger, msg);
960                 } else {
961                     client.setLoginId(userId);
962                     client.setActiveYn(true);
963                 }
964                 fnUserService.saveFnUser(client);
965             }
966         } catch (Exception e) {
967             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
968         }
969
970     }
971
972     private FnUser checkIfRemoteUserExits(String userId, FnApp app,
973         ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
974         FnUser checkRemoteUser = null;
975         try {
976             checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
977         } catch (HTTPException e) {
978             // Some apps are returning 400 if user is not found.
979             if (e.getResponseCode() == 400) {
980                 logger.debug(EELFLoggerDelegate.debugLogger,
981                     "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
982                     e);
983             } else if (e.getResponseCode() == 404) {
984                 logger.debug(EELFLoggerDelegate.debugLogger,
985                     "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
986                     e);
987             } else {
988                 // Other response code, let it come thru.
989                 throw e;
990             }
991         }
992         return checkRemoteUser;
993     }
994
995     private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
996         throws HTTPException {
997         if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
998             List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
999             if (userList != null && !userList.isEmpty()) {
1000                 return userList.get(0);
1001             } else {
1002                 return null;
1003             }
1004         }
1005         return getUser(userId, app, applicationsRestClientService);
1006     }
1007
1008     private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
1009         boolean externalSystemRequest, String reqType, boolean isSystemUser,
1010         Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
1011         boolean result = false;
1012         String userId = rolesInAppForUser.getOrgUserId();
1013         Long appId = rolesInAppForUser.getAppId();
1014         synchronized (syncRests) {
1015             createLocalUserIfNecessary(userId, isSystemUser);
1016
1017             EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1018             for (int i = 0;
1019                 i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1020                 RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1021                 EcompRole role = new EcompRole();
1022                 role.setId(roleInAppForUser.getRoleId());
1023                 role.setName(roleInAppForUser.getRoleName());
1024                 userAppRoles[i] = role;
1025             }
1026             try {
1027                 EcompRole[] applicationRoles = null;
1028
1029                 if (isLoggedInUserRoleAdminOfApp) {
1030                     List<EcompRole> roles = Arrays.stream(userAppRoles)
1031                         .collect(Collectors.toList());
1032                     List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1033                     roles.addAll(roles1);
1034                     applicationRoles = roles.toArray(new EcompRole[0]);
1035                 }
1036
1037                 syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1038                     reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1039                 result = true;
1040             } catch (Exception e) {
1041                 logger.error(EELFLoggerDelegate.errorLogger,
1042                     "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1043                         + userId, e);
1044                 if ("DELETE".equals(reqType)) {
1045                     throw new Exception(e.getMessage());
1046                 }
1047             }
1048         }
1049         return result;
1050     }
1051
1052     private void syncUserRoles(String userId, Long appId,
1053         EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1054         EcompRole[] appRoles) throws Exception {
1055
1056         Transaction transaction = null;
1057         String roleActive;
1058         HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1059         List<FnRole> roleInfo = externalAccessRolesService
1060             .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1061         FnRole adminRole = new FnRole();
1062         if (roleInfo.size() > 0) {
1063             adminRole = roleInfo.get(0);
1064             logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1065         }
1066         try {
1067             List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1068             if (userList.size() > 0) {
1069                 FnUser client = userList.get(0);
1070                 roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1071                 List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1072                 entityManager
1073                     .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1074                     .setParameter("appId", appId)
1075                     .setParameter("userId", client.getId())
1076                     .getResultList();
1077
1078                 if ("DELETE".equals(reqType)) {
1079                     for (FnUserRole userAppRoleList : userRoles) {
1080                         List<FnRole> rolesList =
1081                             (!userAppRoleList.getRoleId().getRoleName()
1082                                 .equals(adminRole.getRoleName()))
1083                                 ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1084                                 (userAppRoleList.getRoleId().getRoleName(), appId)
1085                                 : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1086                         if (!rolesList.isEmpty()) {
1087                             checkIfRoleInactive(rolesList.get(0));
1088                         }
1089                     }
1090                 }
1091
1092                 if (appRoles != null) {
1093                     List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1094                     List<FnUserRole> finalUserRolesList = new ArrayList<>();
1095                     if (checkIfUserisRoleAdmin) {
1096                         for (EcompRole role : appRolesList) {
1097                             for (FnUserRole userAppRoleList : userRoles) {
1098                                 if (userAppRoleList.getRoleId().getRoleName()
1099                                     .equals(role.getName())) {
1100                                     finalUserRolesList.add(userAppRoleList);
1101                                 }
1102
1103                             }
1104                         }
1105                         userRoles = new ArrayList<>(finalUserRolesList);
1106                     }
1107                 }
1108
1109                 for (FnUserRole userRole : userRoles) {
1110                     if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1111                         && !PortalConstants.SYS_ADMIN_ROLE_ID
1112                         .equals(userRole.getRoleId().getId())
1113                         && !extRequestValue) {
1114                         syncUserRolesExtension(userRole, appId,
1115                             newUserAppRolesMap);
1116                     } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1117                         || "DELETE".equals(reqType))) {
1118                         syncUserRolesExtension(userRole, appId,
1119                             newUserAppRolesMap);
1120                     } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1121                         .equals(userRole.getRoleId().getId())) {
1122                         syncUserRolesExtension(userRole, appId,
1123                             newUserAppRolesMap);
1124                     }
1125                 }
1126
1127                 Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1128                 if (newRolesToAdd.size() > 0) {
1129                     FnApp app = fnAppService.getById(appId);
1130
1131                     HashMap<Long, FnRole> rolesMap = new HashMap<>();
1132                     if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1133                         String appIdValue = "";
1134                         if (!extRequestValue) {
1135                             appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1136                         }
1137                         @SuppressWarnings("unchecked")
1138                         List<FnRole> roles = entityManager
1139                             .createQuery(
1140                                 "from " + FnRole.class.getName() + " where appId is null "
1141                                     + appIdValue).getResultList();
1142                         for (FnRole role : roles) {
1143                             role.setAppId(1L);
1144                             rolesMap.put(role.getId(), role);
1145                         }
1146                     } else { // remote app
1147                         @SuppressWarnings("unchecked")
1148                         List<FnRole> roles = entityManager
1149                             .createQuery("from EPRole where appId=:appId")
1150                             .setParameter("appId", appId)
1151                             .getResultList();
1152                         for (FnRole role : roles) {
1153                             if (!extRequestValue && app.getAuthCentral()) {
1154                                 rolesMap.put(role.getId(), role);
1155                             } else {
1156                                 rolesMap.put(role.getAppRoleId(), role);
1157                             }
1158                         }
1159                     }
1160
1161                     FnRole role;
1162                     for (EcompRole userRole : newRolesToAdd) {
1163                         FnUserRole userApp = new FnUserRole();
1164                         if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1165                             .equals(adminRole.getRoleName())) {
1166                             role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1167                             userApp.setRoleId(role);
1168                         } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1169                             && !extRequestValue) {
1170                             continue;
1171                         } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1172                             .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1173                             continue;
1174                         } else {
1175                             userApp.setRoleId(rolesMap.get(userRole.getId()));
1176                         }
1177
1178                         userApp.setUserId(client);
1179                         userApp.setFnAppId(app);
1180                         fnUserRoleService.saveOne(userApp);
1181                     }
1182
1183                     if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1184                         /*
1185                          * for local app -- hack - always make sure fn_role
1186                          * table's app_id is null and not 1 for primary app in
1187                          * this case being onap portal app; reason: hibernate
1188                          * is rightly setting this to 1 while persisting to
1189                          * fn_role as per the mapping but SDK role management
1190                          * code expects the app_id to be null as there is no
1191                          * concept of App_id in SDK
1192                          */
1193                         Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1194                         query.executeUpdate();
1195                     }
1196                 }
1197             }
1198             transaction.commit();
1199         } catch (Exception e) {
1200             logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1201             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1202             EcompPortalUtils.rollbackTransaction(transaction,
1203                 "Exception occurred in syncUserRoles, Details: " + e.toString());
1204             if ("DELETE".equals(reqType)) {
1205                 throw new SyncUserRolesException(e.getMessage());
1206             }
1207         }
1208     }
1209
1210     private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1211         HashMap<Long, EcompRole> result = new HashMap<>();
1212         if (ecompRoles != null) {
1213             for (EcompRole ecompRole : ecompRoles) {
1214                 if (ecompRole.getId() != null) {
1215                     result.put(ecompRole.getId(), ecompRole);
1216                 }
1217             }
1218         }
1219         return result;
1220     }
1221
1222     private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1223         HashMap<Long, EcompRole> newUserAppRolesMap) {
1224
1225         Long userAppRoleId;
1226         if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1227             userAppRoleId = userRole.getRoleId().getId();
1228         } else { // remote app
1229             userAppRoleId = userRole.getId();
1230         }
1231
1232         if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1233             fnUserRoleService.deleteById(userRole.getId());
1234         } else {
1235             newUserAppRolesMap.remove(userAppRoleId);
1236         }
1237     }
1238
1239     private Role fnRoleToRole(final FnRole role) {
1240         return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null,
1241             role.getActiveYn(),
1242             role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1243     }
1244
1245     @SuppressWarnings("unchecked")
1246     public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue,
1247         Long userId) {
1248         List<RoleInAppForUser> rolesInAppForUser = null;
1249         FnApp app = fnAppService.getById(appId);
1250         logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1251         try {
1252             // for onap portal app, no need to make a remote call
1253             List<Role> roleList = new ArrayList<>();
1254             if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1255                 if (app.getAuthCentral()) {
1256                     List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1257                     for (CentralV2Role cenRole : cenRoleList) {
1258                         Role role = new Role();
1259                         role.setActiveYn(cenRole.isActive());
1260                         role.setId(cenRole.getId());
1261                         role.setRoleName(cenRole.getName());
1262                         role.setPriority(cenRole.getPriority());
1263                         roleList.add(role);
1264                     }
1265                 } else {
1266                     Optional<FnUser> user = fnUserService.getUser(userId);
1267                     if (user.isPresent()) {
1268                         roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole)
1269                             .collect(Collectors.toList());
1270                     }
1271                 }
1272                 List<Role> activeRoleList = new ArrayList<>();
1273                 for (Role role : roleList) {
1274                     if (role.getActiveYn()) {
1275                         if (role.getId() != 1) { // prevent portal admin from being added
1276                             activeRoleList.add(role);
1277                         } else if (extRequestValue) {
1278                             activeRoleList.add(role);
1279                         }
1280                     }
1281
1282                 }
1283                 FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1284                 // If localUser does not exists return roles
1285                 Set<FnRole> roleSet = null;
1286                 FnRole[] roleSetList = null;
1287                 if (localUser != null) {
1288                     roleSet = localUser.getAppEPRoles(app);
1289                     roleSetList = roleSet.toArray(new FnRole[0]);
1290                 }
1291                 rolesInAppForUser = fnUserRoleService
1292                     .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1293                 return rolesInAppForUser;
1294             }
1295
1296             EcompRole[] appRoles = null;
1297             boolean checkIfUserIsApplicationAccAdmin = false;
1298             List<EcompRole> roles = new ArrayList<>();
1299             if (app.getAuthCentral()) {
1300                 List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1301                 FnApp application = fnAppService.getById(appId);
1302                 checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1303                     application);
1304
1305                 List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1306                 for (FnRole role : applicationRoles) {
1307                     List<EpAppFunction> cenRoleFuncList = epAppFunctionService
1308                         .getAppRoleFunctionList(role.getId(), app.getId());
1309                     for (EpAppFunction roleFunc : cenRoleFuncList) {
1310
1311                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1312                         functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1313                         String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1314                         String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1315                         String name = roleFunc.getFunctionName();
1316
1317                         FnFunction function = new FnFunction();
1318                         function.setAction(action);
1319                         function.setType(type);
1320                         function.setCode(functionCode);
1321                         function.setName(name);
1322                         role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1323
1324                     }
1325                     roleSetWithFunctioncds.add(role);
1326
1327
1328                 }
1329
1330                 for (FnRole role1 : roleSetWithFunctioncds) {
1331                     EcompRole ecompRole = new EcompRole();
1332                     ecompRole.setId(role1.getId());
1333                     ecompRole.setName(role1.getRoleName());
1334                     ecompRole.setRoleFunctions(role1.getRoleFunctions());
1335                     roles.add(ecompRole);
1336
1337                 }
1338                 if (checkIfUserIsApplicationAccAdmin) {
1339                     appRoles = roles.toArray(new EcompRole[roles.size()]);
1340                     logger.debug(EELFLoggerDelegate.debugLogger,
1341                         "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}",
1342                         appRoles);
1343                 } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1344                     List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1345                     List<String> roleAdminAppRolesNames = new ArrayList<>();
1346                     String QUERY =
1347                         "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1348                             + " where fu.role_id = ep.role_id"
1349                             + " and fu.app_id = ep.app_id"
1350                             + " and fu.user_id = :userId"
1351                             + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1352                             + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1353                             + " and exists"
1354                             + " ("
1355                             + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id"
1356                             + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1357                     List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1358                         .setParameter("userId", userId)
1359                         .getResultList();
1360                     List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1361                         .collect(Collectors.toList());
1362
1363                     List<EcompRole> userapproverRolesList = new ArrayList<>();
1364                     for (String str : getUserApproverRoles) {
1365                         EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1366                         if (epRole != null) {
1367                             userapproverRolesList.add(epRole);
1368                         }
1369                     }
1370                     for (EcompRole role : userapproverRolesList) {
1371
1372                         List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1373                         boolean checkIfFunctionsExits = roleFunList.stream()
1374                             .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1375                         if (checkIfFunctionsExits) {
1376                             roleAdminAppRoles.add(role);
1377                             List<RoleFunction> filteredList = roleFunList.stream()
1378                                 .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1379                             roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1380                                 .collect(Collectors.toList()));
1381                         }
1382                     }
1383                     for (String name : roleAdminAppRolesNames) {
1384                         roles.stream().filter(x -> name.equals(x.getName())).findAny()
1385                             .ifPresent(roleAdminAppRoles::add);
1386
1387                     }
1388                     appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1389
1390                 }
1391             } else {
1392                 appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1393             }
1394             // Test this error case, for generating an internal ONAP Portal
1395             // error
1396             // EcompRole[] appRoles = null;
1397             // If there is an exception in the rest client api, then null will
1398             // be returned.
1399             if (appRoles != null) {
1400                 if (!app.getAuthCentral()) {
1401                     syncAppRoles(appId, appRoles);
1402                 }
1403                 EcompRole[] userAppRoles = null;
1404                 try {
1405                     try {
1406                         if (app.getAuthCentral()) {
1407                             List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1408                             List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1409                                 .createNamedQuery("EPUserAppCurrentRoles")
1410                                 .setParameter("appId", app.getId())
1411                                 .setParameter("userId", actualUser.get(0).getId())
1412                                 .getResultList();
1413                             List<EcompRole> setUserRoles = new ArrayList<>();
1414                             for (EPUserAppCurrentRoles role : userAppsRolesList) {
1415                                 logger.debug(EELFLoggerDelegate.debugLogger,
1416                                     "In getAppRolesForUser() - userAppsRolesList get userRolename = {}",
1417                                     role.getRoleName());
1418                                 EcompRole ecompRole = new EcompRole();
1419                                 ecompRole.setId(role.getRoleId());
1420                                 ecompRole.setName(role.getRoleName());
1421                                 setUserRoles.add(ecompRole);
1422                             }
1423
1424                             boolean checkIfUserisAccAdmin = setUserRoles.stream()
1425                                 .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1426
1427                             if (!checkIfUserisAccAdmin) {
1428                                 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1429                                 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1430
1431                                 List<String> roleNames = new ArrayList<>();
1432                                 for (EcompRole role : setUserRoles) {
1433                                     EcompRole epRole = appRolesList.stream()
1434                                         .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1435                                     List<RoleFunction> roleFunList = new ArrayList<>();
1436
1437                                     if (epRole != null) {
1438                                         if (epRole.getRoleFunctions().size() > 0) {
1439                                             roleFunList.addAll(epRole.getRoleFunctions());
1440                                         }
1441                                         boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1442                                             roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1443                                         if (checkIfFunctionsExits) {
1444                                             finalUserAppRolesList.add(role);
1445                                             List<RoleFunction> filteredList = roleFunList.stream()
1446                                                 .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1447                                                 .collect(Collectors.toList());
1448                                             roleNames = filteredList.stream().map(RoleFunction::getCode)
1449                                                 .collect(Collectors.toList());
1450                                         } else {
1451                                             roleNames.add(epRole.getName());
1452                                         }
1453                                     }
1454                                     for (String name : roleNames) {
1455                                         EcompRole ecompRole = appRolesList.stream()
1456                                             .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1457                                         if (ecompRole != null) {
1458                                             finalUserAppRolesList.add(ecompRole);
1459                                         }
1460                                     }
1461                                 }
1462                                 for (String name : roleNames) {
1463                                     boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1464                                         role -> role.getRoleName().equalsIgnoreCase(name));
1465                                     if (checkIfFunctionsExits) {
1466                                         appRolesList.stream().filter(x -> name.equals(x.getName()))
1467                                             .findAny().ifPresent(setUserRoles::add);
1468                                     }
1469                                 }
1470                                 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1471                             }
1472                         } else {
1473                             userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1474                                 String.format("/user/%s/roles", userId));
1475                         }
1476                     } catch (HTTPException e) {
1477                         // Some apps are returning 400 if user is not found.
1478                         if (e.getResponseCode() == 400) {
1479                             logger.debug(EELFLoggerDelegate.debugLogger,
1480                                 "getAppRolesForUser caught exception with response code 400; continuing", e);
1481                         } else {
1482                             // Other response code, let it come thru.
1483                             throw e;
1484                         }
1485                     }
1486                     if (userAppRoles == null) {
1487                         if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1488                             EcompPortalUtils.setExternalAppResponseCode(200);
1489                             String message = String.format(
1490                                 "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1491                                     + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1492                                     + "Overriding to 200 until framework SDK returns a useful response.",
1493                                 Long.toString(appId), userId);
1494                             logger.warn(EELFLoggerDelegate.applicationLogger, message);
1495                         }
1496                     }
1497
1498                     HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1499                     ArrayList<EcompRole> activeRoles = new ArrayList<>();
1500                     if (userAppRoles != null) {
1501                         for (EcompRole userAppRole : userAppRoles) {
1502                             if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1503                                 EcompRole role = new EcompRole();
1504                                 role.setId(userAppRole.getId());
1505                                 role.setName(userAppRole.getName());
1506                                 activeRoles.add(role);
1507                             }
1508                         }
1509                     }
1510                     EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1511
1512                     boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1513
1514                     // If the remote application isn't down we MUST sync user
1515                     // roles here in case we have this user here!
1516                     syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null,
1517                         checkIfUserisRoleAdmin,
1518                         appRoles);
1519                 } catch (Exception e) {
1520                     // TODO: we may need to check if user exists, maybe remote
1521                     // app is down.
1522                     String message = String.format(
1523                         "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1524                         Long.toString(appId));
1525                     logger.error(EELFLoggerDelegate.errorLogger, message, e);
1526                     userAppRoles = new EcompRole[0];
1527                 }
1528                 rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1529             }
1530         } catch (Exception e) {
1531             String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1532                 Long.toString(appId));
1533             logger.error(EELFLoggerDelegate.errorLogger, message, e);
1534         }
1535         return rolesInAppForUser;
1536     }
1537
1538     private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1539         logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1540         HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1541         try {
1542             List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1543
1544             List<FnRole> obsoleteRoles = new ArrayList<>();
1545             for (FnRole oldAppRole : currentAppRoles) {
1546                 if (oldAppRole.getAppRoleId() != null) {
1547                     EcompRole role;
1548                     role = newRolesMap.get(oldAppRole.getAppRoleId());
1549                     if (role != null) {
1550                         if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1551                             oldAppRole.setRoleName(role.getName());
1552                         }
1553                         oldAppRole.setActiveYn(true);
1554                         newRolesMap.remove(oldAppRole.getAppRoleId());
1555                     } else {
1556                         obsoleteRoles.add(oldAppRole);
1557                     }
1558                 } else {
1559                     obsoleteRoles.add(oldAppRole);
1560                 }
1561             }
1562             Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1563             if (obsoleteRoles.size() > 0) {
1564                 logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1565                 for (FnRole role : obsoleteRoles) {
1566                     logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1567                     Long roleId = role.getId();
1568                     List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1569
1570                     logger.debug(EELFLoggerDelegate.debugLogger,
1571                         "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1572                     for (FnUserRole userRole : userRoles) {
1573                         logger.debug(EELFLoggerDelegate.debugLogger,
1574                             "syncAppRoles: about to delete userRole: " + userRole.toString());
1575                         fnUserRoleService.deleteById(userRole.getId());
1576                         logger.debug(EELFLoggerDelegate.debugLogger,
1577                             "syncAppRoles: finished deleting userRole: " + userRole.toString());
1578                     }
1579                     List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1580                     int numMenuRoles = funcMenuRoles.size();
1581                     logger.debug(EELFLoggerDelegate.debugLogger,
1582                         "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1583                     for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1584                         Long menuId = funcMenuRole.getMenuId().getMenuId();
1585                         // If this is the only role for this menu item, then the
1586                         // app and roles will be gone,
1587                         // so must null out the url too, to be consistent
1588                         List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService
1589                             .retrieveByMenuId(menuId);
1590                         int numMenuRoles2 = funcMenuRoles2.size();
1591                         logger.debug(EELFLoggerDelegate.debugLogger,
1592                             "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1593                         fnMenuFunctionalRolesService.delete(funcMenuRole);
1594
1595                         if (numMenuRoles2 == 1) {
1596                             // If this is the only role for this menu item, then
1597                             // the app and roles will be gone,
1598                             // so must null out the url too, to be consistent
1599                             logger.debug(EELFLoggerDelegate.debugLogger,
1600                                 "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1601                             List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1602                             if (funcMenuItems.size() > 0) {
1603                                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1604                                 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1605                                 funcMenuItem.setUrl("");
1606                             }
1607                         }
1608                     }
1609                     boolean isPortalRequest = true;
1610                     deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1611                     logger.debug(EELFLoggerDelegate.debugLogger,
1612                         "syncAppRoles: about to delete the role: " + role.toString());
1613                     fnRoleService.delete(role);
1614                     logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1615                 }
1616             }
1617             for (EcompRole role : newRolesToAdd) {
1618                 logger.debug(EELFLoggerDelegate.debugLogger,
1619                     "syncAppRoles: about to add missing role: " + role.toString());
1620                 FnRole newRole = new FnRole();
1621                 // Attention! All roles from remote application supposed to be
1622                 // active!
1623                 newRole.setActiveYn(true);
1624                 newRole.setRoleName(role.getName());
1625                 newRole.setAppId(appId);
1626                 newRole.setAppRoleId(role.getId());
1627                 fnRoleService.saveOne(newRole);
1628             }
1629             logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1630             logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1631         } catch (Exception e) {
1632             logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1633             EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1634             throw new Exception(e);
1635         }
1636     }
1637
1638     private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1639         throws Exception {
1640         Session localSession = entityManager.unwrap(Session.class);
1641         try {
1642             String sql;
1643             Query query;
1644             // It should delete only when it portal's roleId
1645             if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1646                 // Delete from fn_role_function
1647                 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1648                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1649                 query = localSession.createSQLQuery(sql);
1650                 query.executeUpdate();
1651                 // Delete from fn_role_composite
1652                 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1653                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1654                 query = localSession.createSQLQuery(sql);
1655                 query.executeUpdate();
1656             }
1657             // Delete from ep_app_role_function
1658             sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1659             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1660             query = localSession.createSQLQuery(sql);
1661             query.executeUpdate();
1662             // Delete from ep_role_notification
1663             sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1664             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1665             query = localSession.createSQLQuery(sql);
1666             query.executeUpdate();
1667             // Delete from fn_user_pseudo_role
1668             sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1669             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1670             query = localSession.createSQLQuery(sql);
1671             query.executeUpdate();
1672             // Delete form EP_WIDGET_CATALOG_ROLE
1673             sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1674             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1675             query = localSession.createSQLQuery(sql);
1676             query.executeUpdate();
1677             // Delete form EP_WIDGET_CATALOG_ROLE
1678             sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1679             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1680             query = localSession.createSQLQuery(sql);
1681             query.executeUpdate();
1682             if (!isPortalRequest) {
1683                 // Delete form fn_menu_functional_roles
1684                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1685                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1686                 query = localSession.createSQLQuery(sql);
1687                 query.executeUpdate();
1688             }
1689         } catch (Exception e) {
1690             logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1691             throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1692         }
1693     }
1694
1695     private void checkIfRoleInactive(FnRole epRole) throws Exception {
1696         if (!epRole.getActiveYn()) {
1697             throw new Exception(epRole.getRoleName() + " role is unavailable");
1698         }
1699     }
1700
1701     public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1702         boolean result = false;
1703         // No changes if no new roles list or no userId.
1704         if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1705             && newAppsListWithAdminRoles.getAppsRoles() != null) {
1706             synchronized (syncRests) {
1707                 List<FnApp> apps = fnAppService.getAppsFullList();
1708                 HashMap<Long, FnApp> enabledApps = new HashMap<>();
1709                 for (FnApp app : apps) {
1710                     enabledApps.put(app.getId(), app);
1711                 }
1712                 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1713                 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1714                     // user Admin role may be added only for enabled apps
1715                     if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1716                         newAppsWhereUserIsAdmin.add(adminRole);
1717                     }
1718                 }
1719                 FnUser user = null;
1720                 boolean createNewUser = false;
1721                 String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1722                 List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1723                 List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1724                 if (localUserList.size() > 0) {
1725                     FnUser tmpUser = localUserList.get(0);
1726                     oldAppsWhereUserIsAdmin = fnUserRoleService
1727                         .retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1728                     if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1729                         user = tmpUser;
1730                     }
1731                 } else if (newAppsWhereUserIsAdmin.size() > 0) {
1732                     // we create new user only if he has Admin Role for any App
1733                     createNewUser = true;
1734                 }
1735                 result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1736                     oldAppsWhereUserIsAdmin);
1737             }
1738         }
1739
1740         return result;
1741     }
1742
1743     @Transactional
1744     public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1745         List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1746         List<FnUserRole> oldAppsWhereUserIsAdmin) {
1747         if (user != null || createNewUser) {
1748             if (createNewUser) {
1749                 user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1750                 if (user != null) {
1751                     user.setActiveYn(true);
1752                 }
1753             }
1754             for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1755                 // user Admin role may be deleted only for enabled
1756                 // apps
1757                 if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1758                     fnUserRoleService.saveOne(oldUserApp);
1759                 }
1760             }
1761             for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1762                 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1763                 FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1764                 FnUserRole newUserApp = new FnUserRole();
1765                 newUserApp.setUserId(user);
1766                 newUserApp.setFnAppId(app);
1767                 newUserApp.setRoleId(role);
1768                 fnUserRoleService.saveOne(newUserApp);
1769             }
1770             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1771                 addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1772                 result = true;
1773             }
1774         }
1775         return result;
1776     }
1777
1778     public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1779         boolean result = false;
1780         try {
1781             // Reset All admin role for centralized applications
1782             List<FnApp> appList = fnAppService.getCentralizedApps();
1783             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1784             for (FnApp app : appList) {
1785                 String name = "";
1786                 if (EPCommonSystemProperties
1787                     .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1788                     name = user.getOrgUserId() + SystemProperties
1789                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1790                 }
1791                 String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1792                 HttpEntity<String> entity = new HttpEntity<>(headers);
1793                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1794                 try {
1795                     ResponseEntity<String> getResponse = template
1796                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1797                             + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1798
1799                     if (getResponse.getBody().equals("{}")) {
1800                         String addDesc = "{\"name\":\"" + extRole + "\"}";
1801                         HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1802                         template.exchange(
1803                             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1804                                 + "role",
1805                             HttpMethod.POST, roleEntity, String.class);
1806                     } else {
1807                         try {
1808                             HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1809                             template.exchange(
1810                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1811                                     + "userRole/" + name + "/" + extRole,
1812                                 HttpMethod.DELETE, deleteUserRole, String.class);
1813                         } catch (Exception e) {
1814                             logger.error(EELFLoggerDelegate.errorLogger,
1815                                 " Role not found for this user may be it gets deleted before", e);
1816                         }
1817                     }
1818                 } catch (Exception e) {
1819                     if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1820                         logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1821                             app.getAuthNamespace(), e.getMessage());
1822                     } else {
1823                         logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1824                             app.getAuthNamespace(), e);
1825                     }
1826                 }
1827             }
1828             for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1829                 FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1830                 try {
1831                     if (app.getAuthCentral()) {
1832                         String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1833                         HttpEntity<String> entity = new HttpEntity<>(headers);
1834                         String name = "";
1835                         if (EPCommonSystemProperties
1836                             .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1837                             name = user.getOrgUserId() + SystemProperties
1838                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1839                         }
1840                         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1841                         ResponseEntity<String> getUserRolesResponse = template.exchange(
1842                             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1843                                 + "userRoles/user/" + name,
1844                             HttpMethod.GET, entity, String.class);
1845                         logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1846                         if (!getUserRolesResponse.getBody().equals("{}")) {
1847                             JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1848                             JSONArray extRoles = jsonObj.getJSONArray("userRole");
1849                             final Map<String, JSONObject> extUserRoles = new HashMap<>();
1850                             for (int i = 0; i < extRoles.length(); i++) {
1851                                 String userRole = extRoles.getJSONObject(i).getString("role");
1852                                 if (userRole.startsWith(app.getAuthNamespace() + ".")
1853                                     && !userRole.equals(app.getAuthNamespace() + ".admin")
1854                                     && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1855
1856                                     extUserRoles.put(userRole, extRoles.getJSONObject(i));
1857                                 }
1858                             }
1859                             if (!extUserRoles.containsKey(extRole)) {
1860                                 // Assign with new apps user admin
1861                                 try {
1862                                     ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1863                                     // Assign user role for an application in external access system
1864                                     ObjectMapper addUserRoleMapper = new ObjectMapper();
1865                                     String userRole = addUserRoleMapper.writeValueAsString(extUser);
1866                                     HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1867                                     template.exchange(
1868                                         SystemProperties.getProperty(
1869                                             EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1870                                         HttpMethod.POST, addUserRole, String.class);
1871                                 } catch (Exception e) {
1872                                     logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1873                                 }
1874
1875                             }
1876                         }
1877                     }
1878                     result = true;
1879                 } catch (Exception e) {
1880                     if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1881                         logger.debug(EELFLoggerDelegate.errorLogger,
1882                             "Application name space not found in External system for app {} due to bad rquest name space ",
1883                             app.getAuthNamespace(), e.getMessage());
1884                     } else {
1885                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1886                             app.getAuthNamespace(), e);
1887                         result = false;
1888                     }
1889                 }
1890             }
1891         } catch (Exception e) {
1892             result = false;
1893             logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
1894         }
1895         return result;
1896     }
1897
1898     public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
1899         final String getAllAppsFunctionsOfUser =
1900             "select distinct ep.function_cd from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_app fa , fn_role fr\n"
1901                 + "         where fu.role_id = ep.role_id \n"
1902                 + "         and fu.app_id = ep.app_id\n"
1903                 + "         and fu.user_id =:userId\n"
1904                 + "         and ea.function_cd = ep.function_cd\n"
1905                 + "            and ((fu.app_id = fa.app_id  and fa.enabled = 'Y' ) or (fa.app_id = 1))\n"
1906                 + "            and fr.role_id = fu.role_id and fr.active_yn='Y' \n"
1907                 + "          union\n"
1908                 + "            select distinct app_r_f.function_cd from ep_app_role_function app_r_f, ep_app_function a_f\n"
1909                 + "         where role_id = 999\n"
1910                 + "         and app_r_f.function_cd = a_f.function_cd\n"
1911                 + "         and exists\n"
1912                 + "         (\n"
1913                 + "         select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id\n"
1914                 + "         and ur.role_id = 999 and ur.app_id = fa.app_id and fa.enabled = 'Y'\n"
1915                 + "         )";
1916         List getRoleFuncListOfPortal = entityManager.createNativeQuery(getAllAppsFunctionsOfUser)
1917             .setParameter("userId", OrgUserId).getResultList();
1918         Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
1919         Set<String> roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
1920             .collect(Collectors.toSet());
1921         if (!roleFunSet.isEmpty()) {
1922             for (String roleFunction : roleFunSet) {
1923                 String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
1924                 getRoleFuncListOfPortalSet.remove(roleFunction);
1925                 getRoleFuncListOfPortalSet.add(roleFun);
1926             }
1927         }
1928
1929         Set<String> finalRoleFunctionSet = new HashSet<>();
1930         for (String roleFn : getRoleFuncListOfPortalSet) {
1931             finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
1932         }
1933
1934         return finalRoleFunctionSet;
1935     }
1936
1937     public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
1938             AppsListWithAdminRole appsListWithAdminRole = null;
1939
1940             try {
1941                 List<FnUser> userList = fnUserService.getUserWithOrgUserId(orgUserId);
1942                 HashMap<Long, Long> appsUserAdmin = new HashMap<>();
1943                 if (userList!= null && userList.size() > 0) {
1944                     FnUser user = userList.get(0);
1945                     List<FnUserRole> userAppList = new ArrayList<>();
1946                     try {
1947                         userAppList = fnUserRoleService.retrieveByUserIdAndRoleId(user.getId(), ACCOUNT_ADMIN_ROLE_ID);
1948                     } catch (Exception e) {
1949                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
1950                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
1951                     }
1952                     for (FnUserRole userApp : userAppList) {
1953                         appsUserAdmin.put(userApp.getFnAppId().getId(), userApp.getUserId().getId());
1954                     }
1955                 }
1956
1957                 appsListWithAdminRole = new AppsListWithAdminRole();
1958                 appsListWithAdminRole.setOrgUserId(orgUserId);
1959                 List<FnApp> appsList = new ArrayList<>();
1960                 try {
1961                     appsList = fnAppService.findAll();
1962                 } catch (Exception e) {
1963                     logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
1964                     EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
1965                 }
1966                 for (FnApp app : appsList) {
1967                     AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
1968                     appNameIdIsAdmin.setId(app.getId());
1969                     appNameIdIsAdmin.setAppName(app.getAppName());
1970                     appNameIdIsAdmin.setIsAdmin(appsUserAdmin.containsKey(app.getId()));
1971                     appNameIdIsAdmin.setRestrictedApp(app.isRestrictedApp());
1972                     appsListWithAdminRole.getAppsRoles().add(appNameIdIsAdmin);
1973                 }
1974             } catch (Exception e) {
1975                 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
1976             }
1977             return appsListWithAdminRole;
1978         }
1979 }