UserRolesController methods 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.Set;
56 import java.util.SortedSet;
57 import java.util.TreeSet;
58 import java.util.stream.Collectors;
59 import javax.persistence.EntityManager;
60 import javax.persistence.Query;
61 import org.apache.commons.lang.StringUtils;
62 import org.apache.cxf.transport.http.HTTPException;
63 import org.hibernate.Session;
64 import org.hibernate.SessionFactory;
65 import org.hibernate.Transaction;
66 import org.json.JSONArray;
67 import org.json.JSONObject;
68 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
69 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
70 import org.onap.portal.domain.db.fn.FnApp;
71 import org.onap.portal.domain.db.fn.FnRole;
72 import org.onap.portal.domain.db.fn.FnUser;
73 import org.onap.portal.domain.db.fn.FnUserRole;
74 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
75 import org.onap.portal.domain.dto.transport.CentralV2Role;
76 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
77 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
78 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
79 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
80 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
81 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
82 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
83 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
84 import org.onap.portal.exception.SyncUserRolesException;
85 import org.onap.portal.logging.format.EPAppMessagesEnum;
86 import org.onap.portal.logging.logic.EPLogUtil;
87 import org.onap.portal.service.ep.EpUserRolesRequestDetService;
88 import org.onap.portal.service.ep.EpUserRolesRequestService;
89 import org.onap.portal.service.fn.FnAppService;
90 import org.onap.portal.service.fn.FnRoleService;
91 import org.onap.portal.service.fn.FnUserRoleService;
92 import org.onap.portal.service.fn.FnUserService;
93 import org.onap.portal.utils.EPCommonSystemProperties;
94 import org.onap.portal.utils.EcompPortalUtils;
95 import org.onap.portal.utils.PortalConstants;
96 import org.onap.portalsdk.core.domain.Role;
97 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
98 import org.onap.portalsdk.core.restful.domain.EcompRole;
99 import org.onap.portalsdk.core.util.SystemProperties;
100 import org.springframework.beans.factory.annotation.Autowired;
101 import org.springframework.http.HttpEntity;
102 import org.springframework.http.HttpHeaders;
103 import org.springframework.http.HttpMethod;
104 import org.springframework.http.HttpStatus;
105 import org.springframework.http.ResponseEntity;
106 import org.springframework.stereotype.Service;
107 import org.springframework.transaction.annotation.Transactional;
108 import org.springframework.web.client.HttpClientErrorException;
109 import org.springframework.web.client.RestTemplate;
110
111 @Service
112 @Transactional
113 public class AdminRolesService {
114
115   private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
116   private static final Object syncRests = new Object();
117   private RestTemplate template = new RestTemplate();
118
119   private final Long SYS_ADMIN_ROLE_ID = 1L;
120   private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
121   private final Long ECOMP_APP_ID = 1L;
122   private final String ADMIN_ACCOUNT = "Is account admin for user {}";
123
124   private final AppsCacheService appsCacheService;
125   private final EntityManager entityManager;
126   private final FnUserService fnUserService;
127   private final FnRoleService fnRoleService;
128   private final FnAppService fnAppService;
129   private final FnUserRoleService fnUserRoleService;
130   private final EcompUserAppRolesService ecompUserAppRolesService;
131   private final ApplicationsRestClientService applicationsRestClientService;
132   private final EpUserRolesRequestDetService epUserRolesRequestDetService;
133   private final ExternalAccessRolesService externalAccessRolesService;
134   private final EpUserRolesRequestService epUserRolesRequestService;
135
136   @Autowired
137   public AdminRolesService(AppsCacheService appsCacheService,
138       final EntityManager entityManager,
139       final FnUserService fnUserService, FnRoleService fnRoleService,
140       FnAppService fnAppService,
141       final FnUserRoleService fnUserRoleService,
142       EcompUserAppRolesService ecompUserAppRolesService,
143       ApplicationsRestClientService applicationsRestClientService,
144       EpUserRolesRequestDetService epUserRolesRequestDetService,
145       ExternalAccessRolesService externalAccessRolesService,
146       EpUserRolesRequestService epUserRolesRequestService) {
147     this.appsCacheService = appsCacheService;
148     this.entityManager = entityManager;
149     this.fnUserService = fnUserService;
150     this.fnRoleService = fnRoleService;
151     this.fnAppService = fnAppService;
152     this.fnUserRoleService = fnUserRoleService;
153     this.ecompUserAppRolesService = ecompUserAppRolesService;
154     this.applicationsRestClientService = applicationsRestClientService;
155     this.epUserRolesRequestDetService = epUserRolesRequestDetService;
156     this.externalAccessRolesService = externalAccessRolesService;
157     this.epUserRolesRequestService = epUserRolesRequestService;
158   }
159
160   public boolean isSuperAdmin(final String orgUserId) {
161     boolean isSuperAdmin;
162     try {
163       isSuperAdmin = fnUserRoleService
164           .isSuperAdmin(orgUserId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
165     } catch (Exception e) {
166       logger.error("isSuperAdmin exception: " + e.toString());
167       throw e;
168     }
169     logger.info("isSuperAdmin " + isSuperAdmin);
170     return isSuperAdmin;
171   }
172
173   public boolean isAccountAdmin(FnUser user) {
174     try {
175       final Map<String, Long> userParams = new HashMap<>();
176       userParams.put("userId", user.getId());
177       logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
178       List<Integer> userAdminApps = getAdminAppsForTheUser(user.getId());
179       logger.debug(EELFLoggerDelegate.debugLogger,
180           "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
181           user.getOrgUserId(), userAdminApps.size());
182
183       if (user.getId() != null) {
184         for (FnUserRole userApp : user.getUserApps()) {
185           if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
186               userAdminApps.size() > 1)) {
187             logger.debug(EELFLoggerDelegate.debugLogger,
188                 "Is account admin for userAdminApps() - for user {}, found Id {}",
189                 user.getOrgUserId(), userApp.getRoleId().getId());
190             return true;
191           }
192         }
193       }
194     } catch (Exception e) {
195       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
196       logger.error(EELFLoggerDelegate.errorLogger,
197           "Exception occurred while executing isAccountAdmin operation",
198           e);
199     }
200     return false;
201   }
202
203   public boolean isUser(FnUser user) {
204     try {
205       FnUser currentUser = fnUserService.getUser(user.getId()).orElseThrow(Exception::new);
206       if (currentUser != null && currentUser.getId() != null) {
207         for (FnUserRole userApp : currentUser.getUserApps()) {
208           if (!userApp.getAppId().getId().equals(ECOMP_APP_ID)) {
209             FnRole role = userApp.getRoleId();
210             if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
211                 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
212               if (role.getActiveYn()) {
213                 return true;
214               }
215             }
216           }
217         }
218       }
219     } catch (Exception e) {
220       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
221       logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
222           e);
223     }
224     return false;
225   }
226
227   public boolean isRoleAdmin(FnUser user) {
228     try {
229       logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
230       List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(user.getId());
231       logger.debug(EELFLoggerDelegate.debugLogger,
232           "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
233       Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
234       Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
235       Set<String> roleFunSet;
236       roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
237           .collect(Collectors.toSet());
238       if (!roleFunSet.isEmpty()) {
239         for (String roleFunction : roleFunSet) {
240           String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
241           getRoleFuncListOfPortalSet1.add(type);
242         }
243       }
244
245       boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
246           .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
247       logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
248           checkIfFunctionsExits);
249
250       return checkIfFunctionsExits;
251
252     } catch (Exception e) {
253       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
254       logger.error(EELFLoggerDelegate.errorLogger,
255           "Exception occurred while executing isRoleAdmin operation",
256           e);
257     }
258     return false;
259   }
260
261   public boolean isAccountAdminOfApplication(FnUser user, FnApp app) {
262     boolean isApplicationAccountAdmin = false;
263     try {
264       logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
265       List<Integer> userAdminApps = getAdminAppsForTheUser(user.getId());
266       if (!userAdminApps.isEmpty()) {
267         isApplicationAccountAdmin = userAdminApps.contains(app.getId());
268         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),
269             app.getId());
270       }
271     } catch (Exception e) {
272       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
273       logger.error(EELFLoggerDelegate.errorLogger,
274           "Exception occurred while executing isAccountAdminOfApplication operation", e);
275     }
276     logger.debug(EELFLoggerDelegate.debugLogger,
277         "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
278         user.getOrgUserId());
279     return isApplicationAccountAdmin;
280
281   }
282
283   private List<Integer> getAdminAppsForTheUser(final Long userId) {
284     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)";
285     return entityManager.createQuery(query, Integer.class)
286         .setParameter("userId", userId).getResultList();
287   }
288
289   public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
290       AppWithRolesForUser newAppRolesForUser) {
291     boolean result = false;
292     boolean epRequestValue = false;
293     String userId = "";
294     String reqMessage = "";
295     if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
296       userId = newAppRolesForUser.getOrgUserId().trim();
297     }
298     Long appId = newAppRolesForUser.getAppId();
299     List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
300
301     if (userId.length() > 0) {
302       ObjectMapper mapper = new ObjectMapper();
303       mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
304
305       try {
306         FnApp app = fnAppService.getById(appId);
307
308         boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user,
309             app);
310         Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
311
312         boolean checkIfUserIsOnlyRoleAdmin =
313             isRoleAdmin(user) && !checkIfUserisApplicationAccAdmin;
314         if (checkIfUserIsOnlyRoleAdmin) {
315           for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
316             if (!roleInAppForUser.getIsApplied()) {
317               EcompRole ecompRole = new EcompRole();
318               ecompRole.setId(roleInAppForUser.getRoleId());
319               ecompRole.setName(roleInAppForUser.getRoleName());
320               rolesGotDeletedFromApprover.add(ecompRole);
321             }
322           }
323         }
324
325         applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
326
327         boolean systemUser = newAppRolesForUser.isSystemUser();
328
329         if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
330             && systemUser) {
331
332           Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
333           RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
334               userRolesInLocalApp);
335           List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
336           Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
337           if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
338             // Apply changes in external Access system
339
340             updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
341                 roleAppUserList,
342                 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
343           }
344           result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
345               "Portal",
346               systemUser, rolesGotDeletedByApprover, false);
347
348         } else if (!app.getAuthCentral() && systemUser) {
349           throw new Exception("For non-centralized application we cannot add systemUser");
350         } else {    // if centralized app
351           if (app.getAuthCentral()) {
352             if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
353               pushRemoteUser(roleInAppForUserList, userId, app, mapper,
354                   applicationsRestClientService, false);
355             }
356
357             Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
358                 roleInAppForUserList);
359             RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
360                 appId,
361                 userRolesInLocalApp);
362             List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
363             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
364
365               // Apply changes in external Access system
366               updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
367                   roleAppUserList,
368                   epRequestValue, false, rolesGotDeletedFromApprover,
369                   checkIfUserIsOnlyRoleAdmin);
370             }
371             result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
372                 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
373                 checkIfUserIsOnlyRoleAdmin);
374           }
375           // In case if portal is not centralized then follow existing approach
376           else if (!app.getAuthCentral() && app.getId()
377               .equals(PortalConstants.PORTAL_APP_ID)) {
378             Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
379                 roleInAppForUserList);
380             RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
381                 appId,
382                 userRolesInLocalApp);
383             Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
384             result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
385                 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
386           } else {// remote app
387             FnUser remoteAppUser;
388             if (!app.getAuthCentral() && !app.getId()
389                 .equals(PortalConstants.PORTAL_APP_ID)) {
390
391               remoteAppUser = checkIfRemoteUserExits(userId, app,
392                   applicationsRestClientService);
393
394               if (remoteAppUser == null) {
395                 addRemoteUser(roleInAppForUserList, userId, app,
396                     mapper, applicationsRestClientService);
397               }
398               Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
399                   roleInAppForUserList, mapper,
400                   applicationsRestClientService, appId, userId);
401               RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
402                   userId, appId,
403                   userRolesInRemoteApp);
404               Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
405               result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
406                   epRequestValue, null, false, rolesGotDeletedByApprover, false);
407
408               // If no roles remain, request app to set user inactive.
409               if (userRolesInRemoteApp.size() == 0) {
410                 logger.debug(EELFLoggerDelegate.debugLogger,
411                     "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
412                     app,
413                     userId);
414                 postUserToRemoteApp(userId, app,
415                     applicationsRestClientService);
416               }
417             }
418           }
419         }
420       } catch (Exception e) {
421         String message = String.format(
422             "Failed to create user or update user roles for User %s, AppId %s",
423             userId, Long.toString(appId));
424         logger.error(EELFLoggerDelegate.errorLogger, message, e);
425         result = false;
426         reqMessage = e.getMessage();
427       }
428     }
429     //return result;
430     return new ExternalRequestFieldsValidator(result, reqMessage);
431
432   }
433
434   private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
435       ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
436       throws Exception {
437     pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
438         roleInAppForUserList, appRoleIdUsed);
439   }
440
441
442   private void postUserToRemoteApp(String userId, FnApp app,
443       ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
444
445     getUser(userId, app, applicationsRestClientService);
446
447   }
448
449   private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
450       throws HTTPException {
451     return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
452
453   }
454
455   private void pushUserOnRemoteApp(String userId, FnApp app,
456       ApplicationsRestClientService applicationsRestClientService,
457       ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
458       throws Exception {
459
460     FnUser client;
461     client = fnUserService.loadUserByUsername(userId);
462
463     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
464     if (client == null) {
465       String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
466       logger.error(EELFLoggerDelegate.errorLogger, msg);
467       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
468       if (!userList.isEmpty()) {
469         logger.debug(EELFLoggerDelegate.debugLogger,
470             userList.get(0).getOrgUserId() + " User was found in Portal");
471         client = userList.get(0);
472         client.setUserApps(Collections.EMPTY_SET);
473         client.setIsSystemUser(false);
474       } else {
475         logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
476         throw new Exception(msg);
477       }
478
479     }
480
481     client.setLoginId(userId);
482     client.setActiveYn(true);
483     client.setOrgUserId(userId);
484
485     roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
486     SortedSet<Role> roles = new TreeSet<>();
487
488     List<FnRole> getAppRoles = externalAccessRolesService.getAppRoles(app.getId());
489     List<FnApp> appList = new ArrayList<>();
490     appList.add(app);
491     List<CentralV2Role> roleList = new ArrayList<>();
492     Map<String, Long> params = new HashMap<>();
493
494     List<FnRole> userRoles = new ArrayList<>();
495
496     for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
497       FnRole role = new FnRole();
498       role.setId(roleInappForUser.getRoleId());
499       role.setRoleName(roleInappForUser.getRoleName());
500       userRoles.add(role);
501     }
502
503     if (appRoleIdUsed) {
504       List<FnRole> userAppRoles = new ArrayList<>();
505       for (FnRole role : userRoles) {
506         FnRole appRole = getAppRoles.stream()
507             .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
508             .orElse(null);
509         FnRole epRole = new FnRole();
510         if (appRole != null) {
511           epRole.setId(appRole.getId());
512           epRole.setRoleName(appRole.getRoleName());
513         }
514         userAppRoles.add(epRole);
515       }
516       userRoles = new ArrayList<>(userAppRoles);
517     }
518     roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
519
520     for (CentralV2Role epRole : roleList) {
521       Role role = new Role();
522       FnRole appRole = getAppRoles.stream()
523           .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
524       if (appRole != null) {
525         role.setId(appRole.getAppRoleId());
526         role.setName(epRole.getName());
527         role.setRoleFunctions(epRole.getRoleFunctions());
528       }
529       roles.add(role);
530     }
531     client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
532     String userInString;
533     userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
534     logger.debug(EELFLoggerDelegate.debugLogger,
535         "about to post a client to remote application, users json = " + userInString);
536     applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
537   }
538
539   private FnRole roleToFnRole(Role role) {
540     return new FnRole(role.getId(), role.getName(), role.getActive(), role.getPriority(), role.getRoleFunctions(),
541         role.getChildRoles(), role.getParentRoles());
542   }
543
544   private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
545       ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
546       throws JsonProcessingException, HTTPException {
547     Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
548     Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
549     String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
550     FnApp externalApp;
551     externalApp = appsCacheService.getApp(appId);
552     String appBaseUri = null;
553     Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
554     if (externalApp != null) {
555       appBaseUri = externalApp.getAppRestEndpoint();
556     }
557     if (appBaseUri != null && appBaseUri.endsWith("/api")) {
558       for (EcompRole eprole : updatedUserRolesinRemote) {
559         RemoteRoleV1 role = new RemoteRoleV1();
560         role.setId(eprole.getId());
561         role.setName(eprole.getName());
562         updatedUserRolesinRemoteV1.add(role);
563       }
564       userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
565     }
566     applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
567         String.format("/user/%s/roles", userId));
568     return updateUserRolesInEcomp;
569   }
570
571   private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
572       ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
573     if (remoteUserShouldBeCreated(roleInAppForUserList)) {
574       createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
575     }
576   }
577
578   private void createNewUserOnRemoteApp(String userId, FnApp app,
579       ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
580       throws Exception {
581
582     FnUser client = fnUserService.loadUserByUsername(userId);
583
584     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
585
586     if (client == null) {
587       String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
588       logger.error(EELFLoggerDelegate.errorLogger, msg);
589       throw new Exception(msg);
590     }
591
592     client.setLoginId(userId);
593     client.setActiveYn(true);
594
595     String userInString;
596     userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
597     logger.debug(EELFLoggerDelegate.debugLogger,
598         "about to post new client to remote application, users json = " + userInString);
599     applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
600
601   }
602
603   private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
604     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
605       if (roleInAppForUser.getIsApplied()) {
606         return true;
607       }
608     }
609     return false;
610   }
611
612   private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
613     Set<EcompRole> existingUserRoles = new TreeSet<>();
614     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
615       if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
616           .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
617         EcompRole ecompRole = new EcompRole();
618         ecompRole.setId(roleInAppForUser.getRoleId());
619         ecompRole.setName(roleInAppForUser.getRoleName());
620         existingUserRoles.add(ecompRole);
621       }
622     }
623     return existingUserRoles;
624   }
625
626   private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
627     List<EpUserRolesRequest> epRequestIdVal;
628     try {
629       epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
630       if (epRequestIdVal.size() > 0) {
631         EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
632         epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
633         epAppRolesRequestData.setRequestStatus("O");
634         epAppRolesRequestData.setUserId(user);
635         epUserRolesRequestService.saveOne(epAppRolesRequestData);
636         List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
637             .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
638         if (epUserAppRolesDetailList.size() > 0) {
639           for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
640             epRequestUpdateList.setRequestType("O");
641             epRequestUpdateList.setReqId(epAppRolesRequestData);
642             epRequestUpdateList.setReqId(epAppRolesRequestData);
643             epUserRolesRequestDetService.saveOne(epRequestUpdateList);
644           }
645           logger.debug(EELFLoggerDelegate.debugLogger,
646               "User App roles request from User Page is overridden");
647         }
648       }
649
650     } catch (Exception e) {
651       logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
652     }
653   }
654
655   private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
656     return constructUsersEcompRoles(roleInAppForUserList);
657   }
658
659   private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
660     Set<EcompRole> existingUserRoles = new TreeSet<>();
661     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
662       if (roleInAppForUser.getIsApplied()) {
663         EcompRole ecompRole = new EcompRole();
664         ecompRole.setId(roleInAppForUser.getRoleId());
665         ecompRole.setName(roleInAppForUser.getRoleName());
666         existingUserRoles.add(ecompRole);
667       }
668     }
669     return existingUserRoles;
670   }
671
672   public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
673       Set<EcompRole> userRolesInRemoteApp) {
674     RolesInAppForUser result;
675     result = new RolesInAppForUser();
676     result.setAppId(appId);
677     result.setOrgUserId(userId);
678
679     for (EcompRole role : userRolesInRemoteApp) {
680       RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
681       roleInAppForUser.setRoleId(role.getId());
682       roleInAppForUser.setRoleName(role.getName());
683       roleInAppForUser.setIsApplied(true);
684       result.getRoles().add(roleInAppForUser);
685     }
686     return result;
687   }
688
689   private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
690       boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
691       boolean isLoggedInUserRoleAdminofApp) throws Exception {
692     try {
693       List<FnUser> userInfo = checkIfUserExists(orgUserId);
694       if (userInfo.isEmpty()) {
695         createLocalUserIfNecessary(orgUserId, isSystemUser);
696       }
697       String name;
698       if (EPCommonSystemProperties
699           .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
700           && !isSystemUser) {
701         name = orgUserId
702             + SystemProperties
703             .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
704       } else {
705         name = orgUserId;
706       }
707       ObjectMapper mapper = new ObjectMapper();
708       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
709       HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
710       ResponseEntity<String> getResponse = externalAccessRolesService
711           .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
712
713       List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
714       String res = getResponse.getBody();
715       JSONObject jsonObj;
716       JSONArray extRoles = null;
717       if (!res.equals("{}")) {
718         jsonObj = new JSONObject(res);
719         extRoles = jsonObj.getJSONArray("role");
720       }
721       ExternalAccessUserRoleDetail userRoleDetail;
722       if (extRoles != null) {
723         for (int i = 0; i < extRoles.length(); i++) {
724           if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
725               && !extRoles.getJSONObject(i).getString("name")
726               .equals(app.getAuthNamespace() + ".admin")
727               && !extRoles.getJSONObject(i).getString("name")
728               .equals(app.getAuthNamespace() + ".owner")) {
729             if (extRoles.getJSONObject(i).has("description")) {
730               ExternalRoleDescription desc = new ExternalRoleDescription(
731                   extRoles.getJSONObject(i).getString("description"));
732               userRoleDetail = new ExternalAccessUserRoleDetail(
733                   extRoles.getJSONObject(i).getString("name"), desc);
734               userRoleDetailList.add(userRoleDetail);
735             } else {
736               userRoleDetail = new ExternalAccessUserRoleDetail(
737                   extRoles.getJSONObject(i).getString("name"), null);
738               userRoleDetailList.add(userRoleDetail);
739             }
740
741           }
742         }
743       }
744
745       List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
746           userRoleDetailList, app);
747
748       List<EcompUserAppRoles> userAppList;
749       // If request coming from portal not from external role approval system then we have to check if user already
750       // have account admin or system admin as GUI will not send these roles
751       if (!isPortalRequest) {
752         FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
753         userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getAppId(), user.getUserId());
754         if (!roleInAppUser.isEmpty()) {
755           for (EcompUserAppRoles userApp : userAppList) {
756             if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
757                 || userApp.getRoleId()
758                 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
759               RoleInAppForUser addSpecialRole = new RoleInAppForUser();
760               addSpecialRole.setIsApplied(true);
761               addSpecialRole.setRoleId(userApp.getRoleId());
762               addSpecialRole.setRoleName(userApp.getRoleName());
763               roleInAppUser.add(addSpecialRole);
764             }
765           }
766         }
767       }
768       List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
769           .collect(Collectors.toList());
770       Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
771       for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
772         currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
773             .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
774                 "_"), roleInAppUserNew);
775       }
776       final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
777       for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
778         currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
779       }
780
781       if (isLoggedInUserRoleAdminofApp) {
782         if (deletedRolesByApprover.size() > 0) {
783           List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
784           for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
785             for (EcompRole role : deletedRolesByApprover) {
786               if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
787                   .equals(role.getName())) {
788                 newUpdatedRoles.add(userRole);
789               }
790             }
791           }
792           if (newUpdatedRoles.size() > 0) {
793             userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
794           } else {
795             userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
796             currentUserRolesToUpdate = new HashMap<>();
797
798           }
799
800         } else {
801           userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
802           currentUserRolesToUpdate = new HashMap<>();
803
804         }
805       }
806
807       // Check if user roles does not exists in local but still there in External Central Auth System delete them all
808       for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
809         if (!(currentUserRolesToUpdate
810             .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
811           HttpEntity<String> entity = new HttpEntity<>(headers);
812           logger.debug(EELFLoggerDelegate.debugLogger,
813               "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
814               userRole.getName());
815           ResponseEntity<String> deleteResponse = template.exchange(
816               SystemProperties
817                   .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
818                   + "userRole/" + name + "/" + userRole.getName(),
819               HttpMethod.DELETE, entity, String.class);
820           logger.debug(EELFLoggerDelegate.debugLogger,
821               "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
822               userRole.getName(), deleteResponse.getBody());
823         }
824       }
825       // Check if user roles does not exists in External Central Auth System add them all
826       for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
827         if (!(currentUserRolesInExternalSystem
828             .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
829                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
830                 "_")))) {
831           ExternalAccessUser extUser = new ExternalAccessUser(name,
832               app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
833                   EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
834                   "_"));
835           String formattedUserRole = mapper.writeValueAsString(extUser);
836           HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
837           logger.debug(EELFLoggerDelegate.debugLogger,
838               "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
839               name, addUserRole.getRoleName());
840           ResponseEntity<String> addResponse = template
841               .exchange(SystemProperties
842                   .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
843                   + "userRole", HttpMethod.POST, entity, String.class);
844           logger.debug(EELFLoggerDelegate.debugLogger,
845               "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
846               addResponse.getBody(), addUserRole.getRoleName());
847           if (addResponse.getStatusCode().value() != 201
848               && addResponse.getStatusCode().value() != 404) {
849             logger.debug(EELFLoggerDelegate.debugLogger,
850                 "Finished POST operation in external system but unable to save user role",
851                 addResponse.getBody(),
852                 addUserRole.getRoleName());
853             throw new Exception(addResponse.getBody());
854           }
855         }
856       }
857     } catch (HttpClientErrorException e) {
858       logger.error(EELFLoggerDelegate.errorLogger,
859           "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
860           app.getId(), e);
861       if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
862         logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
863             orgUserId);
864         throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
865             "Please enter the valid systemUser");
866       }
867       if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
868         logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
869         throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
870       }
871       EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
872       throw e;
873     } catch (Exception e) {
874       logger.error(EELFLoggerDelegate.errorLogger,
875           "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
876           app.getId(), e);
877       EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
878       throw e;
879     }
880   }
881
882   private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
883       List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
884     Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
885     //Add Account Admin role for partner app to prevent conflict
886     if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
887       FnRole role = new FnRole();
888       role.setRoleName(PortalConstants.ADMIN_ROLE
889           .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
890       epRoleList.put(role.getRoleName(), role);
891     }
892     userRoleDetailList.removeIf(
893         userRoleDetail -> !epRoleList
894             .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
895     return userRoleDetailList;
896   }
897
898   private List<FnUser> checkIfUserExists(String userParams) {
899     return fnUserService.getUserWithOrgUserId(userParams);
900   }
901
902   @Transactional
903   private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
904     if (StringUtils.isEmpty(userId)) {
905       logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
906       return;
907     }
908     try {
909       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
910       if (userList.size() == 0) {
911         FnUser client;
912         if (!isSystemUser) {
913           client = fnUserService.loadUserByUsername(userId);
914         } else {
915           client = new FnUser();
916           client.setOrgUserId(userId);
917           client.setIsSystemUser(true);
918           client.setFirstName(userId.substring(0, userId.indexOf("@")));
919         }
920         if (client == null) {
921           String msg = "createLocalUserIfNecessary: cannot create user " + userId
922               + ", because not found in phonebook";
923           logger.error(EELFLoggerDelegate.errorLogger, msg);
924         } else {
925           client.setLoginId(userId);
926           client.setActiveYn(true);
927         }
928         fnUserService.saveFnUser(client);
929       }
930     } catch (Exception e) {
931       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
932     }
933
934   }
935
936   private FnUser checkIfRemoteUserExits(String userId, FnApp app,
937       ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
938     FnUser checkRemoteUser = null;
939     try {
940       checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
941     } catch (HTTPException e) {
942       // Some apps are returning 400 if user is not found.
943       if (e.getResponseCode() == 400) {
944         logger.debug(EELFLoggerDelegate.debugLogger,
945             "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
946             e);
947       } else if (e.getResponseCode() == 404) {
948         logger.debug(EELFLoggerDelegate.debugLogger,
949             "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
950             e);
951       } else {
952         // Other response code, let it come thru.
953         throw e;
954       }
955     }
956     return checkRemoteUser;
957   }
958
959   private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
960       throws HTTPException {
961     if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
962       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
963       if (userList != null && !userList.isEmpty()) {
964         return userList.get(0);
965       } else {
966         return null;
967       }
968     }
969     return getUser(userId, app, applicationsRestClientService);
970   }
971
972   private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
973       boolean externalSystemRequest, String reqType, boolean isSystemUser,
974       Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
975     boolean result = false;
976     String userId = rolesInAppForUser.getOrgUserId();
977     Long appId = rolesInAppForUser.getAppId();
978     synchronized (syncRests) {
979       createLocalUserIfNecessary(userId, isSystemUser);
980
981       EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
982       for (int i = 0;
983           i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
984         RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
985         EcompRole role = new EcompRole();
986         role.setId(roleInAppForUser.getRoleId());
987         role.setName(roleInAppForUser.getRoleName());
988         userAppRoles[i] = role;
989       }
990       try {
991         EcompRole[] applicationRoles = null;
992
993         if (isLoggedInUserRoleAdminOfApp) {
994           List<EcompRole> roles = Arrays.stream(userAppRoles)
995               .collect(Collectors.toList());
996           List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
997           roles.addAll(roles1);
998           applicationRoles = roles.toArray(new EcompRole[0]);
999         }
1000
1001         syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1002             reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1003         result = true;
1004       } catch (Exception e) {
1005         logger.error(EELFLoggerDelegate.errorLogger,
1006             "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1007                 + userId, e);
1008         if ("DELETE".equals(reqType)) {
1009           throw new Exception(e.getMessage());
1010         }
1011       }
1012     }
1013     return result;
1014   }
1015
1016   private void syncUserRoles(String userId, Long appId,
1017       EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1018       EcompRole[] appRoles) throws Exception {
1019
1020     Transaction transaction = null;
1021     String roleActive;
1022     HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1023     List<FnRole> roleInfo = externalAccessRolesService
1024         .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1025     FnRole adminRole = new FnRole();
1026     if (roleInfo.size() > 0) {
1027       adminRole = roleInfo.get(0);
1028       logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1029     }
1030     try {
1031       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1032       if (userList.size() > 0) {
1033         FnUser client = userList.get(0);
1034         roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1035         List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1036         entityManager
1037             .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1038             .setParameter("appId", appId)
1039             .setParameter("userId", client.getId())
1040             .getResultList();
1041
1042         if ("DELETE".equals(reqType)) {
1043           for (FnUserRole userAppRoleList : userRoles) {
1044             List<FnRole> rolesList =
1045                 (!userAppRoleList.getRoleId().getRoleName()
1046                     .equals(adminRole.getRoleName()))
1047                     ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1048                     (userAppRoleList.getRoleId().getRoleName(), appId)
1049                     : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1050             if (!rolesList.isEmpty()) {
1051               checkIfRoleInactive(rolesList.get(0));
1052             }
1053           }
1054         }
1055
1056         if (appRoles != null) {
1057           List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1058           List<FnUserRole> finalUserRolesList = new ArrayList<>();
1059           if (checkIfUserisRoleAdmin) {
1060             for (EcompRole role : appRolesList) {
1061               for (FnUserRole userAppRoleList : userRoles) {
1062                 if (userAppRoleList.getRoleId().getRoleName()
1063                     .equals(role.getName())) {
1064                   finalUserRolesList.add(userAppRoleList);
1065                 }
1066
1067               }
1068             }
1069             userRoles = new ArrayList<>(finalUserRolesList);
1070           }
1071         }
1072
1073         for (FnUserRole userRole : userRoles) {
1074           if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getRoleId())
1075               && !PortalConstants.SYS_ADMIN_ROLE_ID
1076               .equals(userRole.getRoleId().getRoleId())
1077               && !extRequestValue) {
1078             syncUserRolesExtension(userRole, appId,
1079                 newUserAppRolesMap);
1080           } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1081               || "DELETE".equals(reqType))) {
1082             syncUserRolesExtension(userRole, appId,
1083                 newUserAppRolesMap);
1084           } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1085               .equals(userRole.getRoleId().getRoleId())) {
1086             syncUserRolesExtension(userRole, appId,
1087                 newUserAppRolesMap);
1088           }
1089         }
1090
1091         Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1092         if (newRolesToAdd.size() > 0) {
1093           FnApp app = fnAppService.getById(appId);
1094
1095           HashMap<Long, FnRole> rolesMap = new HashMap<>();
1096           if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1097             String appIdValue = "";
1098             if (!extRequestValue) {
1099               appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1100             }
1101             @SuppressWarnings("unchecked")
1102             List<FnRole> roles = entityManager
1103                 .createQuery(
1104                     "from " + FnRole.class.getName() + " where appId is null "
1105                         + appIdValue).getResultList();
1106             for (FnRole role : roles) {
1107               role.setAppId(1L);
1108               rolesMap.put(role.getId(), role);
1109             }
1110           } else { // remote app
1111             @SuppressWarnings("unchecked")
1112             List<FnRole> roles = entityManager
1113                 .createQuery("from EPRole where appId=:appId")
1114                 .setParameter("appId", appId)
1115                 .getResultList();
1116             for (FnRole role : roles) {
1117               if (!extRequestValue && app.getAuthCentral()) {
1118                 rolesMap.put(role.getId(), role);
1119               } else {
1120                 rolesMap.put(role.getAppRoleId(), role);
1121               }
1122             }
1123           }
1124
1125           FnRole role;
1126           for (EcompRole userRole : newRolesToAdd) {
1127             FnUserRole userApp = new FnUserRole();
1128             if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1129                 .equals(adminRole.getRoleName())) {
1130               role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1131               userApp.setRoleId(role);
1132             } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1133                 && !extRequestValue) {
1134               continue;
1135             } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1136                 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1137               continue;
1138             } else {
1139               userApp.setRoleId(rolesMap.get(userRole.getId()));
1140             }
1141
1142             userApp.setUserId(client);
1143             userApp.setAppId(app);
1144             fnUserRoleService.saveOne(userApp);
1145           }
1146
1147           if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1148             /*
1149              * for local app -- hack - always make sure fn_role
1150              * table's app_id is null and not 1 for primary app in
1151              * this case being onap portal app; reason: hibernate
1152              * is rightly setting this to 1 while persisting to
1153              * fn_role as per the mapping but SDK role management
1154              * code expects the app_id to be null as there is no
1155              * concept of App_id in SDK
1156              */
1157             Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1158             query.executeUpdate();
1159           }
1160         }
1161       }
1162       transaction.commit();
1163     } catch (Exception e) {
1164       logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1165       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1166       EcompPortalUtils.rollbackTransaction(transaction,
1167           "Exception occurred in syncUserRoles, Details: " + e.toString());
1168       if ("DELETE".equals(reqType)) {
1169         throw new SyncUserRolesException(e.getMessage());
1170       }
1171     }
1172   }
1173
1174   private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1175     HashMap<Long, EcompRole> result = new HashMap<>();
1176     if (ecompRoles != null) {
1177       for (EcompRole ecompRole : ecompRoles) {
1178         if (ecompRole.getId() != null) {
1179           result.put(ecompRole.getId(), ecompRole);
1180         }
1181       }
1182     }
1183     return result;
1184   }
1185
1186   private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1187       HashMap<Long, EcompRole> newUserAppRolesMap) {
1188
1189     Long userAppRoleId;
1190     if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1191       userAppRoleId = userRole.getRoleId().getRoleId();
1192     } else { // remote app
1193       userAppRoleId = userRole.getId();
1194     }
1195
1196     if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1197       fnUserRoleService.deleteById(userRole.getId());
1198     } else {
1199       newUserAppRolesMap.remove(userAppRoleId);
1200     }
1201   }
1202
1203   private void checkIfRoleInactive(FnRole epRole) throws Exception {
1204     if (!epRole.getActiveYn()) {
1205       throw new Exception(epRole.getRoleName() + " role is unavailable");
1206     }
1207   }
1208 }