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