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