ExternalAccessRolesController up
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / ExternalAccessRolesService.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 com.fasterxml.jackson.databind.type.TypeFactory;
47 import java.io.IOException;
48 import java.util.ArrayList;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.Objects;
54 import java.util.Optional;
55 import java.util.Set;
56 import java.util.SortedSet;
57 import java.util.TreeSet;
58 import java.util.stream.Collectors;
59 import javax.management.InvalidApplicationException;
60 import javax.persistence.EntityManager;
61 import javax.persistence.Query;
62 import javax.persistence.Tuple;
63 import org.json.JSONArray;
64 import org.json.JSONObject;
65 import org.onap.portal.domain.db.DomainVo;
66 import org.onap.portal.domain.db.ep.EpAppFunction;
67 import org.onap.portal.domain.db.ep.EpAppRoleFunction;
68 import org.onap.portal.domain.db.fn.FnApp;
69 import org.onap.portal.domain.db.fn.FnFunction;
70 import org.onap.portal.domain.db.fn.FnRole;
71 import org.onap.portal.domain.db.fn.FnRoleFunction;
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.ecomp.EPAppRoleFunction;
75 import org.onap.portal.domain.dto.ecomp.ExternalRoleDetails;
76 import org.onap.portal.domain.dto.transport.BulkUploadRoleFunction;
77 import org.onap.portal.domain.dto.transport.BulkUploadUserRoles;
78 import org.onap.portal.domain.dto.transport.CentralApp;
79 import org.onap.portal.domain.dto.transport.CentralRole;
80 import org.onap.portal.domain.dto.transport.CentralRoleFunction;
81 import org.onap.portal.domain.dto.transport.CentralUser;
82 import org.onap.portal.domain.dto.transport.CentralUserApp;
83 import org.onap.portal.domain.dto.transport.CentralV2Role;
84 import org.onap.portal.domain.dto.transport.CentralV2User;
85 import org.onap.portal.domain.dto.transport.CentralV2UserApp;
86 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
87 import org.onap.portal.domain.dto.transport.EcompUserRoles;
88 import org.onap.portal.domain.dto.transport.ExternalAccessPerms;
89 import org.onap.portal.domain.dto.transport.ExternalAccessPermsDetail;
90 import org.onap.portal.domain.dto.transport.ExternalAccessRole;
91 import org.onap.portal.domain.dto.transport.ExternalAccessRolePerms;
92 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
93 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
94 import org.onap.portal.domain.dto.transport.GlobalRoleWithApplicationRoleFunction;
95 import org.onap.portal.domain.dto.transport.LocalRole;
96 import org.onap.portal.exception.DeleteDomainObjectFailedException;
97 import org.onap.portal.exception.ExternalAuthSystemException;
98 import org.onap.portal.exception.InactiveApplicationException;
99 import org.onap.portal.exception.InvalidUserException;
100 import org.onap.portal.exception.RoleFunctionException;
101 import org.onap.portal.logging.logic.EPLogUtil;
102 import org.onap.portal.service.app.FnAppService;
103 import org.onap.portal.service.appFunction.EpAppFunctionService;
104 import org.onap.portal.service.appRoleFunction.EpAppRoleFunctionService;
105 import org.onap.portal.service.role.FnRoleService;
106 import org.onap.portal.service.roleFunction.FnRoleFunctionService;
107 import org.onap.portal.service.user.FnUserService;
108 import org.onap.portal.utils.EPCommonSystemProperties;
109 import org.onap.portal.utils.EPUserUtils;
110 import org.onap.portal.utils.EcompPortalUtils;
111 import org.onap.portal.utils.PortalConstants;
112 import org.onap.portalsdk.core.domain.Role;
113 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
114 import org.onap.portalsdk.core.restful.domain.EcompRole;
115 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
116 import org.onap.portalsdk.core.restful.domain.EcompUser;
117 import org.onap.portalsdk.core.util.SystemProperties;
118 import org.springframework.beans.factory.annotation.Autowired;
119 import org.springframework.http.HttpEntity;
120 import org.springframework.http.HttpHeaders;
121 import org.springframework.http.HttpMethod;
122 import org.springframework.http.HttpStatus;
123 import org.springframework.http.ResponseEntity;
124 import org.springframework.stereotype.Service;
125 import org.springframework.transaction.annotation.Propagation;
126 import org.springframework.transaction.annotation.Transactional;
127 import org.springframework.web.client.HttpClientErrorException;
128 import org.springframework.web.client.RestTemplate;
129
130 @SuppressWarnings("unchecked")
131 @Service
132 public class ExternalAccessRolesService {
133
134     private static final String APP_ROLE_NAME_PARAM = "appRoleName";
135     private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
136     private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
137     private static final String FUNCTION_CODE_PARAMS = "functionCode";
138     private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
139     private static final String OWNER = ".owner";
140     private static final String ADMIN = ".admin";
141     private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
142     private static final String FUNCTION_PIPE = "|";
143     private static final String EXTERNAL_AUTH_PERMS = "perms";
144     private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
145     private static final String IS_EMPTY_JSON_STRING = "{}";
146     private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
147     private static final String APP_ID = "appId";
148     private static final String ROLE_NAME = "name";
149     private static final String APP_ID_EQUALS = " app_id = ";
150
151     private static final String GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS = "select"
152         + "  distinct d.roleId as roleId,"
153         + "  d.roleName as roleName,"
154         + "  d.activeYn as active,"
155         + "  d.priority as priority,"
156         + "  c.epAppFunction.functionCd as functionCd,"
157         + "  e.functionName as functionName,"
158         + "  c.epAppFunction.appId as appId,"
159         + "  c.roleAppId as roleAppId"
160         + " from"
161         + "  FnUserRole a,"
162         + "  FnApp b,"
163         + "  EpAppRoleFunction c,"
164         + "  FnRole d,"
165         + "  EpAppFunction e"
166         + " where"
167         + "  b.appId = c.appId.appId"
168         + "  and a.appId = c.roleAppId"
169         + "  and b.enabled = 'Y'"
170         + "  and c.fnRole.roleId = d.roleId"
171         + "  and d.activeYn = 'Y'"
172         + "  and e.functionCd = c.epAppFunction.functionCd"
173         + "  and c.appId.appId = :appId"
174         + "  and e.appId.appId = c.appId.appId";
175
176     private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesService.class);
177     private final RestTemplate template = new RestTemplate();
178
179     private final FnUserService fnUserService;
180     private final FnRoleService fnRoleService;
181     private final FnAppService fnAppService;
182     private final EntityManager entityManager;
183     private final FnRoleFunctionService fnRoleFunctionService;
184     private final EpAppFunctionService epAppFunctionService;
185     private final EpAppRoleFunctionService epAppRoleFunctionService;
186     private final LocalRoleService localRoleService;
187     private final BulkUploadUserRolesService bulkUploadUserRolesService;
188
189     @Autowired
190     public ExternalAccessRolesService(
191         final FnUserService fnUserService,
192         final FnRoleService fnRoleService,
193         final FnAppService fnAppService, EntityManager entityManager,
194         FnRoleFunctionService fnRoleFunctionService,
195         final EpAppFunctionService epAppFunctionService,
196         final EpAppRoleFunctionService epAppRoleFunctionService,
197         final LocalRoleService localRoleService,
198         BulkUploadUserRolesService bulkUploadUserRolesService) {
199         this.fnUserService = fnUserService;
200         this.fnRoleService = fnRoleService;
201         this.fnAppService = fnAppService;
202         this.entityManager = entityManager;
203         this.fnRoleFunctionService = fnRoleFunctionService;
204         this.epAppFunctionService = epAppFunctionService;
205         this.epAppRoleFunctionService = epAppRoleFunctionService;
206         this.localRoleService = localRoleService;
207         this.bulkUploadUserRolesService = bulkUploadUserRolesService;
208     }
209
210     String getFunctionCodeType(String roleFuncItem) {
211         String type = null;
212         if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
213             || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
214             type = "menu";
215         } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
216             || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
217             type = "url";
218         } else if (roleFuncItem.contains(FUNCTION_PIPE)
219             && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
220             type = EcompPortalUtils.getFunctionType(roleFuncItem);
221         }
222         return type;
223     }
224
225     private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
226         return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
227     }
228
229     private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
230         return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
231     }
232
233     private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
234         return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
235     }
236
237     List<FnRole> getPortalAppRoleInfo(Long roleId) {
238         return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId);
239     }
240
241     ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
242         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
243         ResponseEntity<String> getResponse = template
244             .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
245                 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
246         if (getResponse.getStatusCode().value() == 200) {
247             logger.debug(EELFLoggerDelegate.debugLogger,
248                 "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
249                 getResponse.getBody());
250         } else {
251             logger.error(EELFLoggerDelegate.errorLogger,
252                 "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
253                 getResponse.getBody());
254             EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
255         }
256         return getResponse;
257     }
258
259     Map<String, FnRole> getAppRoleNamesWithUnderscoreMap(FnApp app) {
260         final Map<String, FnRole> currentRolesInDB = new HashMap<>();
261         List<FnRole> getCurrentRoleList = null;
262         final Map<String, Long> appParams = new HashMap<>();
263         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
264             getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
265         } else {
266             appParams.put("appId", app.getId());
267             getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId());
268         }
269         for (FnRole role : getCurrentRoleList) {
270             currentRolesInDB.put(role.getRoleName()
271                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
272         }
273         return currentRolesInDB;
274     }
275
276     List<CentralV2Role> createCentralRoleObject(List<FnApp> app, List<FnRole> roleInfo,
277         List<CentralV2Role> roleList) throws RoleFunctionException {
278         for (FnRole role : roleInfo) {
279             List<EpAppFunction> cenRoleFuncList = epAppFunctionService
280                 .getAppRoleFunctionList(role.getId(), app.get(0).getId());
281             SortedSet<DomainVo> roleFunctionSet = new TreeSet<>();
282             for (EpAppFunction roleFunc : cenRoleFuncList) {
283                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
284                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
285                 String type = getFunctionCodeType(roleFunc.getFunctionCd());
286                 String action = getFunctionCodeAction(roleFunc.getFunctionCd());
287                 FnRoleFunction cenRoleFunc = new FnRoleFunction(role,
288                     FnFunction.builder().code(functionCode).name(roleFunc.getFunctionName()).type(type).action(action)
289                         .build());
290             }
291             SortedSet<CentralV2Role> childRoles = new TreeSet<>();
292             SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
293             CentralV2Role cenRole;
294             if (role.getAppRoleId() == null) {
295                 cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated())
296                     .modified(role.getModified())
297                     .rowNum(role.getRowNum()).name(role.getRoleName())
298                     .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
299                     .childRoles(childRoles).parentRoles(parentRoles).build();
300             } else {
301                 cenRole = CentralV2Role.builder().id(role.getAppRoleId())
302                     .created(role.getCreated()).modified(role.getModified())
303                     .rowNum(role.getRowNum()).name(role.getRoleName())
304                     .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
305                     .childRoles(childRoles).parentRoles(parentRoles).build();
306             }
307             roleList.add(cenRole);
308         }
309         return roleList;
310     }
311
312     String getFunctionCodeAction(String roleFuncItem) {
313         return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
314     }
315
316     public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
317         logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
318         List<CentralV2Role> roleList = new ArrayList<>();
319         try {
320             List<FnApp> app = fnAppService.getByUebKey(uebkey);
321             List<FnRole> appRolesList = fnRoleService.getAppRoles(app.get(0).getId());
322             roleList = createCentralRoleObject(app, appRolesList, roleList);
323             if (!Objects.equals(app.get(0).getId(), PortalConstants.PORTAL_APP_ID)) {
324                 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
325                 List<FnRole> globalRolesList = fnRoleService.getGlobalRolesOfPortal();
326                 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
327                 if (!globalRolesList.isEmpty()) {
328                     for (FnRole eprole : globalRolesList) {
329                         CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
330                         portalsGlobalRolesFinlaList.add(cenRole);
331                     }
332                     roleList.addAll(globalRoleList);
333                     for (CentralV2Role role : portalsGlobalRolesFinlaList) {
334                         CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
335                             .orElse(null);
336                         if (result == null) {
337                             roleList.add(role);
338                         }
339                     }
340                 } else {
341                     for (FnRole role : globalRolesList) {
342                         CentralV2Role cenRole = convertRoleToCentralV2Role(role);
343                         roleList.add(cenRole);
344                     }
345                 }
346             }
347         } catch (Exception e) {
348             logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
349             throw e;
350         }
351         logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
352         return roleList.stream().distinct().collect(Collectors.toList());
353     }
354
355     private List<CentralV2Role> getGlobalRolesOfApplication(final Long appId) {
356         List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
357         try {
358             List<Tuple> tuples = entityManager.createQuery(GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS, Tuple.class)
359                 .setParameter("appId", appId)
360                 .getResultList();
361             globalRoles = tuples.stream().map(this::tupleToGlobalRoleWithApplicationRoleFunction)
362                 .collect(Collectors.toList());
363         } catch (Exception e) {
364             logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
365         }
366         List<CentralV2Role> roleList = new ArrayList<>();
367         if (globalRoles.size() > 0) {
368             roleList = finalListOfCentralRoles(globalRoles);
369         }
370         return roleList;
371     }
372
373     private GlobalRoleWithApplicationRoleFunction tupleToGlobalRoleWithApplicationRoleFunction(Tuple tuple) {
374         return GlobalRoleWithApplicationRoleFunction.builder().roleId((Long) tuple.get("roleId"))
375             .roleName((String) tuple.get("roleName"))
376             .functionCd((String) tuple.get("functionCd")).functionName((String) tuple.get("functionName"))
377             .active((Boolean) tuple.get("active")).priority((Integer) tuple.get("priority"))
378             .appId((Long) tuple.get("appId")).roleAppId((Long) tuple.get("roleAppId")).build();
379     }
380
381     private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
382         List<CentralV2Role> rolesfinalList = new ArrayList<>();
383         for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
384             boolean found = false;
385             for (CentralV2Role cenRole : rolesfinalList) {
386                 if (role.getRoleId().equals(cenRole.getId())) {
387                     SortedSet<DomainVo> roleFunctions = new TreeSet<>();
388                     for (DomainVo vo : cenRole.getRoleFunctions()) {
389                         Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
390                         roleFunction.ifPresent(roleFunctions::add);
391                     }
392                     FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
393                     roleFunctions.add(cenRoleFun);
394                     cenRole.setRoleFunctions(roleFunctions);
395                     found = true;
396                     break;
397                 }
398             }
399             if (!found) {
400                 CentralV2Role cenrole = new CentralV2Role();
401                 cenrole.setName(role.getRoleName());
402                 cenrole.setId(role.getRoleId());
403                 cenrole.setActive(role.getActive());
404                 cenrole.setPriority(role.getPriority());
405                 SortedSet<DomainVo> roleFunctions = new TreeSet<>();
406                 FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
407                 roleFunctions.add(cenRoleFun);
408                 cenrole.setRoleFunctions(roleFunctions);
409                 rolesfinalList.add(cenrole);
410             }
411         }
412         return rolesfinalList;
413     }
414
415     public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
416         final Map<String, String> params = new HashMap<>();
417         FnUser user = null;
418         CentralV2User cenV2User = null;
419         String result = null;
420         try {
421             params.put("orgUserIdValue", loginId);
422             List<FnApp> appList = getApp(uebkey);
423             if (!appList.isEmpty()) {
424                 user = fnUserService.loadUserByUsername(loginId);
425                 ObjectMapper mapper = new ObjectMapper();
426                 cenV2User = getV2UserAppRoles(loginId, uebkey);
427                 result = mapper.writeValueAsString(cenV2User);
428             }
429         } catch (Exception e) {
430             logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
431             throw e;
432         }
433         return result;
434     }
435
436     public void syncApplicationRolesWithEcompDB(FnApp app) {
437         try {
438             logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
439             // Sync functions and roles assigned to it which also creates new roles if does
440             // not exits in portal
441             syncRoleFunctionFromExternalAccessSystem(app);
442             logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
443             ObjectMapper mapper = new ObjectMapper();
444             logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
445             // Get Permissions from External Auth System
446             JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app.getId(), app.getAuthNamespace());
447             logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
448             // refactoring done
449             List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
450             List<FnRole> finalRoleList = new ArrayList<>();
451             for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
452                 FnRole ecompRole = convertExternalRoleDetailsToEpRole(externalRole);
453                 finalRoleList.add(ecompRole);
454             }
455             List<FnRole> applicationRolesList;
456             applicationRolesList = getAppRoles(app.getId());
457             List<String> applicationRoleIdList = new ArrayList<>();
458             for (FnRole applicationRole : applicationRolesList) {
459                 applicationRoleIdList.add(applicationRole.getRoleName());
460             }
461             List<FnRole> roleListToBeAddInEcompDB = new ArrayList<>();
462             for (FnRole aafRole : finalRoleList) {
463                 if (!applicationRoleIdList.contains(aafRole.getRoleName())) {
464                     roleListToBeAddInEcompDB.add(aafRole);
465                 }
466             }
467             logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
468             // Check if roles exits in external Access system and if not make inactive in DB
469             inactiveRolesNotInExternalAuthSystem(app.getId(), finalRoleList, applicationRolesList);
470             logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
471             // Add new roles in DB and updates role description in External Auth System
472             addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
473             logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
474         } catch (HttpClientErrorException e) {
475             logger.error(EELFLoggerDelegate.errorLogger,
476                 "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
477             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
478         } catch (Exception e) {
479             logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
480         }
481     }
482
483     public List<FnRole> getAppRoles(Long appId) {
484         List<FnRole> applicationRoles;
485         try {
486             if (appId == 1) {
487                 applicationRoles = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
488             } else {
489                 applicationRoles = fnRoleService.retrieveAppRolesByAppId(appId);
490             }
491         } catch (Exception e) {
492             logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
493             throw e;
494         }
495         return applicationRoles;
496     }
497
498     private FnRole convertExternalRoleDetailsToEpRole(ExternalRoleDetails externalRoleDetails) {
499         FnRole role = new FnRole();
500         role.setActiveYn(true);
501         role.setAppId(externalRoleDetails.getAppId());
502         role.setAppRoleId(externalRoleDetails.getAppRoleId());
503         role.setRoleName(externalRoleDetails.getName());
504         role.setPriority(externalRoleDetails.getPriority());
505         return role;
506     }
507
508     public List<ExternalRoleDetails> getExternalRoleDetailsList(FnApp app, ObjectMapper mapper, JSONArray extRole)
509         throws IOException {
510         List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
511         ExternalAccessPerms externalAccessPerms;
512         List<String> functionCodelist = new ArrayList<>();
513         Map<String, FnRole> curRolesMap = getAppRoleNamesMap(app.getId());
514         Map<String, FnRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
515         for (int i = 0; i < extRole.length(); i++) {
516             ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
517             EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
518             JSONObject Role = (JSONObject) extRole.get(i);
519             String name = extRole.getJSONObject(i).getString(ROLE_NAME);
520             String actualRoleName = name.substring(app.getAuthNamespace().length() + 1);
521             if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
522                 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
523             }
524             SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
525             if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
526                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
527                 for (int j = 0; j < extPerm.length(); j++) {
528                     JSONObject perms = extPerm.getJSONObject(j);
529                     boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
530                         app.getAuthNamespace());
531                     if (isNamespaceMatching) {
532                         externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
533                             perms.getString("instance"), perms.getString("action"));
534                         ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
535                         functionCodelist.add(ePAppRoleFunction.getCode());
536                         externalAccessPermsOfRole.add(externalAccessPerms);
537                     }
538                 }
539             }
540             externalRoleDetail.setActive(true);
541             externalRoleDetail.setName(actualRoleName);
542             if (app.getId() == 1) {
543                 externalRoleDetail.setAppId(null);
544             } else {
545                 externalRoleDetail.setAppId(app.getId());
546             }
547             FnRole currRole = null;
548             currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
549                 ? curRolesUnderscoreMap.get(actualRoleName)
550                 : curRolesMap.get(actualRoleName);
551             Long roleId = null;
552             if (currRole != null) {
553                 roleId = currRole.getId();
554             }
555             final Map<String, EpAppRoleFunction> roleFunctionsMap = new HashMap<>();
556             if (roleId != null) {
557                 List<EpAppRoleFunction> appRoleFunctions = epAppRoleFunctionService
558                     .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), roleId);
559                 if (!appRoleFunctions.isEmpty()) {
560                     for (EpAppRoleFunction roleFunc : appRoleFunctions) {
561                         roleFunctionsMap.put(roleFunc.getEpAppFunction().getFunctionCd(), roleFunc);
562                     }
563                 }
564             }
565             if (!externalAccessPermsOfRole.isEmpty()) {
566                 // Adding functions to role
567                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
568                     EpAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
569                     if (checkRoleFunctionExits == null) {
570                         String funcCode = externalpermission.getType().substring(app.getAuthNamespace().length() + 1)
571                             + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
572                             + externalpermission.getAction();
573                         EpAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
574                         if (checkRoleFunctionPipeExits == null) {
575                             try {
576                                 logger.debug(EELFLoggerDelegate.debugLogger,
577                                     "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
578                                     externalpermission.getInstance());
579                                 List<EpAppFunction> roleFunction = epAppFunctionService
580                                     .getAppFunctionOnCodeAndAppId(app.getId(), externalpermission.getInstance());
581                                 if (roleFunction.isEmpty()) {
582                                     roleFunction = epAppFunctionService
583                                         .getAppFunctionOnCodeAndAppId(app.getId(), funcCode);
584                                 }
585                                 if (!roleFunction.isEmpty()) {
586                                     EpAppRoleFunction apRoleFunction = new EpAppRoleFunction();
587                                     apRoleFunction.setAppId(app);
588                                     apRoleFunction.setFnRole(currRole);
589                                     apRoleFunction.setEpAppFunction(roleFunction.get(0));
590                                     epAppRoleFunctionService.save(apRoleFunction);
591                                 }
592                             } catch (Exception e) {
593                                 logger.error(EELFLoggerDelegate.errorLogger,
594                                     "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
595                             }
596                         }
597                     }
598                 }
599             }
600             externalRoleDetailsList.add(externalRoleDetail);
601         }
602         return externalRoleDetailsList;
603     }
604
605     private Map<String, FnRole> getAppRoleNamesMap(final Long appId) {
606         final Map<String, FnRole> currentRolesInDB = new HashMap<>();
607         List<FnRole> getCurrentRoleList = null;
608         final Map<String, Long> appParams = new HashMap<>();
609         if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
610             getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
611         } else {
612             getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(appId);
613         }
614         for (FnRole role : getCurrentRoleList) {
615             currentRolesInDB.put(role.getRoleName(), role);
616         }
617         return currentRolesInDB;
618     }
619
620     public JSONArray getAppRolesJSONFromExtAuthSystem(final long appId, final String authNamespace) throws Exception {
621         ResponseEntity<String> response = null;
622         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
623         HttpEntity<String> entity = new HttpEntity<>(headers);
624         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
625             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
626         response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
627             + "roles/ns/" + authNamespace, HttpMethod.GET, entity, String.class);
628         String res = response.getBody();
629         logger.debug(EELFLoggerDelegate.debugLogger,
630             "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
631             res);
632         JSONObject jsonObj = new JSONObject(res);
633         JSONArray extRole = jsonObj.getJSONArray("role");
634         for (int i = 0; i < extRole.length(); i++) {
635             if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + ADMIN)
636                 || extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + OWNER)
637                 || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + ACCOUNT_ADMINISTRATOR)
638                 && !(appId == PortalConstants.PORTAL_APP_ID))) {
639                 extRole.remove(i);
640                 i--;
641             }
642         }
643         return extRole;
644     }
645
646     private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(FnApp app, List<FnRole> roleListToBeAddInEcompDB) {
647         FnRole roleToBeAddedInEcompDB;
648         for (FnRole fnRole : roleListToBeAddInEcompDB) {
649             try {
650                 roleToBeAddedInEcompDB = fnRole;
651                 if (app.getId() == 1) {
652                     roleToBeAddedInEcompDB.setAppRoleId(null);
653                 }
654                 fnRoleService.saveOne(roleToBeAddedInEcompDB);
655                 List<FnRole> getRoleCreatedInSync = null;
656                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
657                     getRoleCreatedInSync = fnRoleService
658                         .retrieveAppRolesByRoleNameAndByAppId(roleToBeAddedInEcompDB.getRoleName(), app.getId());
659                     FnRole epUpdateRole = getRoleCreatedInSync.get(0);
660                     epUpdateRole.setAppRoleId(epUpdateRole.getId());
661                     fnRoleService.saveOne(epUpdateRole);
662                 }
663                 List<FnRole> roleList;
664                 final Map<String, String> params = new HashMap<>();
665                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getRoleName());
666                 boolean isPortalRole;
667                 if (app.getId() == 1) {
668                     isPortalRole = true;
669                     roleList = fnRoleService
670                         .retrieveAppRolesByRoleNameAndWhereAppIdIsNull(roleToBeAddedInEcompDB.getRoleName());
671                 } else {
672                     isPortalRole = false;
673                     roleList = fnRoleService
674                         .retrieveAppRolesByRoleNameAndByAppId(roleToBeAddedInEcompDB.getRoleName(), app.getId());
675                 }
676                 FnRole role = roleList.get(0);
677                 Role aaFrole = new Role();
678                 aaFrole.setId(role.getId());
679                 aaFrole.setActive(role.getActiveYn());
680                 aaFrole.setPriority(role.getPriority());
681                 aaFrole.setName(role.getRoleName());
682                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
683             } catch (Exception e) {
684                 logger.error(EELFLoggerDelegate.errorLogger,
685                     "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
686             }
687         }
688     }
689
690     private void updateRoleInExternalSystem(Role updateExtRole, FnApp app, boolean isGlobalRole) throws Exception {
691         ObjectMapper mapper = new ObjectMapper();
692         ResponseEntity<String> deleteResponse = null;
693         List<FnRole> epRoleList = null;
694         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
695             || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
696             epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
697         } else {
698             epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app.getId());
699         }
700         // Assigning functions to global role
701         if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
702             List<FnFunction> functions = new ArrayList<>();
703             for (FnRoleFunction roleFunction : convertSetToListOfRoleFunctions(updateExtRole)) {
704                 functions.add(roleFunction.getFunctionCd());
705             }
706             // TODO HARDCODED ID
707             FnApp portalAppInfo = fnAppService.getById(PortalConstants.PORTAL_APP_ID);
708             addFunctionsTOGlobalRole(epRoleList, updateExtRole, functions, mapper, app, portalAppInfo);
709         } else {
710             String appRole = getSingleAppRole(epRoleList.get(0).getRoleName(), app);
711             List<FnRoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
712             if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
713                 JSONObject jsonObj = new JSONObject(appRole);
714                 JSONArray extRole = jsonObj.getJSONArray("role");
715                 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
716                     String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
717                     Map<String, String> delRoleKeyMapper = new HashMap<>();
718                     delRoleKeyMapper.put(ROLE_NAME, roleName);
719                     String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
720                     deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
721                     if (deleteResponse.getStatusCode().value() != 200) {
722                         throw new ExternalAuthSystemException(deleteResponse.getBody());
723                     }
724                     addRole(updateExtRole, app.getUebKey());
725                 } else {
726                     String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
727                     String name = extRole.getJSONObject(0).getString(ROLE_NAME);
728                     List<ExternalAccessPerms> list = new ArrayList<>();
729                     if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
730                         JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
731                         list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
732                             .constructCollectionType(List.class, ExternalAccessPerms.class));
733                     }
734                     // If role name or role functions are updated then delete
735                     // record in External System and add new record to avoid
736                     // conflicts
737                     boolean isRoleNameChanged = false;
738                     if (!desc.equals(updateExtRole.getName())) {
739                         isRoleNameChanged = true;
740                         deleteRoleInExtSystem(mapper, name);
741                         addRole(updateExtRole, app.getUebKey());
742                         // add partner functions to the global role in External
743                         // Auth System
744                         if (!list.isEmpty() && isGlobalRole) {
745                             addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
746                         }
747                         list.removeIf(
748                             perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace()));
749                         // if role name is changes please ignore the previous
750                         // functions in External Auth
751                         // and update with user requested functions
752                         addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
753                     }
754                     // Delete role in External System if role is inactive
755                     if (!updateExtRole.getActive()) {
756                         deleteRoleInExtSystem(mapper, name);
757                     }
758                     if (!isRoleNameChanged) {
759                         addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
760                             list);
761                     }
762                 }
763             } else {
764                 // It seems like role exists in local DB but not in External
765                 // Access system
766                 if (updateExtRole.getActive()) {
767                     addRole(updateExtRole, app.getUebKey());
768                     ExternalAccessRolePerms extAddRolePerms = null;
769                     ExternalAccessPerms extAddPerms = null;
770                     List<FnRoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
771                     HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
772                     for (FnRoleFunction roleFunc : roleFunctionListAdd) {
773                         extAddPerms = new ExternalAccessPerms(
774                             app.getAuthNamespace() + "." + roleFunc.getFunctionCd().getType(),
775                             roleFunc.getFunctionCd().getCode(), roleFunc.getFunctionCd().getAction());
776                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
777                             app.getAuthNamespace() + "." + updateExtRole.getName().replaceAll(
778                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
779                         addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
780                     }
781                 }
782             }
783         }
784     }
785
786     private void addRemoveFunctionsToRole(Role updateExtRole, FnApp app, ObjectMapper mapper,
787         List<FnRoleFunction> fnRoleFunctions, String name, List<ExternalAccessPerms> list) throws Exception {
788         boolean response;
789         List<FnFunction> roleFunctionListNew = new ArrayList<>();
790         for (FnRoleFunction roleFunction : fnRoleFunctions) {
791             roleFunctionListNew.add(roleFunction.getFunctionCd());
792         }
793         Map<String, FnFunction> updateRoleFunc = new HashMap<>();
794         for (FnFunction addPerm : roleFunctionListNew) {
795             updateRoleFunc.put(addPerm.getCode(), addPerm);
796         }
797         final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
798         final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
799         list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace()));
800         // Update permissions in the ExternalAccess System
801         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
802         if (!list.isEmpty()) {
803             for (ExternalAccessPerms perm : list) {
804                 FnFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getAuthNamespace().length() + 1)
805                     + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
806                 if (roleFunc == null) {
807                     FnFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
808                     if (roleFuncPipeFilter == null) {
809                         removePermForRole(perm, mapper, name, headers);
810                     }
811                 }
812                 extRolePermMap.put(perm.getInstance(), perm);
813                 extRolePermMapPipes.put(perm.getType().substring(app.getAuthNamespace().length() + 1) + FUNCTION_PIPE
814                     + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
815             }
816         }
817         response = true;
818         if (!roleFunctionListNew.isEmpty()) {
819             for (FnFunction roleFunc : roleFunctionListNew) {
820                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
821                     ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
822                     if (perm == null) {
823                         response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
824                             roleFunc);
825                     }
826                 } else {
827                     if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
828                         response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
829                             roleFunc);
830                     }
831                 }
832             }
833         }
834     }
835
836     private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, FnApp app, ObjectMapper mapper,
837         HttpHeaders headers, FnFunction roleFunc) throws JsonProcessingException {
838         boolean response;
839         ExternalAccessRolePerms extRolePerms;
840         ExternalAccessPerms extPerms;
841         String code;
842         String type;
843         String action;
844         if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
845             code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
846             type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
847             action = getFunctionCodeAction(roleFunc.getCode());
848         } else {
849             code = roleFunc.getCode();
850             type = roleFunc.getCode().contains("menu") ? "menu" : "url";
851             action = "*";
852         }
853         extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, code, action);
854         extRolePerms = new ExternalAccessRolePerms(extPerms, app.getAuthNamespace() + "." + updateExtRole.getName()
855             .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
856         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
857         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
858         logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
859             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
860         ResponseEntity<String> addResponse = template.exchange(
861             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
862             HttpMethod.POST, entity, String.class);
863         if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
864             response = false;
865             logger.debug(EELFLoggerDelegate.debugLogger,
866                 "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
867                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
868         } else {
869             response = true;
870             logger.debug(EELFLoggerDelegate.debugLogger,
871                 "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
872                 updateRolePerms, addResponse.getStatusCode().value());
873         }
874         return response;
875     }
876
877     private void addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
878         HttpHeaders headers) throws JsonProcessingException {
879         boolean response;
880         String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
881         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
882         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
883             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
884         ResponseEntity<String> addResponse = template.exchange(
885             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
886             HttpMethod.POST, entity, String.class);
887         if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
888             response = false;
889             logger.debug(EELFLoggerDelegate.debugLogger,
890                 "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
891                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
892         } else {
893             response = true;
894             logger.debug(EELFLoggerDelegate.debugLogger,
895                 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
896                 updateRolePerms, addResponse.getStatusCode().value());
897         }
898     }
899
900     private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
901         FnApp app, Role updateExtRole) throws Exception {
902         for (ExternalAccessPerms perm : permslist) {
903             if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace())) {
904                 ExternalAccessRolePerms extAddGlobalRolePerms = null;
905                 ExternalAccessPerms extAddPerms = null;
906                 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
907                 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
908                     app.getAuthNamespace() + "." + updateExtRole.getName().replaceAll(
909                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
910                 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
911                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
912                 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
913                 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
914                     CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
915                 try {
916                     ResponseEntity<String> addResponse = template
917                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
918                             + "role/perm", HttpMethod.POST, entity, String.class);
919                     if (addResponse.getStatusCode().value() != 201) {
920                         logger.debug(EELFLoggerDelegate.debugLogger,
921                             "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
922                             addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
923                     } else {
924                         logger.debug(EELFLoggerDelegate.debugLogger,
925                             "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
926                             addResponse.getStatusCode().value());
927                     }
928                 } catch (Exception e) {
929                     logger.error(EELFLoggerDelegate.errorLogger,
930                         "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
931                 }
932             }
933         }
934     }
935
936     private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
937         throws JsonProcessingException, Exception, ExternalAuthSystemException {
938         ResponseEntity<String> deleteResponse;
939         Map<String, String> delRoleKeyMapper = new HashMap<>();
940         delRoleKeyMapper.put(ROLE_NAME, name);
941         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
942         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
943         if (deleteResponse.getStatusCode().value() != 200) {
944             logger.error(EELFLoggerDelegate.errorLogger,
945                 "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
946                 deleteResponse.getBody());
947             throw new ExternalAuthSystemException(deleteResponse.getBody());
948         }
949     }
950
951     public void addRole(Role addRole, String uebkey) throws Exception {
952         boolean response = false;
953         ResponseEntity<String> addResponse = null;
954         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
955         FnApp app = getApp(uebkey).get(0);
956         String newRole = updateExistingRoleInExternalSystem(addRole.getName(), app.getAuthNamespace());
957         HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
958         logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
959         addResponse = template.exchange(
960             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
961             HttpMethod.POST, entity, String.class);
962         if (addResponse.getStatusCode().value() == 201) {
963             response = true;
964             logger.debug(EELFLoggerDelegate.debugLogger,
965                 "addRole: Finished adding role in the External Auth system  and response code: {} ",
966                 addResponse.getStatusCode().value());
967         }
968         if (addResponse.getStatusCode().value() == 406) {
969             logger.error(EELFLoggerDelegate.errorLogger,
970                 "addRole: Failed to add in the External Auth system due to {} and status code: {}",
971                 addResponse.getBody(), addResponse.getStatusCode().value());
972         }
973     }
974
975     private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
976         ResponseEntity<String> delResponse = null;
977         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
978         HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
979         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
980             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
981         delResponse = template.exchange(
982             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
983             HttpMethod.DELETE, entity, String.class);
984         logger.debug(EELFLoggerDelegate.debugLogger,
985             "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
986             delRole, delResponse.getStatusCode().value());
987         return delResponse;
988     }
989
990     private String getSingleAppRole(String addRole, FnApp app) throws Exception {
991         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
992         HttpEntity<String> entity = new HttpEntity<>(headers);
993         ResponseEntity<String> response = null;
994         logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
995         response = template.exchange(
996             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
997                 + app.getAuthNamespace() + "." + addRole
998                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
999             HttpMethod.GET, entity, String.class);
1000         logger.debug(EELFLoggerDelegate.debugLogger,
1001             "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
1002             response.getStatusCode().value());
1003         return response.getBody();
1004     }
1005
1006     private void addFunctionsTOGlobalRole(List<FnRole> epRoleList, Role updateExtRole,
1007         List<FnFunction> roleFunctionListNew, ObjectMapper mapper, FnApp app, FnApp portalAppInfo)
1008         throws Exception {
1009         try {
1010             logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
1011             // GET Permissions from External Auth System
1012             JSONArray extPerms = getExtAuthPermissions(app.getAuthNamespace());
1013             List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1014             final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
1015             final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
1016             final Map<String, FnFunction> userRquestedFunctionsMap = new HashMap<>();
1017             final Map<String, FnFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
1018             for (ExternalAccessPermsDetail permDetail : permsDetailList) {
1019                 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
1020                 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
1021             }
1022             // Add If function does not exists for role in External Auth System
1023             for (FnFunction roleFunc : roleFunctionListNew) {
1024                 String roleFuncCode = "";
1025                 ExternalAccessPermsDetail permsDetail;
1026                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
1027                     roleFuncCode = roleFunc.getCode();
1028                     permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
1029                 } else {
1030                     roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1031                     permsDetail = existingPermsWithRoles.get(roleFuncCode);
1032                 }
1033                 if (null == permsDetail.getRoles()
1034                     || !permsDetail.getRoles()
1035                     .contains(portalAppInfo.getAuthNamespace() + FUNCTION_PIPE
1036                         + epRoleList.get(0).getRoleName().replaceAll(
1037                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
1038                         "_"))) {
1039                     addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
1040                 }
1041                 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
1042                 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
1043             }
1044             List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = entityManager
1045                 .createNamedQuery("getGlobalRoleForRequestedApp")
1046                 .setParameter("requestedAppId", app.getId())
1047                 .setParameter("roleId", updateExtRole.getId())
1048                 .getResultList();
1049             for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
1050                 String globalRoleFuncWithoutPipes = "";
1051                 FnFunction roleFunc = null;
1052                 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
1053                     globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
1054                     roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
1055                 } else {
1056                     globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
1057                     roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
1058                 }
1059                 if (roleFunc == null) {
1060                     ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
1061                         ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
1062                         : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
1063                     ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
1064                         EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
1065                         permDetailFromMap.getAction());
1066                     String roleName = portalAppInfo.getAuthNamespace() + "." + globalRoleFunc.getRoleName()
1067                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
1068                     HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1069                     removePermForRole(perm, mapper, roleName, headers);
1070                 }
1071             }
1072             logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
1073         } catch (Exception e) {
1074             logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
1075             throw e;
1076         }
1077     }
1078
1079     private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
1080         throws ExternalAuthSystemException, JsonProcessingException {
1081         ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
1082         String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
1083         try {
1084             HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
1085             logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
1086                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
1087             ResponseEntity<String> deletePermResponse = template
1088                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1089                     + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
1090             if (deletePermResponse.getStatusCode().value() != 200) {
1091                 throw new ExternalAuthSystemException(deletePermResponse.getBody());
1092             }
1093             logger.debug(EELFLoggerDelegate.debugLogger,
1094                 "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
1095                 permDetails, deletePermResponse.getStatusCode().value());
1096         } catch (Exception e) {
1097             if (e.getMessage().contains("404")) {
1098                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
1099                     permDetails, e.getMessage());
1100             } else {
1101                 throw e;
1102             }
1103         }
1104     }
1105
1106     private void addRoleFunctionsToGlobalRoleInExternalSystem(FnFunction addFunction, Role globalRole,
1107         ObjectMapper mapper, FnApp app, FnApp portalAppInfo) throws Exception {
1108         try {
1109             logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
1110             ExternalAccessRolePerms extAddRolePerms = null;
1111             ExternalAccessPerms extAddPerms = null;
1112             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1113             String code = "";
1114             String type = "";
1115             String action = "";
1116             if (addFunction.getFunctionCd().contains(FUNCTION_PIPE)) {
1117                 code = EcompPortalUtils.getFunctionCode(addFunction.getFunctionCd());
1118                 type = getFunctionCodeType(addFunction.getFunctionCd());
1119                 action = getFunctionCodeAction(addFunction.getFunctionCd());
1120             } else {
1121                 code = addFunction.getFunctionCd();
1122                 type = addFunction.getFunctionCd().contains("menu") ? "menu" : "url";
1123                 action = "*";
1124             }
1125             extAddPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, code, action);
1126             extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
1127                 portalAppInfo.getAuthNamespace() + "." + globalRole
1128                     .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1129             String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
1130             HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1131             logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
1132                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1133             ResponseEntity<String> addResponse = template.exchange(
1134                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1135                 HttpMethod.POST, entity, String.class);
1136             if (addResponse.getStatusCode().value() != 201) {
1137                 logger.debug(EELFLoggerDelegate.debugLogger,
1138                     "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
1139                     addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
1140             } else {
1141                 logger.debug(EELFLoggerDelegate.debugLogger,
1142                     "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
1143                     addResponse.getStatusCode().value());
1144             }
1145             logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
1146         } catch (Exception e) {
1147             logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
1148             throw e;
1149         }
1150     }
1151
1152     private List<FnRoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
1153         Set<FnRoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
1154         List<FnRoleFunction> roleFunctionList = new ArrayList<>();
1155         ObjectMapper roleFuncMapper = new ObjectMapper();
1156         for (Object nextValue : roleFunctionSetList) {
1157             FnRoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, FnRoleFunction.class);
1158             roleFunctionList.add(roleFunction);
1159         }
1160         return roleFunctionList.stream().distinct().collect(Collectors.toList());
1161     }
1162
1163     private List<FnRole> getPartnerAppRoleInfo(Long roleId, Long appId) {
1164         List<FnRole> roleInfo = fnRoleService.retrieveAppRoleByAppRoleIdAndByAppId(roleId, appId);
1165         if (roleInfo.isEmpty()) {
1166             roleInfo = fnRoleService.retrieveAppRoleByAppRoleIdAndByAppId(appId, roleId);
1167         }
1168         return roleInfo;
1169     }
1170
1171     private void inactiveRolesNotInExternalAuthSystem(final Long appId, List<FnRole> finalRoleList,
1172         List<FnRole> applicationRolesList) {
1173         final Map<String, FnRole> checkRolesInactive = new HashMap<>();
1174         for (FnRole extrole : finalRoleList) {
1175             checkRolesInactive.put(extrole.getRoleName(), extrole);
1176         }
1177         for (FnRole role : applicationRolesList) {
1178             try {
1179                 List<FnRole> roleList;
1180                 if (!checkRolesInactive.containsKey(role.getRoleName())) {
1181                     if (appId == 1) {
1182                         roleList = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role.getRoleName());
1183                     } else {
1184                         roleList = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role.getRoleName(), appId);
1185                     }
1186                     if (!roleList.isEmpty()) {
1187                         FnRole updateRoleInactive = roleList.get(0);
1188                         updateRoleInactive.setActiveYn(false);
1189                         fnRoleService.saveOne(updateRoleInactive);
1190                     }
1191                 }
1192             } catch (Exception e) {
1193                 logger.error(EELFLoggerDelegate.errorLogger,
1194                     "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
1195             }
1196         }
1197     }
1198
1199     private JSONArray getExtAuthPermissions(String authNamespace) throws Exception {
1200         ResponseEntity<String> response = null;
1201         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1202         HttpEntity<String> entity = new HttpEntity<>(headers);
1203         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
1204             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1205         response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1206             + "perms/ns/" + authNamespace, HttpMethod.GET, entity, String.class);
1207         String res = response.getBody();
1208         logger.debug(EELFLoggerDelegate.debugLogger,
1209             "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
1210             response.getBody());
1211         JSONObject jsonObj = new JSONObject(res);
1212         JSONArray extPerms = jsonObj.getJSONArray("perm");
1213         for (int i = 0; i < extPerms.length(); i++) {
1214             if (extPerms.getJSONObject(i).getString("type").equals(authNamespace + ".access")) {
1215                 extPerms.remove(i);
1216                 i--;
1217             }
1218         }
1219         return extPerms;
1220     }
1221
1222     public void syncRoleFunctionFromExternalAccessSystem(FnApp app) {
1223         try {
1224             // get Permissions from External Auth System
1225             JSONArray extPerms = getExtAuthPermissions(app.getAuthNamespace());
1226             List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1227             final Map<String, EpAppFunction> roleFuncMap = new HashMap<>();
1228             List<EpAppFunction> appFunctions = epAppFunctionService.getAllRoleFunctions(app.getId());
1229             if (!appFunctions.isEmpty()) {
1230                 for (EpAppFunction roleFunc : appFunctions) {
1231                     roleFuncMap.put(roleFunc.getFunctionCd(), roleFunc);
1232                 }
1233             }
1234             // get Roles for portal in DB
1235             List<FnRole> portalRoleList = getGlobalRolesOfPortal();
1236             final Map<String, FnRole> existingPortalRolesMap = new HashMap<>();
1237             for (FnRole epRole : portalRoleList) {
1238                 existingPortalRolesMap.put(epRole.getRoleName().replaceAll(
1239                     EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1240             }
1241             // get Roles in DB
1242             final Map<String, FnRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
1243             // store External Permissions with Pipe and without Pipe (just
1244             // instance)
1245             final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1246             final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1247             for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1248                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1249                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1250                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1251             }
1252             // Add if new functions and app role functions were added in
1253             // external auth system
1254             for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1255                 String code = permsDetail.getInstance();
1256                 EpAppFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1257                 List<EpAppFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1258                     getFunctionCodeKey);
1259                 List<String> roles = permsDetail.getRoles();
1260                 if (roles != null) {
1261                     addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
1262                         existingPortalRolesMap);
1263                 }
1264             }
1265             // Check if function does exits in External Auth System but exits in
1266             // local then delete function and its dependencies
1267             for (EpAppFunction roleFunc : appFunctions) {
1268                 try {
1269                     ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1270                         .get(roleFunc.getFunctionCd());
1271                     if (null == getFunctionCodeContainsPipeKey) {
1272                         ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getFunctionCd());
1273                         if (null == getFunctionCodeKey) {
1274                             deleteAppRoleFuncDoesNotExitsInExtSystem(app.getId(), roleFunc.getFunctionCd());
1275                         }
1276                     }
1277                 } catch (Exception e) {
1278                     logger.error(EELFLoggerDelegate.errorLogger,
1279                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1280                 }
1281             }
1282             logger.debug(EELFLoggerDelegate.debugLogger,
1283                 "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1284         } catch (Exception e) {
1285             logger.error(EELFLoggerDelegate.errorLogger,
1286                 "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1287         }
1288     }
1289
1290     private List<EpAppFunction> addGetLocalFunction(FnApp app,
1291         final Map<String, EpAppFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
1292         EpAppFunction getFunctionCodeKey) {
1293         String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
1294             getFunctionCodeKey);
1295         List<EpAppFunction> roleFunctionList = epAppFunctionService
1296             .getAppFunctionOnCodeAndAppId(app.getId(), finalFunctionCodeVal);
1297         if (roleFunctionList.isEmpty()) {
1298             roleFunctionList = epAppFunctionService.getAppFunctionOnCodeAndAppId(app.getId(), code);
1299         }
1300         return roleFunctionList;
1301     }
1302
1303     private String addToLocalIfFunctionNotExists(FnApp app, final Map<String, EpAppFunction> roleFuncMap,
1304         ExternalAccessPermsDetail permsDetail, String code, EpAppFunction getFunctionCodeKey) {
1305         String finalFunctionCodeVal = "";
1306         if (null == getFunctionCodeKey) {
1307             finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
1308             EpAppFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
1309             // If function does not exist in local then add!
1310             if (null == checkIfCodeStillExits) {
1311                 logger.debug(EELFLoggerDelegate.debugLogger,
1312                     "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
1313                 addFunctionInEcompDB(app, permsDetail, code);
1314                 logger.debug(EELFLoggerDelegate.debugLogger,
1315                     "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
1316             }
1317         }
1318         return finalFunctionCodeVal;
1319     }
1320
1321     private void addFunctionInEcompDB(FnApp app, ExternalAccessPermsDetail permsDetail, String code) {
1322         try {
1323             EpAppFunction addFunction = new EpAppFunction();
1324             addFunction.setAppId(app);
1325             addFunction.setFunctionCd(code);
1326             addFunction.setFunctionName(permsDetail.getDescription());
1327             epAppFunctionService.save(addFunction);
1328         } catch (Exception e) {
1329             logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
1330         }
1331     }
1332
1333     private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(FnApp app, JSONArray extPerms) throws IOException {
1334         ExternalAccessPermsDetail permDetails = null;
1335         List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
1336         for (int i = 0; i < extPerms.length(); i++) {
1337             String description = null;
1338             if (extPerms.getJSONObject(i).has("description")) {
1339                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
1340             } else {
1341                 description =
1342                     extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1) + "|"
1343                         + extPerms.getJSONObject(i).getString("instance") + "|"
1344                         + extPerms.getJSONObject(i).getString("action");
1345             }
1346             if (extPerms.getJSONObject(i).has("roles")) {
1347                 ObjectMapper rolesListMapper = new ObjectMapper();
1348                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
1349                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
1350                     TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
1351                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1352                     extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1)
1353                         + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1354                         + extPerms.getJSONObject(i).getString("action"),
1355                     extPerms.getJSONObject(i).getString("action"), list, description);
1356                 permsDetailList.add(permDetails);
1357             } else {
1358                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
1359                     extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1)
1360                         + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
1361                         + extPerms.getJSONObject(i).getString("action"),
1362                     extPerms.getJSONObject(i).getString("action"), description);
1363                 permsDetailList.add(permDetails);
1364             }
1365         }
1366         return permsDetailList;
1367     }
1368
1369     public List<FnRole> getGlobalRolesOfPortal() {
1370         List<FnRole> globalRoles = new ArrayList<>();
1371         try {
1372             globalRoles = fnRoleService.getGlobalRolesOfPortal();
1373         } catch (Exception e) {
1374             logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
1375         }
1376         return globalRoles;
1377     }
1378
1379     private void deleteAppRoleFuncDoesNotExitsInExtSystem(final Long appId, final String roleFunc) {
1380         logger.debug(EELFLoggerDelegate.debugLogger,
1381             "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc);
1382         epAppRoleFunctionService.deleteByAppIdAndFunctionCd(appId, roleFunc);
1383         logger.debug(EELFLoggerDelegate.debugLogger,
1384             "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc);
1385         logger.debug(EELFLoggerDelegate.debugLogger,
1386             "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc);
1387         epAppFunctionService.deleteByAppIdAndFunctionCd(appId, roleFunc);
1388         logger.debug(EELFLoggerDelegate.debugLogger,
1389             "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc);
1390     }
1391
1392     private CentralV2Role convertRoleToCentralV2Role(FnRole role) {
1393         return CentralV2Role.builder().id(role.getId()).created(role.getCreated())
1394             .modified(role.getModified()).createdId(role.getCreatedId().getId())
1395             .modifiedId(role.getModifiedId().getId())
1396             .rowNum(role.getRowNum()).name(role.getRoleName()).active(role.getActiveYn())
1397             .priority(role.getPriority()).roleFunctions(new TreeSet<>()).childRoles(new TreeSet<>())
1398             .parentRoles(new TreeSet<>()).build();
1399     }
1400
1401     private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(FnApp app, final Map<String, FnRole> currentRolesInDB,
1402         List<EpAppFunction> roleFunctionList, List<String> roles,
1403         Map<String, FnRole> existingPortalRolesMap) throws Exception {
1404         if (!roleFunctionList.isEmpty()) {
1405             final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1406             final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1407             List<LocalRole> localRoleList = localRoleService
1408                 .getCurrentAppRoleFunctions(app.getId(), roleFunctionList.get(0).getFunctionCd());
1409             for (LocalRole localRole : localRoleList) {
1410                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1411                     EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1412             }
1413             for (String addRole : roles) {
1414                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
1415             }
1416             for (String extAuthrole : roles) {
1417                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1418                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
1419                     app.getAuthNamespace());
1420                 if (isNameSpaceMatching) {
1421                     if (!currentAppRoleFunctionsMap
1422                         .containsKey(extAuthrole.substring(app.getAuthNamespace().length() + 1))) {
1423                         FnRole localAddFuntionRole = currentRolesInDB
1424                             .get(extAuthrole.substring(app.getAuthNamespace().length() + 1));
1425                         if (localAddFuntionRole == null) {
1426                             checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1427                         } else {
1428                             EpAppRoleFunction addAppRoleFunc = new EpAppRoleFunction();
1429                             addAppRoleFunc.setAppId(app);
1430                             addAppRoleFunc.setEpAppFunction(roleFunctionList.get(0));
1431                             addAppRoleFunc.setFnRole(localAddFuntionRole);
1432                             epAppRoleFunctionService.save(addAppRoleFunc);
1433                         }
1434                     }
1435                     // This block is to save global role function if exists
1436                 } else {
1437                     String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1438                     boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1439                     if (checkIfGlobalRoleExists) {
1440                         FnRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1441                         EpAppRoleFunction addGlobalRoleFunctions = new EpAppRoleFunction();
1442                         List<EpAppRoleFunction> currentGlobalRoleFunctionsList = epAppRoleFunctionService
1443                             .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), role.getId());
1444                         boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
1445                             .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getEpAppFunction()
1446                                 .getFunctionCd()
1447                                 .equals(roleFunctionList.get(0).getFunctionCd()));
1448                         if (!checkIfRoleFunctionExists) {
1449                             addGlobalRoleFunctions.setAppId(app);
1450                             addGlobalRoleFunctions.setFnRole(role);
1451                             if (!app.getId().equals(role.getAppRoleId())) {
1452                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1453                             } else {
1454                                 addGlobalRoleFunctions.setRoleAppId(null);
1455                             }
1456                             addGlobalRoleFunctions.setEpAppFunction(roleFunctionList.get(0));
1457                             epAppRoleFunctionService.save(addGlobalRoleFunctions);
1458                         }
1459                     }
1460                 }
1461             }
1462             for (LocalRole localRoleDelete : localRoleList) {
1463                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
1464                     .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
1465                     epAppRoleFunctionService
1466                         .deleteByAppIdAndFunctionCdAndRoleId(app.getId(), roleFunctionList.get(0).getFunctionCd(),
1467                             localRoleDelete.getRoleId());
1468                 }
1469             }
1470         }
1471     }
1472
1473     private void checkAndAddRoleInDB(FnApp app, final Map<String, FnRole> currentRolesInDB,
1474         List<EpAppFunction> roleFunctionList, String roleList) throws Exception {
1475         if (!currentRolesInDB.containsKey(roleList.substring(app.getAuthNamespace().length() + 1))) {
1476             FnRole role = addRoleInDBIfDoesNotExists(app.getId(),
1477                 roleList.substring(app.getAuthNamespace().length() + 1));
1478             addRoleDescriptionInExtSystem(role.getRoleName(), app.getAuthNamespace());
1479             if (!roleFunctionList.isEmpty()) {
1480                 try {
1481                     EpAppRoleFunction addAppRoleFunc = new EpAppRoleFunction();
1482                     addAppRoleFunc.setAppId(app);
1483                     addAppRoleFunc.setEpAppFunction(roleFunctionList.get(0));
1484                     addAppRoleFunc.setFnRole(role);
1485                     epAppRoleFunctionService.save(addAppRoleFunc);
1486                 } catch (Exception e) {
1487                     logger.error(EELFLoggerDelegate.errorLogger,
1488                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
1489                 }
1490             }
1491         }
1492     }
1493
1494     private FnRole addRoleInDBIfDoesNotExists(final Long appId, final String role) {
1495         FnRole setNewRole = new FnRole();
1496         try {
1497             boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, appId);
1498             List<FnRole> getRoleCreated = null;
1499             if (!appId.equals(PortalConstants.PORTAL_APP_ID)) {
1500                 List<FnRole> roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
1501                 if (!isCreated) {
1502                     FnRole epUpdateRole = roleCreated.get(0);
1503                     epUpdateRole.setAppRoleId(epUpdateRole.getId());
1504                     fnRoleService.saveOne(epUpdateRole);
1505                     getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
1506                 } else {
1507                     getRoleCreated = roleCreated;
1508                 }
1509             } else {
1510                 getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role);
1511             }
1512             if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
1513                 FnRole roleObject = getRoleCreated.get(0);
1514                 setNewRole.setId(roleObject.getId());
1515                 setNewRole.setRoleName(roleObject.getRoleName());
1516                 setNewRole.setActiveYn(roleObject.getActiveYn());
1517                 setNewRole.setPriority(roleObject.getPriority());
1518             }
1519         } catch (Exception e) {
1520             logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
1521         }
1522         return setNewRole;
1523     }
1524
1525     private boolean checkIfRoleExitsElseCreateInSyncFunctions(final String role, final long appId) {
1526         boolean isCreated;
1527         List<FnRole> roleCreated = null;
1528         if (appId == PortalConstants.PORTAL_APP_ID) {
1529             roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role);
1530         } else {
1531             roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
1532         }
1533         if (roleCreated == null || roleCreated.isEmpty()) {
1534             FnRole epRoleNew = new FnRole();
1535             epRoleNew.setActiveYn(true);
1536             epRoleNew.setRoleName(role);
1537             if (appId == PortalConstants.PORTAL_APP_ID) {
1538                 epRoleNew.setAppId(null);
1539             } else {
1540                 epRoleNew.setAppId(appId);
1541             }
1542             fnRoleService.saveOne(epRoleNew);
1543             isCreated = false;
1544         } else {
1545             isCreated = true;
1546         }
1547         return isCreated;
1548     }
1549
1550     private String updateExistingRoleInExternalSystem(final String roleName, final String authNamespace)
1551         throws JsonProcessingException {
1552         ObjectMapper mapper = new ObjectMapper();
1553         String addNewRole = "";
1554         ExternalAccessRole extRole = new ExternalAccessRole();
1555         extRole.setName(authNamespace + "." + roleName
1556             .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1557         extRole.setDescription(String.valueOf(roleName));
1558         addNewRole = mapper.writeValueAsString(extRole);
1559         return addNewRole;
1560     }
1561
1562     private boolean addRoleDescriptionInExtSystem(final String roleName, final String authNamespace) throws Exception {
1563         boolean status = false;
1564         try {
1565             String addRoleNew = updateExistingRoleInExternalSystem(roleName, authNamespace);
1566             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1567             HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1568             template.exchange(
1569                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1570                 HttpMethod.PUT, entity, String.class);
1571             status = true;
1572         } catch (HttpClientErrorException e) {
1573             logger.error(EELFLoggerDelegate.errorLogger,
1574                 "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
1575             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1576         } catch (Exception e) {
1577             logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
1578         }
1579         return status;
1580     }
1581
1582     public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
1583         List<CentralRole> cenRoleList = new ArrayList<>();
1584         for (CentralV2Role v2CenRole : v2CenRoleList) {
1585             SortedSet<EpAppFunction> cenRoleFuncList = new TreeSet<>();
1586             for (DomainVo vo : v2CenRole.getRoleFunctions()) {
1587                 Optional<FnRoleFunction> v2CenRoleFunc = fnRoleFunctionService.findById(vo.getId());
1588                 if (v2CenRoleFunc.isPresent()) {
1589                     EpAppFunction roleFunc = EpAppFunction.builder()
1590                         .functionCd(v2CenRoleFunc.get().getFunctionCd().getCode())
1591                         .functionName(v2CenRoleFunc.get().getRole().getRoleName())
1592                         .build();
1593                     cenRoleFuncList.add(roleFunc);
1594                 }
1595             }
1596             CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(),
1597                 v2CenRole.getPriority(), cenRoleFuncList);
1598             cenRoleList.add(role);
1599         }
1600         return cenRoleList;
1601     }
1602
1603     public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1604         boolean response = false;
1605         String message = "";
1606         try {
1607             FnApp app = getApp(uebkey).get(0);
1608             addRoleInEcompDB(saveRole, app);
1609             response = true;
1610         } catch (Exception e) {
1611             message = e.getMessage();
1612             logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1613         }
1614         return new ExternalRequestFieldsValidator(response, message);
1615     }
1616
1617     @Transactional(rollbackFor = Exception.class)
1618     public void addRoleInEcompDB(Role addRoleInDB, FnApp app) throws Exception {
1619         boolean result;
1620         FnRole epRole;
1621         Set<FnFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
1622         List<FnFunction> roleFunctionListNew = new ArrayList<>();
1623         ObjectMapper mapper = new ObjectMapper();
1624         for (Object nextValue : roleFunctionList) {
1625             FnFunction roleFunction = mapper.convertValue(nextValue, FnFunction.class);
1626             roleFunctionListNew.add(roleFunction);
1627         }
1628         List<FnFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
1629         try {
1630             if (addRoleInDB.getId() == null) { // check if it is new role
1631                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1632                     checkIfRoleExitsInExternalSystem(addRoleInDB, app);
1633                 }
1634                 FnRole epRoleNew = new FnRole();
1635                 epRoleNew.setActiveYn(addRoleInDB.getActive());
1636                 epRoleNew.setRoleName(addRoleInDB.getName());
1637                 epRoleNew.setPriority(addRoleInDB.getPriority());
1638                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1639                     epRoleNew.setAppId(null);
1640                 } else {
1641                     epRoleNew.setAppId(app.getId());
1642                 }
1643                 fnRoleService.saveOne(epRoleNew);
1644                 List<FnRole> getRoleCreated = null;
1645                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1646                     List<FnRole> roleCreated = fnRoleService
1647                         .retrieveAppRolesByRoleNameAndByAppId(addRoleInDB.getName(), app.getId());
1648                     FnRole epUpdateRole = roleCreated.get(0);
1649                     epUpdateRole.setAppRoleId(epUpdateRole.getId());
1650                     fnRoleService.saveOne(epUpdateRole);
1651                     getRoleCreated = fnRoleService
1652                         .retrieveAppRolesByRoleNameAndByAppId(addRoleInDB.getName(), app.getId());
1653                 } else {
1654                     getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(addRoleInDB.getName());
1655                 }
1656                 // Add role in External Auth system
1657                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1658                     addNewRoleInExternalSystem(getRoleCreated, app);
1659                 }
1660                 result = true;
1661             } else { // if role already exists then update it
1662                 FnRole globalRole = null;
1663                 List<FnRole> applicationRoles;
1664                 List<FnRole> globalRoleList = getGlobalRolesOfPortal();
1665                 boolean isGlobalRole = false;
1666                 if (!globalRoleList.isEmpty()) {
1667                     FnRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
1668                         .orElse(null);
1669                     if (role != null) {
1670                         globalRole = role;
1671                         isGlobalRole = true;
1672                     }
1673                 }
1674                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
1675                     || (globalRole != null && app.getId() != globalRole.getAppId())) {
1676                     applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
1677                 } else {
1678                     applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app.getId());
1679                 }
1680                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1681                     updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
1682                     // Add all user to the re-named role in external auth system
1683                     if (!applicationRoles.isEmpty()
1684                         && !addRoleInDB.getName().equals(applicationRoles.get(0).getRoleName())) {
1685                         bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
1686                             addRoleInDB.getName());
1687                     }
1688                 }
1689                 deleteRoleFunction(app, applicationRoles);
1690                 if (!applicationRoles.isEmpty()) {
1691                     epRole = applicationRoles.get(0);
1692                     epRole.setRoleName(addRoleInDB.getName());
1693                     epRole.setPriority(addRoleInDB.getPriority());
1694                     epRole.setActiveYn(addRoleInDB.getActive());
1695                     if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1696                         epRole.setAppId(null);
1697                         epRole.setAppRoleId(null);
1698                     } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
1699                         && applicationRoles.get(0).getAppRoleId() == null) {
1700                         epRole.setAppRoleId(epRole.getId());
1701                     }
1702                     fnRoleService.saveOne(epRole);
1703                 }
1704                 Long roleAppId = null;
1705                 if (globalRole != null && !app.getId().equals(globalRole.getAppId())) {
1706                     roleAppId = PortalConstants.PORTAL_APP_ID;
1707                 }
1708                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
1709                 result = true;
1710             }
1711         } catch (Exception e) {
1712             logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
1713             throw e;
1714         }
1715     }
1716
1717     private void saveRoleFunction(List<FnFunction> roleFunctionListNew, FnApp app, List<FnRole> applicationRoles,
1718         Long roleAppId) {
1719         for (FnFunction roleFunc : roleFunctionListNew) {
1720             String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1721             EpAppRoleFunction appRoleFunc = new EpAppRoleFunction();
1722             appRoleFunc.setAppId(app);
1723             appRoleFunc.setFnRole(applicationRoles.get(0));
1724             appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
1725             List<EpAppFunction> roleFunction = epAppFunctionService.getRoleFunction(roleFunc.getCode(), app.getId());
1726             if (roleFunction.isEmpty()) {
1727                 roleFunction = epAppFunctionService.getRoleFunction(code, app.getId());
1728             }
1729             if (roleFunction.size() > 1) {
1730                 EpAppFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
1731                 appRoleFunc.setEpAppFunction(getExactFunctionCode);
1732             } else {
1733                 appRoleFunc.setEpAppFunction(roleFunction.get(0));
1734             }
1735             epAppRoleFunctionService.save(appRoleFunc);
1736         }
1737     }
1738
1739     @Transactional(propagation = Propagation.REQUIRED)
1740     public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1741         boolean result;
1742         try {
1743             List<FnRole> epRoleList;
1744             FnApp app = getApp(uebkey).get(0);
1745             if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1746                 epRoleList = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(deleteRole);
1747             } else {
1748                 epRoleList = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(deleteRole, app.getId());
1749             }
1750             if (!epRoleList.isEmpty()) {
1751                 // Delete app role functions before deleting role
1752                 deleteRoleFunction(app, epRoleList);
1753                 if (app.getId() == 1) {
1754                     // Delete fn_user_ role
1755                     String query =
1756                         "DELETE FROM FN_USER_ROLE WHERE " + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList
1757                             .get(0).getId();
1758                     entityManager.createQuery(query).executeUpdate();
1759                     boolean isPortalRequest = false;
1760                     deleteRoleDependencyRecords(epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1761                 }
1762                 deleteRoleInExternalAuthSystem(epRoleList, app);
1763                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1764                 fnRoleService.delete(epRoleList.get(0));
1765             }
1766             result = true;
1767         } catch (Exception e) {
1768             logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1769             result = false;
1770         }
1771         return result;
1772     }
1773
1774     private void deleteRoleInExternalAuthSystem(List<FnRole> epRoleList, FnApp app) throws Exception {
1775         ResponseEntity<String> deleteResponse;
1776         ResponseEntity<String> res = getNameSpaceIfExists(app);
1777         if (res.getStatusCode() == HttpStatus.OK) {
1778             // Delete Role in External System
1779             String deleteRoleKey = "{\"name\":\"" + app.getAuthNamespace() + "." + epRoleList.get(0).getRoleName()
1780                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1781             deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1782             if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1783                 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1784                 logger.error(EELFLoggerDelegate.errorLogger,
1785                     "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1786                     deleteResponse.getBody());
1787             }
1788             logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1789         }
1790     }
1791
1792     private void deleteRoleFunction(FnApp app, List<FnRole> role) {
1793         List<EpAppRoleFunction> appRoleFunctionList = epAppRoleFunctionService
1794             .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), role.get(0).getId());
1795         epAppRoleFunctionService.deleteInBatch(appRoleFunctionList);
1796     }
1797
1798     public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1799         List<CentralV2Role> roleList = new ArrayList<>();
1800         try {
1801             List<FnApp> app = getApp(uebkey);
1802             Long appId = null;
1803             if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1804                 appId = app.get(0).getId();
1805             }
1806             List<FnRole> epRole;
1807             if (appId == null) {
1808                 epRole = fnRoleService.retrieveActiveRolesWhereAppIdIsNull();
1809             } else {
1810                 epRole = fnRoleService.retrieveActiveRolesOfApplication(appId);
1811             }
1812             roleList = createCentralRoleObject(app, epRole, roleList);
1813             List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1814             if (globalRoleList.size() > 0) {
1815                 roleList.addAll(globalRoleList);
1816             }
1817         } catch (Exception e) {
1818             logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1819             throw e;
1820         }
1821         return roleList;
1822     }
1823
1824     public Integer bulkUploadRoles(String uebkey) throws Exception {
1825         List<FnApp> app = getApp(uebkey);
1826         List<FnRole> roles = getAppRoles(app.get(0).getId());
1827         List<CentralV2Role> cenRoleList = new ArrayList<>();
1828         final Map<String, Long> params = new HashMap<>();
1829         Integer rolesListAdded = 0;
1830         try {
1831             cenRoleList = createCentralRoleObject(app, roles, cenRoleList);
1832             ObjectMapper mapper = new ObjectMapper();
1833             mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
1834             String roleList = mapper.writeValueAsString(cenRoleList);
1835             List<Role> roleObjectList = mapper.readValue(roleList,
1836                 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
1837             for (Role role : roleObjectList) {
1838                 addRoleInExternalSystem(role, app.get(0));
1839                 rolesListAdded++;
1840             }
1841             if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1842                 // Add Account Admin role in External AUTH System
1843                 try {
1844                     String addAccountAdminRole = "";
1845                     ExternalAccessRole extRole = new ExternalAccessRole();
1846                     extRole.setName(app.get(0).getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE
1847                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1848                     addAccountAdminRole = mapper.writeValueAsString(extRole);
1849                     HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1850                     HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
1851                     template.exchange(
1852                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1853                         HttpMethod.POST, entity, String.class);
1854                     rolesListAdded++;
1855                 } catch (HttpClientErrorException e) {
1856                     logger.error(EELFLoggerDelegate.errorLogger,
1857                         "HttpClientErrorException - Failed to create Account Admin role", e);
1858                     EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1859                 } catch (Exception e) {
1860                     if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1861                         logger.error(EELFLoggerDelegate.errorLogger,
1862                             "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
1863                             e);
1864                     } else {
1865                         logger.error(EELFLoggerDelegate.errorLogger,
1866                             "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
1867                     }
1868                 }
1869             }
1870         } catch (Exception e) {
1871             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
1872             throw e;
1873         }
1874         return rolesListAdded;
1875     }
1876
1877     private void addRoleInExternalSystem(Role role, FnApp app) throws Exception {
1878         String addRoleNew = updateExistingRoleInExternalSystem(role.getName(), app.getAuthNamespace());
1879         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1880         try {
1881             HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
1882             template.exchange(
1883                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
1884                 HttpMethod.POST, entity, String.class);
1885         } catch (HttpClientErrorException e) {
1886             logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
1887                 e);
1888             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1889         } catch (Exception e) {
1890             if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1891                 logger.error(EELFLoggerDelegate.errorLogger,
1892                     "addRoleInExternalSystem: Role already exits but does not break functionality", e);
1893             } else {
1894                 logger.error(EELFLoggerDelegate.errorLogger,
1895                     "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
1896             }
1897         }
1898     }
1899
1900     public Integer bulkUploadFunctions(String uebkey) throws Exception {
1901         FnApp app = getApp(uebkey).get(0);
1902         List<FnRoleFunction> roleFuncList = fnRoleFunctionService.findAll();
1903         EpAppFunction cenRoleFunc;
1904         Integer functionsAdded = 0;
1905         try {
1906             for (FnRoleFunction roleFunc : roleFuncList) {
1907                 cenRoleFunc = EpAppFunction.builder()
1908                     .functionCd(roleFunc.getFunctionCd().getName())
1909                     .roleId(roleFunc.getRole().getId())
1910                     .build();
1911                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
1912                 functionsAdded++;
1913             }
1914         } catch (HttpClientErrorException e) {
1915             logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
1916             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1917         } catch (Exception e) {
1918             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
1919         }
1920         return functionsAdded;
1921     }
1922
1923     public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
1924         FnApp app = getApp(uebkey).get(0);
1925         List<FnRole> roles = getAppRoles(app.getId());
1926         Integer roleFunctions = 0;
1927         try {
1928             for (FnRole role : roles) {
1929                 List<BulkUploadRoleFunction> appRoleFunc = bulkUploadUserRolesService
1930                     .uploadAllRoleFunctions(role.getId());
1931                 if (!appRoleFunc.isEmpty()) {
1932                     for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
1933                         addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
1934                         roleFunctions++;
1935                     }
1936                 }
1937             }
1938         } catch (HttpClientErrorException e) {
1939             logger.error(EELFLoggerDelegate.errorLogger,
1940                 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
1941             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1942         } catch (Exception e) {
1943             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
1944         }
1945         return roleFunctions;
1946     }
1947
1948     private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, FnRole role, FnApp app) {
1949         String type;
1950         String instance = "";
1951         String action = "";
1952         if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
1953             type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
1954             instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
1955             action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
1956         } else {
1957             type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
1958             instance = addRoleFunc.getFunctionCd();
1959             action = "*";
1960         }
1961         ExternalAccessRolePerms extRolePerms = null;
1962         ExternalAccessPerms extPerms = null;
1963         ObjectMapper mapper = new ObjectMapper();
1964         try {
1965             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1966             extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, instance, action,
1967                 addRoleFunc.getFunctionName());
1968             extRolePerms = new ExternalAccessRolePerms(extPerms, app.getAuthNamespace() + "." + role.getRoleName()
1969                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
1970             String updateRolePerms = mapper.writeValueAsString(extRolePerms);
1971             HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
1972             template.exchange(
1973                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
1974                 HttpMethod.POST, entity, String.class);
1975         } catch (Exception e) {
1976             if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
1977                 logger.error(EELFLoggerDelegate.errorLogger,
1978                     "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
1979                     e);
1980             } else {
1981                 logger.error(EELFLoggerDelegate.errorLogger,
1982                     "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
1983             }
1984         }
1985     }
1986
1987
1988     public Integer bulkUploadUserRoles(String uebkey) throws Exception {
1989         FnApp app = getApp(uebkey).get(0);
1990         List<BulkUploadUserRoles> userRolesList;
1991         Integer userRolesAdded = 0;
1992         if (app.getAuthCentral()) {
1993             userRolesList = bulkUploadUserRolesService.getBulkUserRoles(app.getUebKey());
1994             for (BulkUploadUserRoles userRolesUpload : userRolesList) {
1995                 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
1996                     addUserRoleInExternalSystem(userRolesUpload);
1997                     userRolesAdded++;
1998                 }
1999             }
2000         }
2001         return userRolesAdded;
2002     }
2003
2004     public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2005         FnApp app = getApp(uebkey).get(0);
2006         List<EpAppFunction> roleFuncList = epAppFunctionService.getAllRoleFunctions(app.getId());
2007         Integer functionsAdded = 0;
2008         try {
2009             for (EpAppFunction roleFunc : roleFuncList) {
2010                 addFunctionInExternalSystem(roleFunc, app);
2011                 functionsAdded++;
2012             }
2013         } catch (HttpClientErrorException e) {
2014             logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
2015                 e);
2016             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2017         } catch (Exception e) {
2018             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2019         }
2020         return functionsAdded;
2021     }
2022
2023     public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2024         FnApp app = getApp(uebkey).get(0);
2025         for (Role role : roleList) {
2026             addRoleInExternalSystem(role, app);
2027         }
2028     }
2029
2030     private void addFunctionInExternalSystem(EpAppFunction roleFunc, FnApp app) throws Exception {
2031         ObjectMapper mapper = new ObjectMapper();
2032         ExternalAccessPerms extPerms = new ExternalAccessPerms();
2033         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2034         String type = "";
2035         String instance = "";
2036         String action = "";
2037         if ((roleFunc.getFunctionCd().contains(FUNCTION_PIPE))
2038             || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2039             type = EcompPortalUtils.getFunctionType(roleFunc.getFunctionCd());
2040             instance = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
2041             action = EcompPortalUtils.getFunctionAction(roleFunc.getFunctionCd());
2042         } else {
2043             type = roleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2044             instance = roleFunc.getFunctionCd();
2045             action = "*";
2046         }
2047         try {
2048             extPerms.setAction(action);
2049             extPerms.setInstance(instance);
2050             extPerms.setType(app.getAuthNamespace() + "." + type);
2051             extPerms.setDescription(roleFunc.getFunctionName());
2052             String addFunction = mapper.writeValueAsString(extPerms);
2053             HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2054             logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2055                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2056             ResponseEntity<String> addPermResponse = template.exchange(
2057                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2058                 HttpMethod.POST, entity, String.class);
2059             logger.debug(EELFLoggerDelegate.debugLogger,
2060                 "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2061                 addPermResponse.getStatusCode().value(), addFunction);
2062         } catch (HttpClientErrorException e) {
2063             logger.error(EELFLoggerDelegate.errorLogger,
2064                 "HttpClientErrorException - Failed to add function in external central auth system", e);
2065             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2066             throw e;
2067         } catch (Exception e) {
2068             logger.error(EELFLoggerDelegate.errorLogger,
2069                 "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2070             throw e;
2071         }
2072     }
2073
2074     public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2075         FnApp app = getApp(uebkey).get(0);
2076         List<FnRole> roles = getAppRoles(app.getId());
2077         Integer roleFunctions = 0;
2078         try {
2079             for (FnRole role : roles) {
2080                 List<BulkUploadRoleFunction> appRoleFunc = bulkUploadUserRolesService
2081                     .uploadPartnerRoleFunctions(role.getId());
2082                 if (!appRoleFunc.isEmpty()) {
2083                     for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2084                         addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2085                         roleFunctions++;
2086                     }
2087                 }
2088             }
2089             // upload global role functions to ext auth system
2090             if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2091                 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2092             }
2093         } catch (HttpClientErrorException e) {
2094             logger.error(EELFLoggerDelegate.errorLogger,
2095                 "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2096             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2097         } catch (Exception e) {
2098             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2099         }
2100         return roleFunctions;
2101     }
2102
2103     private Integer bulkUploadGlobalRoleFunctions(FnApp app, Integer roleFunctions) throws Exception {
2104         try {
2105             //TODO HARDCODED ID!!!!!
2106             FnApp portalApp = fnAppService.getById(1L);
2107             String getBulkUploadPartnerGlobalRoleFunctions =
2108                 "select distinct fr.role_id, fr.role_name, fr.active_yn, fr.priority, epr.function_cd, ep.function_name, ep.app_id, epr.role_app_id"
2109                     + " from fn_role fr, ep_app_function ep, ep_app_role_function epr"
2110                     + " where fr.role_id = epr.role_id and ep.function_cd = epr.function_cd and ep.app_id = epr.app_id and  epr.app_id = :appId and epr.role_app_id = 1";
2111             List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = entityManager
2112                 .createQuery(getBulkUploadPartnerGlobalRoleFunctions)
2113                 .setParameter("appId", app.getId())
2114                 .getResultList();
2115             ObjectMapper mapper = new ObjectMapper();
2116             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2117             for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2118                 ExternalAccessRolePerms extRolePerms;
2119                 ExternalAccessPerms extPerms;
2120                 String type = "";
2121                 String instance = "";
2122                 String action = "";
2123                 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2124                     type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2125                     instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2126                     action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2127                 } else {
2128                     type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2129                     instance = globalRoleFunc.getFunctionCd();
2130                     action = "*";
2131                 }
2132                 extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, instance, action);
2133                 extRolePerms = new ExternalAccessRolePerms(extPerms,
2134                     portalApp.getAuthNamespace() + "." + globalRoleFunc.getRoleName().replaceAll(
2135                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2136                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2137                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2138                 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2139                 roleFunctions++;
2140             }
2141         } catch (HttpClientErrorException e) {
2142             logger.error(EELFLoggerDelegate.errorLogger,
2143                 "HttpClientErrorException - Failed to add role function in external central auth system", e);
2144             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2145             throw e;
2146         } catch (Exception e) {
2147             logger.error(EELFLoggerDelegate.errorLogger,
2148                 "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2149             throw e;
2150         }
2151         return roleFunctions;
2152     }
2153
2154     private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
2155         logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
2156             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
2157         ResponseEntity<String> addPermResponse = template.exchange(
2158             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2159             HttpMethod.POST, entity, String.class);
2160         logger.debug(EELFLoggerDelegate.debugLogger,
2161             "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
2162             addPermResponse.getStatusCode().value(), updateRolePerms);
2163     }
2164
2165     public List<String> getMenuFunctionsList(String uebkey) throws Exception {
2166         List<String> appMenuFunctionsList = null;
2167         List<String> appMenuFunctionsFinalList = new ArrayList<>();
2168         try {
2169             FnApp app = getApp(uebkey).get(0);
2170             String getMenuFunctions = "select f.function_cd from ep_app_function f"
2171                 + " where f.app_id =:appId"
2172                 + " UNION"
2173                 + " select epa.function_cd from fn_role fnr, ep_app_role_function epr, ep_app_function epa where epr.role_id = fnr.role_id"
2174                 + " and epa.function_cd = epr.function_cd and fnr.role_name like 'global%' and fnr.app_id is null and epr.app_id = 1";
2175             appMenuFunctionsList = entityManager.createQuery(getMenuFunctions).setParameter(APP_ID, app.getId())
2176                 .getResultList();
2177             for (String appMenuFunction : appMenuFunctionsList) {
2178                 if (appMenuFunction.contains(FUNCTION_PIPE)) {
2179                     appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
2180                 } else {
2181                     appMenuFunctionsFinalList.add(appMenuFunction);
2182                 }
2183             }
2184         } catch (Exception e) {
2185             logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
2186             return appMenuFunctionsFinalList;
2187         }
2188         return appMenuFunctionsFinalList;
2189     }
2190
2191     public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
2192         List<String> usersList = new ArrayList<>();
2193         List<EcompUser> usersfinalList = new ArrayList<>();
2194         try {
2195             FnApp app = getApp(uebkey).get(0);
2196             String ApplicationUserRoles =
2197                 "select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, fu.login_id, \n"
2198                     + " fu.active_yn , fr.app_role_id, fr.role_name, epr.function_cd , epf.function_name\n"
2199                     + " from fn_user fu, fn_role fr, fn_user_role fur, ep_app_role_function epr , ep_app_function epf\n"
2200                     + " where fu.user_id = fur.user_id and fu.active_yn='Y' and fur.role_id = fr.role_id and fr.app_id =:appId and fr.active_yn='Y' and epr.function_cd= epf.function_cd and epf.app_id=epr.app_id and fur.role_id=epr.role_id\n"
2201                     + " union\n"
2202                     + " select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, \n"
2203                     + " fu.login_id, fu.active_yn , fr.role_id, fr.role_name, earf.function_cd , eaf.function_name\n"
2204                     + " from fn_user_role a, fn_role fr, fn_user fu , ep_app_role_function earf, ep_app_function eaf\n"
2205                     + " where a.role_id in (select b.role_id from ep_app_role_function b where b.role_app_id = 1 and b.app_id =:appId) and a.user_id =fu.user_id and a.role_id = fr.role_id and fr.active_yn='Y' and fu.active_yn='Y'\n"
2206                     + " and earf.role_id = a.role_id and earf.function_cd = eaf.function_cd and earf.app_id = eaf.app_id  and earf.role_app_id = 1 and fr.active_yn='Y' and fu.active_yn='Y'";
2207
2208             List<EcompUserRoles> userList = entityManager.createQuery(ApplicationUserRoles)
2209                 .setParameter("appId", app.getId()).getResultList();
2210             for (EcompUserRoles ecompUserRole : userList) {
2211                 boolean found = false;
2212                 Set<EcompRole> roles = null;
2213                 for (EcompUser user : usersfinalList) {
2214                     if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
2215                         EcompRole ecompRole = new EcompRole();
2216                         ecompRole.setId(ecompUserRole.getRoleId());
2217                         ecompRole.setName(ecompUserRole.getRoleName());
2218                         roles = user.getRoles();
2219                         EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
2220                             .findAny().orElse(null);
2221                         SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
2222                         if (role != null) {
2223                             roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
2224                         }
2225                         String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
2226                         functionCode = EPUserUtils.decodeFunctionCode(functionCode);
2227                         EcompRoleFunction epRoleFunction = new EcompRoleFunction();
2228                         epRoleFunction.setName(ecompUserRole.getFunctionName());
2229                         epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
2230                         epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
2231                         epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
2232                         roleFunctionSet.add(epRoleFunction);
2233                         ecompRole.setRoleFunctions(roleFunctionSet);
2234                         roles.add(ecompRole);
2235                         user.setRoles(roles);
2236                         found = true;
2237                         break;
2238                     }
2239                 }
2240                 if (!found) {
2241                     EcompUser epUser = new EcompUser();
2242                     epUser.setOrgId(ecompUserRole.getOrgId());
2243                     epUser.setManagerId(ecompUserRole.getManagerId());
2244                     epUser.setFirstName(ecompUserRole.getFirstName());
2245                     epUser.setLastName(ecompUserRole.getLastName());
2246                     epUser.setPhone(ecompUserRole.getPhone());
2247                     epUser.setEmail(ecompUserRole.getEmail());
2248                     epUser.setOrgUserId(ecompUserRole.getOrgUserId());
2249                     epUser.setOrgCode(ecompUserRole.getOrgCode());
2250                     epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
2251                     epUser.setJobTitle(ecompUserRole.getJobTitle());
2252                     epUser.setLoginId(ecompUserRole.getLoginId());
2253                     epUser.setActive(true);
2254                     roles = new HashSet<>();
2255                     EcompRole ecompRole = new EcompRole();
2256                     ecompRole.setId(ecompUserRole.getRoleId());
2257                     ecompRole.setName(ecompUserRole.getRoleName());
2258                     SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
2259                     String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
2260                     functionCode = EPUserUtils.decodeFunctionCode(functionCode);
2261                     EcompRoleFunction epRoleFunction = new EcompRoleFunction();
2262                     epRoleFunction.setName(ecompUserRole.getFunctionName());
2263                     epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
2264                     epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
2265                     epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
2266                     roleFunctionSet.add(epRoleFunction);
2267                     ecompRole.setRoleFunctions(roleFunctionSet);
2268                     roles.add(ecompRole);
2269                     epUser.setRoles(roles);
2270                     usersfinalList.add(epUser);
2271                 }
2272             }
2273             ObjectMapper mapper = new ObjectMapper();
2274             for (EcompUser u1 : usersfinalList) {
2275                 String str = mapper.writeValueAsString(u1);
2276                 usersList.add(str);
2277             }
2278         } catch (Exception e) {
2279             logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
2280             throw e;
2281         }
2282         return usersfinalList;
2283     }
2284
2285     public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
2286         throws Exception {
2287         List<FnApp> appList = getApp(uebkey);
2288         FnApp app = appList.get(0);
2289         List<FnUser> epUserList;
2290         epUserList = getUser(loginId);
2291         List<EcompRole> missingUserAppRoles = new ArrayList<>();
2292         List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
2293         logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
2294         List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
2295         if (userApplicationsRolesfromDB.size() > 0) {
2296             missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
2297                 .collect(Collectors.toList());
2298         }
2299         List<String> missingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
2300             .collect(Collectors.toList());
2301         logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + missingroleNamesList);
2302
2303         List<EcompRole> finalMissingRoleList = new ArrayList<>();
2304         if (missingUserAppRoles.size() > 0) {
2305             final Map<String, Long> params = new HashMap<>();
2306             for (EcompRole role : missingUserAppRoles) {
2307                 EcompRole epRole = new EcompRole();
2308                 epRole.setId(role.getId());
2309                 epRole.setName(role.getName());
2310                 String getAppRoleFunctionList =
2311                     "SELECT DISTINCT f.app_id , f.function_cd, f.function_name from ep_app_role_function rf, ep_app_function f"
2312                         + " where rf.role_id =:roleId and rf.app_id =:appId and rf.app_id = f.app_id and rf.function_cd = f.function_cd";
2313                 List<EpAppFunction> appRoleFunctionList = entityManager.createQuery(getAppRoleFunctionList)
2314                     .setParameter("roleId", role.getId()).setParameter(APP_ID, app.getId()).getResultList();
2315                 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
2316                 for (EpAppFunction roleFunc : appRoleFunctionList) {
2317                     String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
2318                     String type = getFunctionCodeType(roleFunc.getFunctionCd());
2319                     String action = getFunctionCodeAction(roleFunc.getFunctionCd());
2320                     EcompRoleFunction fun = new EcompRoleFunction();
2321                     fun.setAction(action);
2322                     fun.setCode(functionCode);
2323                     fun.setType(type);
2324                     fun.setName(roleFunc.getFunctionName());
2325                     roleFunctionSet.add(fun);
2326
2327                 }
2328                 epRole.setRoleFunctions(roleFunctionSet);
2329                 finalMissingRoleList.add(epRole);
2330             }
2331         }
2332
2333         return finalMissingRoleList;
2334     }
2335
2336     private List<EcompRole> getUserAppRoles(FnApp app, FnUser user) {
2337         String getUserAppCurrentRoles = "select distinct fu.role_id, fr.user_id, fu.role_name, fu.priority from fn_role fu left outer join fn_user_role fr ON fu.role_id = fr.role_id and fu.app_id = fr.app_id and fr.role_id != 999 where fu.app_id =:appId and fr.user_id =:userId and fu.active_yn='Y' \n";
2338         List<EPUserAppCurrentRoles> userAppsRolesList = entityManager.createQuery(getUserAppCurrentRoles)
2339             .setParameter("appId", app.getId())
2340             .setParameter("userId", user.getId())
2341             .getResultList();
2342         List<EcompRole> setUserRoles = new ArrayList<>();
2343         for (EPUserAppCurrentRoles role : userAppsRolesList) {
2344             logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
2345                 role.getRoleName());
2346             EcompRole ecompRole = new EcompRole();
2347             ecompRole.setId(role.getRoleId());
2348             ecompRole.setName(role.getRoleName());
2349             setUserRoles.add(ecompRole);
2350         }
2351         logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
2352             setUserRoles.size());
2353         return setUserRoles;
2354     }
2355
2356     private List<FnUser> getUser(String loginId) throws InvalidUserException {
2357         List<FnUser> userList = fnUserService.getUserWithOrgUserId(loginId);
2358         if (userList.isEmpty()) {
2359             throw new InvalidUserException("User not found");
2360         }
2361         return userList;
2362     }
2363
2364     @Transactional(propagation = Propagation.REQUIRED)
2365     public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
2366         throws Exception {
2367         String message = "";
2368         boolean response = false;
2369         FnApp app = null;
2370         try {
2371             List<FnRole> epRoleList = null;
2372             app = getApp(uebkey).get(0);
2373             if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2374                 epRoleList = getPortalAppRoleInfo(roleId);
2375             } else {
2376                 epRoleList = getPartnerAppRoleInfo(roleId, app.getId());
2377             }
2378             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2379                 // Delete User Role in External System before deleting role
2380                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
2381             }
2382             // Delete user app roles
2383             fnRoleService.delete(epRoleList.get(0));
2384             boolean isPortalRequest = false;
2385             deleteRoleDependencyRecords(epRoleList.get(0).getId(), app.getId(), isPortalRequest);
2386             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2387                 // Final call to delete role once all dependencies has been
2388                 // deleted
2389                 deleteRoleInExternalAuthSystem(epRoleList, app);
2390             }
2391             fnRoleService.delete(epRoleList.get(0));
2392             logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
2393             response = true;
2394         } catch (HttpClientErrorException e) {
2395             logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
2396             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2397             message = e.getMessage();
2398         } catch (Exception e) {
2399             logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
2400             message = e.getMessage();
2401         }
2402         return new ExternalRequestFieldsValidator(response, message);
2403     }
2404
2405     @Transactional(propagation = Propagation.REQUIRED)
2406     public void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
2407         throws Exception {
2408         try {
2409             String sql = "";
2410             Query query = null;
2411             // It should delete only when it portal's roleId
2412             if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
2413                 // Delete from fn_role_function
2414                 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
2415                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2416                 query = entityManager.createQuery(sql);
2417                 query.executeUpdate();
2418                 // Delete from fn_role_composite
2419                 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
2420                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2421                 query = entityManager.createQuery(sql);
2422                 query.executeUpdate();
2423             }
2424             // Delete from ep_app_role_function
2425             sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
2426             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2427             query = entityManager.createQuery(sql);
2428             query.executeUpdate();
2429             // Delete from ep_role_notification
2430             sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
2431             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2432             query = entityManager.createQuery(sql);
2433             query.executeUpdate();
2434             // Delete from fn_user_pseudo_role
2435             sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
2436             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2437             query = entityManager.createQuery(sql);
2438             query.executeUpdate();
2439             // Delete form EP_WIDGET_CATALOG_ROLE
2440             sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
2441             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2442             query = entityManager.createQuery(sql);
2443             query.executeUpdate();
2444             // Delete form EP_WIDGET_CATALOG_ROLE
2445             sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
2446             logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2447             query = entityManager.createQuery(sql);
2448             query.executeUpdate();
2449             if (!isPortalRequest) {
2450                 // Delete form fn_menu_functional_roles
2451                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
2452                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
2453                 query = entityManager.createQuery(sql);
2454                 query.executeUpdate();
2455             }
2456         } catch (Exception e) {
2457             logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
2458             throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
2459         }
2460     }
2461
2462     private void deleteUserRoleInExternalSystem(FnRole role, FnApp app, String LoginId) throws Exception {
2463         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2464         HttpEntity<String> entity = new HttpEntity<>(headers);
2465         getNameSpaceIfExists(app);
2466         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
2467             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2468         ResponseEntity<String> getResponse = template.exchange(
2469             SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
2470                 + LoginId
2471                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
2472                 + "/" + app.getAuthNamespace() + "."
2473                 + role.getRoleName()
2474                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
2475             HttpMethod.GET, entity, String.class);
2476         logger.debug(EELFLoggerDelegate.debugLogger,
2477             "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
2478             getResponse.getBody());
2479         if (getResponse.getStatusCode().value() != 200) {
2480             throw new ExternalAuthSystemException(getResponse.getBody());
2481         }
2482         String res = getResponse.getBody();
2483         if (!res.equals(IS_EMPTY_JSON_STRING)) {
2484             HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
2485             logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
2486                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2487             ResponseEntity<String> deleteResponse = template.exchange(
2488                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
2489                     + LoginId
2490                     + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
2491                     + "/" + app.getAuthNamespace() + "."
2492                     + role.getRoleName().replaceAll(
2493                     EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
2494                 HttpMethod.DELETE, userRoleentity, String.class);
2495             if (deleteResponse.getStatusCode().value() != 200) {
2496                 throw new ExternalAuthSystemException("Failed to delete user role");
2497             }
2498             logger.debug(EELFLoggerDelegate.debugLogger,
2499                 "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
2500                 deleteResponse.getStatusCode().value());
2501         }
2502     }
2503
2504     public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
2505         FnApp app = getApp(uebkey).get(0);
2506         List<BulkUploadUserRoles> userRolesList;
2507         Integer userRolesAdded = 0;
2508         if (app.getAuthCentral()) {
2509             userRolesList = bulkUploadUserRolesService.getBulkUsersForSingleRole(app.getUebKey(), roleId);
2510             for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2511                 userRolesUpload.setRoleName(modifiedRoleName);
2512                 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
2513                     addUserRoleInExternalSystem(userRolesUpload);
2514                     userRolesAdded++;
2515                 }
2516             }
2517         }
2518         return userRolesAdded;
2519     }
2520
2521     private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2522         try {
2523             String name = "";
2524             ObjectMapper mapper = new ObjectMapper();
2525             if (EPCommonSystemProperties
2526                 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2527                 name = userRolesUpload.getOrgUserId()
2528                     + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2529             }
2530             ExternalAccessUser extUser = new ExternalAccessUser(name,
2531                 userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
2532                     .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2533             String userRole = mapper.writeValueAsString(extUser);
2534             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2535             HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2536             template.exchange(
2537                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2538                 HttpMethod.POST, entity, String.class);
2539         } catch (HttpClientErrorException e) {
2540             logger.error(EELFLoggerDelegate.errorLogger,
2541                 "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
2542             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2543         } catch (Exception e) {
2544             if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2545                 logger.error(EELFLoggerDelegate.errorLogger,
2546                     "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
2547             } else {
2548                 logger.error(EELFLoggerDelegate.errorLogger,
2549                     "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
2550             }
2551         }
2552     }
2553
2554     private void addNewRoleInExternalSystem(List<FnRole> newRole, FnApp app)
2555         throws Exception {
2556         try {
2557             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2558             ObjectMapper mapper = new ObjectMapper();
2559             String addNewRole;
2560             ExternalAccessRole extRole = new ExternalAccessRole();
2561             extRole.setName(app.getAuthNamespace() + "." + newRole.get(0).getRoleName()
2562                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2563             extRole.setDescription(String.valueOf(newRole.get(0).getRoleName()));
2564             addNewRole = mapper.writeValueAsString(extRole);
2565             HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
2566             logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
2567                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
2568             ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
2569                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2570                 HttpMethod.POST, postEntity, String.class);
2571             if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
2572                 logger.debug(EELFLoggerDelegate.debugLogger,
2573                     "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
2574                     addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
2575             }
2576         } catch (HttpClientErrorException ht) {
2577             fnRoleService.delete(newRole.get(0));
2578             logger.error(EELFLoggerDelegate.debugLogger,
2579                 "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
2580             throw new HttpClientErrorException(ht.getStatusCode());
2581         }
2582     }
2583
2584     private void checkIfRoleExitsInExternalSystem(Role checkRole, FnApp app) throws Exception {
2585         getNameSpaceIfExists(app);
2586         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2587         String roleName = app.getAuthNamespace() + "." + checkRole.getName()
2588             .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
2589         HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
2590         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
2591             CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2592         ResponseEntity<String> checkRoleInExternalSystem = template
2593             .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
2594                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
2595         if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
2596             logger.debug(
2597                 "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
2598                 checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
2599             throw new ExternalAuthSystemException(" Role already exists in external system");
2600         }
2601     }
2602
2603     public ResponseEntity<String> getNameSpaceIfExists(FnApp app) throws Exception {
2604         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2605         HttpEntity<String> entity = new HttpEntity<>(headers);
2606         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
2607         ResponseEntity<String> response = null;
2608         try {
2609             response = template
2610                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2611                     + "nss/" + app.getAuthNamespace(), HttpMethod.GET, entity, String.class);
2612             logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
2613                 response.getStatusCode().value());
2614         } catch (HttpClientErrorException e) {
2615             logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
2616             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2617             if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
2618                 throw new InvalidApplicationException("Invalid NameSpace");
2619             } else {
2620                 throw e;
2621             }
2622         }
2623         return response;
2624     }
2625
2626     private FnRoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
2627         String instance;
2628         String type;
2629         String action;
2630         FnRoleFunction cenRoleFun = null;
2631         if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
2632             instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
2633             type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
2634             action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
2635             cenRoleFun = FnRoleFunction.builder().build();
2636             FnRole fnRole = new FnRole();
2637             FnFunction fnFunction = FnFunction.builder().functionCd(instance).name(role.getFunctionName()).type(type)
2638                 .action(action).build();
2639             cenRoleFun.setRole(fnRole);
2640             cenRoleFun.setFunctionCd(fnFunction);
2641         } else {
2642             type = getFunctionCodeType(role.getFunctionCd());
2643             action = getFunctionCodeAction(role.getFunctionCd());
2644             FnFunction fnFunction = FnFunction.builder().functionCd(role.getFunctionCd()).name(role.getFunctionName())
2645                 .type(type).action(action).build();
2646             cenRoleFun.setRole(new FnRole());
2647             cenRoleFun.setFunctionCd(fnFunction);
2648         }
2649         return cenRoleFun;
2650     }
2651
2652     public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
2653         CentralUser sendUserRoles = null;
2654         try {
2655             CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
2656             sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
2657         } catch (Exception e) {
2658             logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
2659             throw e;
2660         }
2661         return sendUserRoles;
2662     }
2663
2664     private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
2665         FnApp app;
2666         List<FnApp> appList = getApp(uebkey);
2667         app = appList.get(0);
2668         FnUser user = fnUserService.loadUserByUsername(loginId);
2669         Set<FnUserRole> userAppSet = user.getUserApps();
2670         return createEPUser(user, userAppSet, app);
2671     }
2672
2673     public List<FnApp> getApp(String uebkey) throws Exception {
2674         List<FnApp> app = null;
2675         try {
2676             app = fnAppService.getByUebKey(uebkey);
2677             if (!app.isEmpty() && !app.get(0).getEnabled()
2678                 && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2679                 throw new InactiveApplicationException("Application:" + app.get(0).getAppName() + " is Unavailable");
2680             }
2681         } catch (Exception e) {
2682             logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
2683             throw e;
2684         }
2685         return app;
2686     }
2687
2688     private CentralV2User createEPUser(FnUser userInfo, Set<FnUserRole> userAppSet, FnApp app) {
2689         CentralV2User userAppList = CentralV2User.builder().build();
2690         CentralV2User user1;
2691         List<FnRole> globalRoleList = new ArrayList<>();
2692         try {
2693             if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2694                 globalRoleList = fnRoleService.userAppGlobalRoles(userInfo.getId(), app.getId());
2695             }
2696             userAppList.setUserApps(new TreeSet<>());
2697             for (FnUserRole userApp : userAppSet) {
2698                 if (userApp.getRoleId().getActiveYn()) {
2699                     FnApp epApp = userApp.getFnAppId();
2700                     String globalRole = userApp.getRoleId().getRoleName().toLowerCase();
2701                     if (((epApp.getId().equals(app.getId()))
2702                         && (!userApp.getRoleId().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
2703                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
2704                         && (globalRole.toLowerCase().startsWith("global_")))) {
2705                         CentralV2UserApp cua = new CentralV2UserApp();
2706                         cua.setUserId(null);
2707                         CentralApp cenApp = CentralApp.builder().id(1L).created(epApp.getCreated())
2708                             .modified(epApp.getModified()).createdId(epApp.getId())
2709                             .modifiedId(epApp.getModifiedId().getId()).rowNum(epApp.getRowNum())
2710                             .name(epApp.getAppName()).imageUrl(epApp.getAppImageUrl())
2711                             .description(epApp.getAppDescription()).notes(epApp.getAppNotes())
2712                             .url(epApp.getAppUrl()).alternateUrl(epApp.getAppAlternateUrl())
2713                             .restEndpoint(epApp.getAppRestEndpoint()).mlAppName(epApp.getMlAppName())
2714                             .mlAppAdminId(epApp.getMlAppAdminId()).motsId(String.valueOf(epApp.getMotsId()))
2715                             .appPassword(epApp.getAppPassword()).open(String.valueOf(epApp.getOpen()))
2716                             .enabled(String.valueOf(epApp.getEnabled())).thumbnail(epApp.getThumbnail())
2717                             .username(epApp.getAppUsername()).uebKey(epApp.getUebKey())
2718                             .uebSecret(epApp.getUebSecret()).uebTopicName(epApp.getUebTopicName())
2719                             .build();
2720                         cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
2721                         cua.setApp(cenApp);
2722                         Long appId = null;
2723                         if (globalRole.toLowerCase().startsWith("global_")
2724                             && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
2725                             && !epApp.getId().equals(app.getId())) {
2726                             appId = app.getId();
2727                             FnRole result = null;
2728                             if (globalRoleList.size() > 0) {
2729                                 result = globalRoleList.stream()
2730                                     .filter(x -> userApp.getRoleId().getId().equals(x.getId())).findAny()
2731                                     .orElse(null);
2732                             }
2733                             if (result == null) {
2734                                 continue;
2735                             }
2736                         } else {
2737                             appId = userApp.getFnAppId().getId();
2738                         }
2739                         List<EpAppFunction> appRoleFunctionList = epAppFunctionService
2740                             .getAppRoleFunctionList(userApp.getRoleId().getId(), appId);
2741                         SortedSet<EpAppFunction> roleFunctionSet = new TreeSet<>();
2742                         for (EpAppFunction roleFunc : appRoleFunctionList) {
2743                             String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
2744                             String type = getFunctionCodeType(roleFunc.getFunctionCd());
2745                             String action = getFunctionCodeAction(roleFunc.getFunctionCd());
2746                             EpAppFunction cenRoleFunc = new EpAppFunction(roleFunc.getId(),
2747                                 functionCode, roleFunc.getFunctionName(), null, type, action, null);
2748                             roleFunctionSet.add(cenRoleFunc);
2749                         }
2750                         Long userRoleId;
2751                         if (globalRole.toLowerCase().startsWith("global_")
2752                             || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2753                             userRoleId = userApp.getRoleId().getId();
2754                         } else {
2755                             userRoleId = userApp.getRoleId().getAppRoleId();
2756                         }
2757                         CentralV2Role cenRole = CentralV2Role.builder().id(userRoleId)
2758                             .created(userApp.getRoleId().getCreated()).modified(userApp.getRoleId().getModified())
2759                             .createdId(userApp.getRoleId().getCreatedId().getId())
2760                             .modifiedId(userApp.getRoleId().getModifiedId().getId())
2761                             .rowNum(userApp.getRoleId().getRowNum()).name(userApp.getRoleId().getRoleName())
2762                             .active(userApp.getRoleId().getActiveYn()).priority(userApp.getRoleId().getPriority())
2763                             //.roleFunctions(roleFunctionSet).setChildRoles(null).setParentRoles(null)
2764                             .build();
2765                         cua.setRole(cenRole);
2766                         userAppList.getUserApps().add(cua);
2767                     }
2768                 }
2769             }
2770             user1 = CentralV2User.builder().id(null).created(userInfo.getCreated())
2771                 .modified(userInfo.getModified()).createdId(userInfo.getCreatedId().getId())
2772                 .modifiedId(userInfo.getModifiedId().getId()).rowNum(userInfo.getRowNum())
2773                 .orgId(userInfo.getOrgId().getOrgId()).managerId(userInfo.getOrgManagerUserId())
2774                 .firstName(userInfo.getFirstName()).middleInitial(userInfo.getMiddleName())
2775                 .lastName(userInfo.getLastName()).phone(userInfo.getPhone()).fax(userInfo.getFax())
2776                 .cellular(userInfo.getCellular()).email(userInfo.getEmail())
2777                 .addressId(userInfo.getAddressId()).alertMethodCd(userInfo.getAlertMethodCd().getAlertMethodCd())
2778                 .hrid(userInfo.getHrid()).orgUserId(userInfo.getOrgUserId()).orgCode(userInfo.getOrgCode())
2779                 .address1(userInfo.getAddressLine1()).address2(userInfo.getAddressLine2()).city(userInfo.getCity())
2780                 .state(userInfo.getStateCd()).zipCode(userInfo.getZipCode()).country(userInfo.getCountryCd())
2781                 .orgManagerUserId(userInfo.getOrgManagerUserId()).locationClli(userInfo.getLocationClli())
2782                 .businessCountryCode(userInfo.getBusinessUnit())
2783                 .businessCountryName(userInfo.getBusinessUnitName())
2784                 .businessUnit(userInfo.getBusinessUnit()).businessUnitName(userInfo.getBusinessUnitName())
2785                 .department(userInfo.getDepartment()).departmentName(userInfo.getDepartmentName())
2786                 .companyCode(userInfo.getOrgCode()).company(userInfo.getCompany())
2787                 .zipCodeSuffix(userInfo.getZipCode()).jobTitle(userInfo.getJobTitle())
2788                 //.commandChain(userInfo.getCommandChain()).siloStatus(userInfo.getSiloStatus())
2789                 .costCenter(userInfo.getCostCenter()).financialLocCode(userInfo.getFinLocCode())
2790                 .loginId(userInfo.getLoginId()).loginPwd(userInfo.getLoginPwd())
2791                 .lastLoginDate(userInfo.getLastLoginDate()).active(userInfo.getActiveYn())
2792                 //.internal(userInfo.getIsInternalYn()).selectedProfileId(userInfo.getSelectedProfileId())
2793                 //.timeZoneId(userInfo.getTimezone().getTimezoneId()).online(userInfo.isOnline())
2794                 //.chatId(userInfo.getChatId()).setUserApps(userAppList.getUserApps()).setPseudoRoles(null)
2795                 .build();
2796         } catch (Exception e) {
2797             logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
2798             throw e;
2799         }
2800         return user1;
2801     }
2802
2803     private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
2804         Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
2805         Set<CentralUserApp> userApps = new TreeSet<>();
2806         for (CentralV2UserApp userApp : userV2Apps) {
2807             CentralApp app = userApp.getApp();
2808             CentralUserApp cua = new CentralUserApp();
2809             cua.setUserId(null);
2810             cua.setApp(app);
2811             SortedSet<EpAppFunction> cenRoleFunction = new TreeSet<>();
2812             for (DomainVo vo : userApp.getRole().getRoleFunctions()) {
2813                 Optional<EpAppFunction> epApp = epAppFunctionService.getForId(vo.getId());
2814                 if (epApp.isPresent()) {
2815                     EpAppFunction cenRoleFunc = EpAppFunction.builder().functionCd(epApp.get().getFunctionCd())
2816                         .functionName(
2817                             epApp.get().getFunctionName()).build();
2818                     cenRoleFunction.add(cenRoleFunc);
2819                 }
2820             }
2821             CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
2822                 userApp.getRole().isActive(), userApp.getRole().getPriority(), cenRoleFunction);
2823             cua.setRole(role);
2824             userApps.add(cua);
2825         }
2826         return CentralUser.builder().id(cenV2User.getId()).created(cenV2User.getCreated())
2827             .modified(cenV2User.getModified()).createdId(cenV2User.getCreatedId())
2828             .modifiedId(cenV2User.getModifiedId()).rowNum(cenV2User.getRowNum())
2829             .orgId(cenV2User.getOrgId()).managerId(cenV2User.getManagerId())
2830             .firstName(cenV2User.getFirstName()).middleInitial(cenV2User.getMiddleInitial())
2831             .lastName(cenV2User.getLastName()).phone(cenV2User.getPhone()).fax(cenV2User.getFax())
2832             .cellular(cenV2User.getCellular()).email(cenV2User.getEmail())
2833             .addressId(cenV2User.getAddressId()).alertMethodCd(cenV2User.getAlertMethodCd())
2834             .hrid(cenV2User.getHrid()).orgUserId(cenV2User.getOrgUserId()).orgCode(cenV2User.getOrgCode())
2835             .address1(cenV2User.getAddress1()).address2(cenV2User.getAddress2()).city(cenV2User.getCity())
2836             .state(cenV2User.getState()).zipCode(cenV2User.getZipCode()).country(cenV2User.getCountry())
2837             .orgManagerUserId(cenV2User.getOrgManagerUserId()).locationClli(cenV2User.getLocationClli())
2838             .businessCountryCode(cenV2User.getBusinessCountryCode())
2839             .businessCountryName(cenV2User.getBusinessCountryName()).businessUnit(cenV2User.getBusinessUnit())
2840             .businessUnitName(cenV2User.getBusinessUnitName()).department(cenV2User.getDepartment())
2841             .departmentName(cenV2User.getDepartmentName()).companyCode(cenV2User.getCompanyCode())
2842             .company(cenV2User.getCompany()).zipCodeSuffix(cenV2User.getZipCodeSuffix())
2843             .jobTitle(cenV2User.getJobTitle()).commandChain(cenV2User.getCommandChain())
2844             .siloStatus(cenV2User.getSiloStatus()).costCenter(cenV2User.getCostCenter())
2845             .financialLocCode(cenV2User.getFinancialLocCode()).loginId(cenV2User.getLoginId())
2846             .loginPwd(cenV2User.getLoginPwd()).lastLoginDate(cenV2User.getLastLoginDate())
2847             .active(cenV2User.isActive()).internal(cenV2User.isInternal())
2848             .selectedProfileId(cenV2User.getSelectedProfileId()).timeZoneId(cenV2User.getTimeZoneId())
2849             .online(cenV2User.isOnline()).chatId(cenV2User.getChatId()).userApps(userApps).build();
2850     }
2851
2852     public CentralV2Role getRoleInfo(final Long roleId, final String uebkey) throws Exception {
2853         List<CentralV2Role> roleList = new ArrayList<>();
2854         CentralV2Role cenRole = CentralV2Role.builder().build();
2855         List<FnRole> roleInfo;
2856         List<FnApp> app;
2857         try {
2858             app = getApp(uebkey);
2859             if (app.isEmpty()) {
2860                 throw new InactiveApplicationException("Application not found");
2861             }
2862             if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2863                 List<FnRole> globalRoleList = getGlobalRolesOfPortal();
2864                 if (globalRoleList.size() > 0) {
2865                     FnRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
2866                         .orElse(null);
2867                     if (result != null) {
2868                         return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
2869                     }
2870                 }
2871             }
2872             if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2873                 roleInfo = getPortalAppRoleInfo(roleId);
2874             } else {
2875                 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0).getId());
2876             }
2877             roleList = createCentralRoleObject(app, roleInfo, roleList);
2878             if (roleList.isEmpty()) {
2879                 return cenRole;
2880             }
2881         } catch (Exception e) {
2882             logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
2883             throw e;
2884         }
2885         return roleList.get(0);
2886     }
2887
2888     private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
2889         CentralV2Role finalGlobalrole;
2890         List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
2891         try {
2892             roleWithApplicationRoleFucntions = entityManager
2893                 .createNamedQuery("getGlobalRoleForRequestedApp")
2894                 .setParameter("roleId", roleId)
2895                 .setParameter("requestedAppId", requestedAppId)
2896                 .getResultList();
2897         } catch (Exception e) {
2898             logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
2899         }
2900         if (roleWithApplicationRoleFucntions.size() > 0) {
2901             List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
2902             finalGlobalrole = rolesfinalList.get(0);
2903         } else {
2904             List<FnRole> roleList = getPortalAppRoleInfo(roleId);
2905             finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
2906         }
2907         return finalGlobalrole;
2908     }
2909
2910     public EpAppFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
2911         String code = EcompPortalUtils.getFunctionCode(functionCode);
2912         String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
2913         EpAppFunction roleFunc = null;
2914         FnApp app = getApp(uebkey).get(0);
2915         List<EpAppFunction> getRoleFuncList = null;
2916         try {
2917             getRoleFuncList = epAppFunctionService.getRoleFunction(functionCode, app.getId());
2918             if (getRoleFuncList.isEmpty()) {
2919                 getRoleFuncList = epAppFunctionService.getRoleFunction(encodedCode, app.getId());
2920                 if (getRoleFuncList.isEmpty()) {
2921                     return roleFunc;
2922                 }
2923             }
2924             if (getRoleFuncList.size() > 1) {
2925                 EpAppFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
2926                 if (cenV2RoleFunction == null) {
2927                     return roleFunc;
2928                 }
2929                 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
2930             } else {
2931                 // Check even if single record have pipes
2932                 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getFunctionCd().contains(FUNCTION_PIPE)) {
2933                     roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
2934                 } else {
2935                     roleFunc = getRoleFuncList.get(0);
2936                 }
2937             }
2938         } catch (Exception e) {
2939             logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
2940             throw e;
2941         }
2942         return roleFunc;
2943     }
2944
2945     private EpAppFunction appFunctionListFilter(String roleFuncCode, List<EpAppFunction> roleFunction) {
2946         final Map<String, EpAppFunction> appFunctionsFilter = new HashMap<>();
2947         final Map<String, EpAppFunction> appFunctionsFilterPipes = new HashMap<>();
2948         EpAppFunction getExactFunctionCode;
2949         for (EpAppFunction cenRoleFunction : roleFunction) {
2950             appFunctionsFilter.put(cenRoleFunction.getFunctionCd(), cenRoleFunction);
2951             appFunctionsFilterPipes
2952                 .put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getFunctionCd()), cenRoleFunction);
2953         }
2954         getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
2955         if (getExactFunctionCode == null) {
2956             getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
2957         }
2958         return getExactFunctionCode;
2959     }
2960
2961     private EpAppFunction checkIfPipesExitsInFunctionCode(EpAppFunction getRoleFuncList) {
2962         EpAppFunction roleFunc;
2963         String functionCodeFormat = getRoleFuncList.getFunctionCd();
2964         if (functionCodeFormat.contains(FUNCTION_PIPE)) {
2965             String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
2966             String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
2967             String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
2968             roleFunc = new EpAppFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
2969                 getRoleFuncList.getFunctionName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
2970                 newfunctionActionFormat, getRoleFuncList.getEditUrl());
2971         } else {
2972             roleFunc = EpAppFunction.builder()
2973                 .id(getRoleFuncList.getId())
2974                 .functionCd(functionCodeFormat)
2975                 .functionName(getRoleFuncList.getFunctionName())
2976                 .appId(getRoleFuncList.getAppId())
2977                 .editUrl(getRoleFuncList.getEditUrl())
2978                 .build();
2979         }
2980         return roleFunc;
2981     }
2982
2983     public boolean saveCentralRoleFunction(EpAppFunction domainCentralRoleFunction, FnApp app)
2984         throws Exception {
2985         boolean saveOrUpdateFunction = false;
2986         try {
2987             if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getFunctionCd())) {
2988                 domainCentralRoleFunction
2989                     .setFunctionCd(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getFunctionCd()));
2990             }
2991             final Map<String, String> functionParams = new HashMap<>();
2992             functionParams.put("appId", String.valueOf(app.getId()));
2993             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
2994                 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
2995             }
2996             if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
2997                 domainCentralRoleFunction.setFunctionCd(domainCentralRoleFunction.getType() + FUNCTION_PIPE
2998                     + domainCentralRoleFunction.getFunctionCd() + FUNCTION_PIPE + domainCentralRoleFunction
2999                     .getAction());
3000             }
3001             domainCentralRoleFunction.setAppId(app);
3002             epAppFunctionService.save(domainCentralRoleFunction);
3003             saveOrUpdateFunction = true;
3004         } catch (Exception e) {
3005             logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
3006             throw e;
3007         }
3008         return saveOrUpdateFunction;
3009     }
3010
3011     private void addRoleFunctionInExternalSystem(EpAppFunction domainCentralRoleFunction, FnApp app)
3012         throws Exception {
3013         ObjectMapper mapper = new ObjectMapper();
3014         ExternalAccessPerms extPerms = new ExternalAccessPerms();
3015         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3016         String type = "";
3017         String instance = "";
3018         String action = "";
3019         if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
3020             || domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)) {
3021             type = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
3022                 ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getFunctionCd())
3023                 : domainCentralRoleFunction.getType();
3024             instance = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
3025                 ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getFunctionCd())
3026                 : domainCentralRoleFunction.getFunctionCd();
3027             action = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
3028                 ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getFunctionCd())
3029                 : domainCentralRoleFunction.getAction();
3030         } else {
3031             type = domainCentralRoleFunction.getFunctionCd().contains("menu") ? "menu" : "url";
3032             instance = domainCentralRoleFunction.getFunctionCd();
3033             action = "*";
3034         }
3035         // get Permissions from External Auth System
3036         JSONArray extPermsList = getExtAuthPermissions(app.getAuthNamespace());
3037         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
3038         String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
3039         boolean checkIfFunctionsExits = permsDetailList.stream()
3040             .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
3041         if (!checkIfFunctionsExits) {
3042             try {
3043                 extPerms.setAction(action);
3044                 extPerms.setInstance(instance);
3045                 extPerms.setType(app.getAuthNamespace() + "." + type);
3046                 extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
3047                 String addFunction = mapper.writeValueAsString(extPerms);
3048                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
3049                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
3050                     CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
3051                 ResponseEntity<String> addPermResponse = template.exchange(
3052                     SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
3053                     HttpMethod.POST, entity, String.class);
3054                 logger.debug(EELFLoggerDelegate.debugLogger,
3055                     "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
3056                     addPermResponse.getStatusCode().value(), addFunction);
3057             } catch (HttpClientErrorException e) {
3058                 logger.error(EELFLoggerDelegate.errorLogger,
3059                     "HttpClientErrorException - Failed to add function in external central auth system", e);
3060                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3061                 throw e;
3062             } catch (Exception e) {
3063                 logger.error(EELFLoggerDelegate.errorLogger,
3064                     "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
3065                 throw e;
3066             }
3067         } else {
3068             try {
3069                 extPerms.setAction(action);
3070                 extPerms.setInstance(instance);
3071                 extPerms.setType(app.getAuthNamespace() + "." + type);
3072                 extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
3073                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
3074                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
3075                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
3076                     CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
3077                 ResponseEntity<String> updatePermResponse = template.exchange(
3078                     SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
3079                     HttpMethod.PUT, entity, String.class);
3080                 logger.debug(EELFLoggerDelegate.debugLogger,
3081                     "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
3082                     updateRoleFunction, updatePermResponse.getStatusCode().value());
3083             } catch (HttpClientErrorException e) {
3084                 logger.error(EELFLoggerDelegate.errorLogger,
3085                     "HttpClientErrorException - Failed to add function in external central auth system", e);
3086                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3087                 throw e;
3088             } catch (Exception e) {
3089                 logger.error(EELFLoggerDelegate.errorLogger,
3090                     "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
3091                     e);
3092                 throw e;
3093             }
3094         }
3095     }
3096
3097     public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3098         SortedSet<EpAppFunction> cenRoleFuncList = new TreeSet<>();
3099         for (DomainVo vo : v2CenRole.getRoleFunctions()) {
3100             Optional<EpAppFunction> v2CenRoleFunc = epAppFunctionService.getForId(vo.getId());
3101             if (v2CenRoleFunc.isPresent()) {
3102                 EpAppFunction roleFunc = EpAppFunction.builder()
3103                     .functionCd(v2CenRoleFunc.get().getFunctionCd())
3104                     .functionName(v2CenRoleFunc.get().getFunctionName())
3105                     .build();
3106                 cenRoleFuncList.add(roleFunc);
3107             }
3108
3109         }
3110         return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
3111             cenRoleFuncList);
3112     }
3113
3114     public List<EpAppFunction> getRoleFuncList(String uebkey) throws Exception {
3115         FnApp app = getApp(uebkey).get(0);
3116         List<EpAppFunction> finalRoleList = new ArrayList<>();
3117         List<EpAppFunction> getRoleFuncList = epAppFunctionService.getAllRoleFunctions(app.getId());
3118         for (EpAppFunction roleFuncItem : getRoleFuncList) {
3119             String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getFunctionCd());
3120             String type = "";
3121             if (roleFuncItem.getFunctionCd().contains("|")) {
3122                 type = EcompPortalUtils.getFunctionType(roleFuncItem.getFunctionCd());
3123             } else {
3124                 type = getFunctionCodeType(roleFuncItem.getFunctionCd());
3125             }
3126             String action = getFunctionCodeAction(roleFuncItem.getFunctionCd());
3127             roleFuncItem.setFunctionCd(EPUserUtils.decodeFunctionCode(code));
3128             roleFuncItem.setType(type);
3129             roleFuncItem.setAction(action);
3130             finalRoleList.add(roleFuncItem);
3131         }
3132         return finalRoleList;
3133     }
3134
3135     public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
3136         List<EpAppFunction> answer) {
3137         List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3138         for (EpAppFunction cenRoleFunc : answer) {
3139             CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3140             setRoleFunc.setCode(cenRoleFunc.getFunctionCd());
3141             setRoleFunc.setName(cenRoleFunc.getFunctionName());
3142             addRoleFuncList.add(setRoleFunc);
3143         }
3144         return addRoleFuncList;
3145     }
3146
3147     @Transactional(rollbackFor = Exception.class)
3148     public boolean deleteCentralRoleFunction(String code, FnApp app) {
3149         boolean deleteFunctionResponse = false;
3150         try {
3151             List<EpAppFunction> domainCentralRoleFunction = epAppFunctionService.getRoleFunction(code, app.getId());
3152             EpAppFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
3153             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
3154                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
3155                 // Delete role function dependency records
3156                 deleteAppRoleFunctions(appFunctionCode.getFunctionCd(), app.getId());
3157             }
3158             epAppFunctionService.deleteOne(appFunctionCode);
3159             deleteFunctionResponse = true;
3160         } catch (Exception e) {
3161             logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
3162         }
3163         return deleteFunctionResponse;
3164     }
3165
3166     private void deleteRoleFunctionInExternalSystem(EpAppFunction domainCentralRoleFunction, FnApp app) {
3167         try {
3168             ObjectMapper mapper = new ObjectMapper();
3169             ExternalAccessPerms extPerms = new ExternalAccessPerms();
3170             String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getFunctionCd());
3171             String checkType = getFunctionCodeType(domainCentralRoleFunction.getFunctionCd());
3172             String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getFunctionCd());
3173             HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3174             extPerms.setAction(actionValue);
3175             extPerms.setInstance(instanceValue);
3176             extPerms.setType(app.getAuthNamespace() + "." + checkType);
3177             extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
3178             String deleteRoleFunction = mapper.writeValueAsString(extPerms);
3179             HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
3180             logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
3181                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
3182             ResponseEntity<String> delPermResponse = template
3183                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3184                     + "perm?force=true", HttpMethod.DELETE, entity, String.class);
3185             logger.debug(EELFLoggerDelegate.debugLogger,
3186                 "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
3187                 deleteRoleFunction, delPermResponse.getStatusCode().value());
3188         } catch (HttpClientErrorException e) {
3189             logger.error(EELFLoggerDelegate.errorLogger,
3190                 "HttpClientErrorException - Failed to delete functions in External System", e);
3191             EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3192         } catch (Exception e) {
3193             if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
3194                 logger.debug(EELFLoggerDelegate.debugLogger,
3195                     " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
3196                     e.getMessage());
3197             } else {
3198                 logger.error(EELFLoggerDelegate.errorLogger,
3199                     "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
3200             }
3201         }
3202     }
3203
3204     private void deleteAppRoleFunctions(final String code, final Long appId) {
3205         epAppFunctionService.deleteByAppIdAndFunctionCd(appId, code);
3206     }
3207
3208     public Integer updateAppRoleDescription(String uebkey) {
3209         Integer roleDescUpdated = 0;
3210         FnApp app;
3211         try {
3212             app = getApp(uebkey).get(0);
3213             List<FnRole> roles = getAppRoles(app.getId());
3214             for (FnRole epRole : roles) {
3215                 Role role = new Role();
3216                 role.setName(epRole.getRoleName());
3217                 boolean status = addRoleDescriptionInExtSystem(role.getName(), app.getAuthNamespace());
3218                 if (status)
3219                     roleDescUpdated++;
3220             }
3221         } catch (Exception e) {
3222             logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
3223         }
3224         return roleDescUpdated;
3225     }
3226
3227 }