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