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