Onboarding Page Account Admin Change
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / ExternalAccessRolesServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.service;
39
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Iterator;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Set;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
50 import java.util.stream.Collectors;
51
52 import org.apache.commons.codec.DecoderException;
53 import org.hibernate.Query;
54 import org.hibernate.Session;
55 import org.hibernate.SessionFactory;
56 import org.hibernate.Transaction;
57 import org.hibernate.criterion.Criterion;
58 import org.hibernate.criterion.Restrictions;
59 import org.json.JSONArray;
60 import org.json.JSONObject;
61 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
62 import org.onap.portalapp.portal.domain.CentralizedApp;
63 import org.onap.portalapp.portal.domain.EPApp;
64 import org.onap.portalapp.portal.domain.EPAppRoleFunction;
65 import org.onap.portalapp.portal.domain.EPRole;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EPUserApp;
68 import org.onap.portalapp.portal.domain.ExternalRoleDetails;
69 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
70 import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
71 import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
72 import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
73 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
74 import org.onap.portalapp.portal.exceptions.InvalidUserException;
75 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
76 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
77 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
78 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
79 import org.onap.portalapp.portal.transport.*;
80 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
81 import org.onap.portalapp.portal.utils.EcompPortalUtils;
82 import org.onap.portalapp.portal.utils.PortalConstants;
83 import org.onap.portalapp.util.EPUserUtils;
84 import org.onap.portalsdk.core.domain.Role;
85 import org.onap.portalsdk.core.domain.RoleFunction;
86 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
87 import org.onap.portalsdk.core.restful.domain.EcompRole;
88 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
89 import org.onap.portalsdk.core.restful.domain.EcompUser;
90 import org.onap.portalsdk.core.service.DataAccessService;
91 import org.onap.portalsdk.core.util.SystemProperties;
92 import org.springframework.beans.factory.annotation.Autowired;
93 import org.springframework.context.annotation.EnableAspectJAutoProxy;
94 import org.springframework.http.HttpEntity;
95 import org.springframework.http.HttpHeaders;
96 import org.springframework.http.HttpMethod;
97 import org.springframework.http.HttpStatus;
98 import org.springframework.http.ResponseEntity;
99 import org.springframework.stereotype.Service;
100 import org.springframework.transaction.annotation.Transactional;
101 import org.springframework.web.client.HttpClientErrorException;
102 import org.springframework.web.client.RestTemplate;
103
104 import com.fasterxml.jackson.core.JsonProcessingException;
105 import com.fasterxml.jackson.databind.DeserializationFeature;
106 import com.fasterxml.jackson.databind.ObjectMapper;
107 import com.fasterxml.jackson.databind.type.TypeFactory;
108
109 @Service("externalAccessRolesService")
110 @EnableAspectJAutoProxy
111 @EPMetricsLog
112 @EPAuditLog
113 public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {
114         private static final String APP_ROLE_NAME_PARAM = "appRoleName";
115         private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
116         private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
117         private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
118         private static final String FUNCTION_CODE_PARAMS = "functionCode";
119         private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
120         private static final String OWNER = ".owner";
121         private static final String ADMIN = ".admin";
122         private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
123         private static final String FUNCTION_PIPE = "|";
124         private static final String EXTERNAL_AUTH_PERMS = "perms";
125         private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
126         private static final String IS_EMPTY_JSON_STRING = "{}";
127         private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
128         private static final String APP_ID = "appId";
129         private static final String ROLE_NAME = "name";
130         private static final String APP_ID_EQUALS = " app_id = ";
131         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);
132         @Autowired
133         private DataAccessService dataAccessService;
134         @Autowired
135         private EPAppService epAppService;
136         @Autowired
137         private SessionFactory sessionFactory;
138         @Autowired
139         EPRoleService ePRoleService;
140         RestTemplate template = new RestTemplate();
141         // These decode values are based on HexDecoder
142         static final String decodeValueOfForwardSlash = "2f";
143         static final String decodeValueOfHiphen = "2d";
144         static final String decodeValueOfStar = "2a";
145
146         @SuppressWarnings("unchecked")
147         @Override
148         public List<EPRole> getAppRoles(Long appId) throws Exception {
149                 List<EPRole> applicationRoles = null;
150                 final Map<String, Long> appParams = new HashMap<>();
151                 try {
152                         if (appId == 1) {
153                                 applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
154                         } else {
155                                 appParams.put("appId", appId);
156                                 applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
157                         }
158                 } catch (Exception e) {
159                         logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
160                         throw e;
161                 }
162                 return applicationRoles;
163         }
164
165         @SuppressWarnings("unchecked")
166         @Override
167         public List<EPApp> getApp(String uebkey) throws Exception {
168                 List<EPApp> app = null;
169                 try {
170                         final Map<String, String> appUebkeyParams = new HashMap<>();
171                         appUebkeyParams.put("appKey", uebkey);
172                         app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
173                         if (!app.isEmpty() && !app.get(0).getEnabled()
174                                         && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
175                                 throw new InactiveApplicationException("Application:" + app.get(0).getName() + " is Unavailable");
176                         }
177                 } catch (Exception e) {
178                         logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
179                         throw e;
180                 }
181                 return app;
182         }
183
184         /**
185          * It returns single application role from external auth system
186          * 
187          * @param addRole
188          * @param app
189          * @return JSON string which contains application role details
190          * @throws Exception
191          */
192         private String getSingleAppRole(String addRole, EPApp app) throws Exception {
193                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
194                 HttpEntity<String> entity = new HttpEntity<>(headers);
195                 ResponseEntity<String> response = null;
196                 logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
197                 response = template.exchange(
198                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
199                                                 + app.getNameSpace() + "." + addRole
200                                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
201                                 HttpMethod.GET, entity, String.class);
202                 logger.debug(EELFLoggerDelegate.debugLogger,
203                                 "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
204                                 response.getStatusCode().value());
205                 return response.getBody();
206         }
207
208         @Override
209         public boolean addRole(Role addRole, String uebkey) throws Exception {
210                 boolean response = false;
211                 ResponseEntity<String> addResponse = null;
212                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
213                 EPApp app = getApp(uebkey).get(0);
214                 String newRole = updateExistingRoleInExternalSystem(addRole, app);
215                 HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
216                 logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
217                 addResponse = template.exchange(
218                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
219                                 HttpMethod.POST, entity, String.class);
220                 if (addResponse.getStatusCode().value() == 201) {
221                         response = true;
222                         logger.debug(EELFLoggerDelegate.debugLogger,
223                                         "addRole: Finished adding role in the External Auth system  and response code: {} ",
224                                         addResponse.getStatusCode().value());
225                 }
226                 if (addResponse.getStatusCode().value() == 406) {
227                         logger.error(EELFLoggerDelegate.errorLogger,
228                                         "addRole: Failed to add in the External Auth system due to {} and status code: {}",
229                                         addResponse.getBody(), addResponse.getStatusCode().value());
230                 }
231                 return response;
232         }
233
234         /**
235          * 
236          * It deletes record in external auth system
237          * 
238          * @param delRole
239          * @return JSON String which has status code and response body
240          * @throws Exception
241          */
242         private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
243                 ResponseEntity<String> delResponse = null;
244                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
245                 HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
246                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
247                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
248                 delResponse = template.exchange(
249                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
250                                 HttpMethod.DELETE, entity, String.class);
251                 logger.debug(EELFLoggerDelegate.debugLogger,
252                                 "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
253                                 delRole, delResponse.getStatusCode().value());
254                 return delResponse;
255         }
256
257         /**
258          * It updates role in external auth system
259          * 
260          * @param updateExtRole
261          * @param app
262          * @return true if success else false
263          * @throws Exception If updateRoleInExternalSystem fails we catch it in logger
264          *                   for detail message
265          */
266         private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
267                 boolean response = false;
268                 ObjectMapper mapper = new ObjectMapper();
269                 ResponseEntity<String> deleteResponse = null;
270                 List<EPRole> epRoleList = null;
271                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
272                                 || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
273                         epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
274                 } else {
275                         epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
276                 }
277                 // Assigning functions to global role
278                 if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
279                         List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
280                         EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
281                         addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
282                         response = true;
283                 } else {
284                         String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
285                         List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
286                         if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
287                                 JSONObject jsonObj = new JSONObject(appRole);
288                                 JSONArray extRole = jsonObj.getJSONArray("role");
289                                 if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
290                                         String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
291                                         Map<String, String> delRoleKeyMapper = new HashMap<>();
292                                         delRoleKeyMapper.put(ROLE_NAME, roleName);
293                                         String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
294                                         deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
295                                         if (deleteResponse.getStatusCode().value() != 200) {
296                                                 throw new ExternalAuthSystemException(deleteResponse.getBody());
297                                         }
298                                         addRole(updateExtRole, app.getUebKey());
299                                 } else {
300                                         String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
301                                         String name = extRole.getJSONObject(0).getString(ROLE_NAME);
302                                         List<ExternalAccessPerms> list = new ArrayList<>();
303                                         if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
304                                                 JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
305                                                 list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
306                                                                 .constructCollectionType(List.class, ExternalAccessPerms.class));
307                                         }
308                                         // If role name or role functions are updated then delete
309                                         // record in External System and add new record to avoid
310                                         // conflicts
311                                         boolean isRoleNameChanged = false;
312                                         if (!desc.equals(updateExtRole.getName())) {
313                                                 isRoleNameChanged = true;
314                                                 deleteRoleInExtSystem(mapper, name);
315                                                 addRole(updateExtRole, app.getUebKey());
316                                                 // add partner functions to the global role in External
317                                                 // Auth System
318                                                 if (!list.isEmpty() && isGlobalRole) {
319                                                         addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
320                                                 }
321                                                 list.removeIf(
322                                                                 perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
323                                                 // if role name is changes please ignore the previous
324                                                 // functions in External Auth
325                                                 // and update with user requested functions
326                                                 addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
327                                         }
328                                         // Delete role in External System if role is inactive
329                                         if (!updateExtRole.getActive()) {
330                                                 deleteRoleInExtSystem(mapper, name);
331                                         }
332                                         if (!isRoleNameChanged) {
333                                                 response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
334                                                                 list);
335                                         }
336                                 }
337                         } else {
338                                 // It seems like role exists in local DB but not in External
339                                 // Access system
340                                 if (updateExtRole.getActive()) {
341                                         addRole(updateExtRole, app.getUebKey());
342                                         ExternalAccessRolePerms extAddRolePerms = null;
343                                         ExternalAccessPerms extAddPerms = null;
344                                         List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
345                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
346                                         for (RoleFunction roleFunc : roleFunctionListAdd) {
347                                                 extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
348                                                                 roleFunc.getCode(), roleFunc.getAction());
349                                                 extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
350                                                                 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
351                                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
352                                                 response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
353                                         }
354                                 }
355                         }
356                 }
357                 return response;
358         }
359
360         private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
361                         throws JsonProcessingException, Exception, ExternalAuthSystemException {
362                 ResponseEntity<String> deleteResponse;
363                 Map<String, String> delRoleKeyMapper = new HashMap<>();
364                 delRoleKeyMapper.put(ROLE_NAME, name);
365                 String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
366                 deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
367                 if (deleteResponse.getStatusCode().value() != 200) {
368                         logger.error(EELFLoggerDelegate.errorLogger,
369                                         "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
370                                         deleteResponse.getBody());
371                         throw new ExternalAuthSystemException(deleteResponse.getBody());
372                 }
373         }
374
375         private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
376                         List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
377                 boolean response;
378                 Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
379                 for (RoleFunction addPerm : roleFunctionListNew) {
380                         updateRoleFunc.put(addPerm.getCode(), addPerm);
381                 }
382                 final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
383                 final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
384                 list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
385                 // Update permissions in the ExternalAccess System
386                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
387                 if (!list.isEmpty()) {
388                         for (ExternalAccessPerms perm : list) {
389                                 RoleFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length() + 1)
390                                                 + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
391                                 if (roleFunc == null) {
392                                         RoleFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
393                                         if (roleFuncPipeFilter == null)
394                                                 removePermForRole(perm, mapper, name, headers);
395                                 }
396                                 extRolePermMap.put(perm.getInstance(), perm);
397                                 extRolePermMapPipes.put(perm.getType().substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE
398                                                 + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
399                         }
400                 }
401                 response = true;
402                 if (!roleFunctionListNew.isEmpty()) {
403                         for (RoleFunction roleFunc : roleFunctionListNew) {
404                                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
405                                         ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
406                                         if (perm == null) {
407                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
408                                                                 roleFunc);
409                                         }
410                                 } else {
411                                         if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
412                                                 response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
413                                                                 roleFunc);
414                                         }
415                                 }
416                         }
417                 }
418                 return response;
419         }
420
421         /*
422          * Adds function to the role in the external auth system while editing a role or
423          * updating new functions to a role
424          *
425          */
426         private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
427                         HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
428                 boolean response;
429                 ExternalAccessRolePerms extRolePerms;
430                 ExternalAccessPerms extPerms;
431                 String code = "";
432                 String type = "";
433                 String action = "";
434                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
435                         code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
436                         type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
437                         action = getFunctionCodeAction(roleFunc.getCode());
438                 } else {
439                         code = roleFunc.getCode();
440                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
441                         action = "*";
442                 }
443                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
444                 extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + updateExtRole.getName()
445                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
446                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
447                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
448                 logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
449                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
450                 ResponseEntity<String> addResponse = template.exchange(
451                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
452                                 HttpMethod.POST, entity, String.class);
453                 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
454                         response = false;
455                         logger.debug(EELFLoggerDelegate.debugLogger,
456                                         "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
457                                         addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
458                 } else {
459                         response = true;
460                         logger.debug(EELFLoggerDelegate.debugLogger,
461                                         "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
462                                         updateRolePerms, addResponse.getStatusCode().value());
463                 }
464                 return response;
465         }
466
467         private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
468                         EPApp app, Role updateExtRole) throws Exception {
469                 for (ExternalAccessPerms perm : permslist) {
470                         if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
471                                 ExternalAccessRolePerms extAddGlobalRolePerms = null;
472                                 ExternalAccessPerms extAddPerms = null;
473                                 extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
474                                 extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
475                                                 app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
476                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
477                                 String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
478                                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
479                                 HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
480                                 logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
481                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
482                                 try {
483                                         ResponseEntity<String> addResponse = template
484                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
485                                                                         + "role/perm", HttpMethod.POST, entity, String.class);
486                                         if (addResponse.getStatusCode().value() != 201) {
487                                                 logger.debug(EELFLoggerDelegate.debugLogger,
488                                                                 "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
489                                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
490                                         } else {
491                                                 logger.debug(EELFLoggerDelegate.debugLogger,
492                                                                 "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
493                                                                 addResponse.getStatusCode().value());
494                                         }
495                                 } catch (Exception e) {
496                                         logger.error(EELFLoggerDelegate.errorLogger,
497                                                         "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
498                                 }
499                         }
500                 }
501         }
502
503         @SuppressWarnings("unchecked")
504         private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole,
505                         List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
506                         throws Exception {
507                 try {
508                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
509                         // GET Permissions from External Auth System
510                         JSONArray extPerms = getExtAuthPermissions(app);
511                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
512                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
513                         final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
514                         final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
515                         final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
516                         for (ExternalAccessPermsDetail permDetail : permsDetailList) {
517                                 existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
518                                 existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
519                         }
520                         // Add If function does not exists for role in External Auth System
521                         for (RoleFunction roleFunc : roleFunctionListNew) {
522                                 String roleFuncCode = "";
523                                 ExternalAccessPermsDetail permsDetail;
524                                 if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
525                                         roleFuncCode = roleFunc.getCode();
526                                         permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
527                                 } else {
528                                         roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
529                                         permsDetail = existingPermsWithRoles.get(roleFuncCode);
530                                 }
531                                 if (null == permsDetail.getRoles()
532                                                 || !permsDetail.getRoles()
533                                                                 .contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE
534                                                                                 + epRoleList.get(0).getName().replaceAll(
535                                                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
536                                                                                                 "_"))) {
537                                         addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
538                                 }
539                                 userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
540                                 userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
541                         }
542                         // Delete functions if exists in External Auth System but not in
543                         // incoming
544                         // request
545                         final Map<String, Long> epAppRoleFuncParams = new HashMap<>();
546                         epAppRoleFuncParams.put("requestedAppId", app.getId());
547                         epAppRoleFuncParams.put("roleId", updateExtRole.getId());
548                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService
549                                         .executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
550                         for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
551                                 String globalRoleFuncWithoutPipes = "";
552                                 RoleFunction roleFunc = null;
553                                 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
554                                         globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
555                                         roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
556                                 } else {
557                                         globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
558                                         roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
559                                 }
560                                 if (roleFunc == null) {
561                                         ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
562                                                         ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
563                                                         : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
564                                         ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
565                                                         EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
566                                                         permDetailFromMap.getAction());
567                                         String roleName = portalAppInfo.getNameSpace() + "." + globalRoleFunc.getRoleName()
568                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
569                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
570                                         removePermForRole(perm, mapper, roleName, headers);
571                                 }
572                         }
573                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
574                 } catch (Exception e) {
575                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
576                         throw e;
577                 }
578         }
579
580         private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole,
581                         ObjectMapper mapper, EPApp app, EPApp portalAppInfo) throws Exception {
582                 try {
583                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
584                         ExternalAccessRolePerms extAddRolePerms = null;
585                         ExternalAccessPerms extAddPerms = null;
586                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
587                         String code = "";
588                         String type = "";
589                         String action = "";
590                         if (addFunction.getCode().contains(FUNCTION_PIPE)) {
591                                 code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
592                                 type = getFunctionCodeType(addFunction.getCode());
593                                 action = getFunctionCodeAction(addFunction.getCode());
594                         } else {
595                                 code = addFunction.getCode();
596                                 type = addFunction.getCode().contains("menu") ? "menu" : "url";
597                                 action = "*";
598                         }
599                         extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
600                         extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, portalAppInfo.getNameSpace() + "." + globalRole
601                                         .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
602                         String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
603                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
604                         logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
605                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
606                         ResponseEntity<String> addResponse = template.exchange(
607                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
608                                         HttpMethod.POST, entity, String.class);
609                         if (addResponse.getStatusCode().value() != 201) {
610                                 logger.debug(EELFLoggerDelegate.debugLogger,
611                                                 "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
612                                                 addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
613                         } else {
614                                 logger.debug(EELFLoggerDelegate.debugLogger,
615                                                 "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
616                                                 addResponse.getStatusCode().value());
617                         }
618                         logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
619                 } catch (Exception e) {
620                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
621                         throw e;
622                 }
623         }
624
625         private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
626                         HttpHeaders headers) throws JsonProcessingException {
627                 boolean response;
628                 String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
629                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
630                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
631                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
632                 ResponseEntity<String> addResponse = template.exchange(
633                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
634                                 HttpMethod.POST, entity, String.class);
635                 if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
636                         response = false;
637                         logger.debug(EELFLoggerDelegate.debugLogger,
638                                         "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
639                                         addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
640                 } else {
641                         response = true;
642                         logger.debug(EELFLoggerDelegate.debugLogger,
643                                         "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
644                                         updateRolePerms, addResponse.getStatusCode().value());
645                 }
646                 return response;
647         }
648
649         /**
650          * 
651          * It converts list of functions in updateExtRole parameter to the RoleFunction
652          * object
653          * 
654          * @param updateExtRole
655          * @return list of functions
656          */
657         @SuppressWarnings("unchecked")
658         private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
659                 Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
660                 List<RoleFunction> roleFunctionList = new ArrayList<>();
661                 ObjectMapper roleFuncMapper = new ObjectMapper();
662                 Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
663                 while (itetaror.hasNext()) {
664                         Object nextValue = itetaror.next();
665                         RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
666                         roleFunctionList.add(roleFunction);
667                 }
668                 return roleFunctionList.stream().distinct().collect(Collectors.toList());
669         }
670
671         /**
672          * It delete permissions/functions in the external auth system
673          * 
674          * @param perm
675          * @param permMapper
676          * @param name
677          * @param headers
678          * @throws JsonProcessingException
679          * @throws Exception
680          */
681         private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
682                         throws ExternalAuthSystemException, JsonProcessingException {
683                 ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
684                 String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
685                 try {
686                         HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
687                         logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
688                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
689                         ResponseEntity<String> deletePermResponse = template
690                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
691                                                         + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
692                         if (deletePermResponse.getStatusCode().value() != 200) {
693                                 throw new ExternalAuthSystemException(deletePermResponse.getBody());
694                         }
695                         logger.debug(EELFLoggerDelegate.debugLogger,
696                                         "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
697                                         permDetails, deletePermResponse.getStatusCode().value());
698                 } catch (Exception e) {
699                         if (e.getMessage().contains("404")) {
700                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
701                                                 permDetails, e.getMessage());
702                         } else {
703                                 throw e;
704                         }
705                 }
706         }
707
708         /**
709          * It will create new role in the External Auth System
710          * 
711          * @param newRole
712          * @param app
713          * @return true if successfully added in the system else false
714          * @throws Exception If fails to add role in the system
715          */
716         private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app)
717                         throws Exception, HttpClientErrorException {
718                 try {
719                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
720                         ObjectMapper mapper = new ObjectMapper();
721                         String addNewRole = "";
722                         ExternalAccessRole extRole = new ExternalAccessRole();
723                         extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName()
724                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
725                         extRole.setDescription(String.valueOf(newRole.get(0).getName()));
726                         addNewRole = mapper.writeValueAsString(extRole);
727                         HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
728                         logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
729                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
730                         ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
731                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
732                                         HttpMethod.POST, postEntity, String.class);
733                         if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
734                                 logger.debug(EELFLoggerDelegate.debugLogger,
735                                                 "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
736                                                 addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
737                         }
738                 } catch (HttpClientErrorException ht) {
739                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + newRole.get(0).getId(), null);
740                         logger.error(EELFLoggerDelegate.debugLogger,
741                                         "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
742                         throw new HttpClientErrorException(ht.getStatusCode());
743                 }
744         }
745
746         /**
747          * 
748          * It updates existing role in the External Auth System
749          * 
750          * @param addRole It Contains role information
751          * @param app
752          * @return string which is formatted to match with the external auth system
753          * @throws JsonProcessingException
754          */
755         private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
756                 ObjectMapper mapper = new ObjectMapper();
757                 String addNewRole = "";
758                 ExternalAccessRole extRole = new ExternalAccessRole();
759                 extRole.setName(app.getNameSpace() + "." + addRole.getName()
760                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
761                 extRole.setDescription(String.valueOf(addRole.getName()));
762                 addNewRole = mapper.writeValueAsString(extRole);
763                 return addNewRole;
764         }
765
766         /**
767          * It create a role in the external auth system and then in our local
768          * 
769          * @param addRoleInDB
770          * @param app
771          * @return true else false
772          * @throws Exception
773          */
774         @SuppressWarnings("unchecked")
775         @Transactional(rollbackFor = Exception.class)
776         public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {
777                 boolean result = false;
778                 EPRole epRole = null;
779                 Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
780                 List<RoleFunction> roleFunctionListNew = new ArrayList<>();
781                 ObjectMapper mapper = new ObjectMapper();
782                 Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
783                 while (itetaror.hasNext()) {
784                         Object nextValue = itetaror.next();
785                         RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
786                         roleFunctionListNew.add(roleFunction);
787                 }
788                 List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
789                 try {
790                         if (addRoleInDB.getId() == null) { // check if it is new role
791                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
792                                         checkIfRoleExitsInExternalSystem(addRoleInDB, app);
793                                 }
794                                 EPRole epRoleNew = new EPRole();
795                                 epRoleNew.setActive(addRoleInDB.getActive());
796                                 epRoleNew.setName(addRoleInDB.getName());
797                                 epRoleNew.setPriority(addRoleInDB.getPriority());
798                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
799                                         epRoleNew.setAppId(null);
800                                 } else {
801                                         epRoleNew.setAppId(app.getId());
802                                 }
803                                 dataAccessService.saveDomainObject(epRoleNew, null);
804                                 List<EPRole> getRoleCreated = null;
805                                 final Map<String, String> epAppRoleParams = new HashMap<>();
806                                 final Map<String, String> epAppPortalRoleParams = new HashMap<>();
807                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
808                                         epAppRoleParams.put("appId", String.valueOf(app.getId()));
809                                         epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
810                                         List<EPRole> roleCreated = dataAccessService
811                                                         .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
812                                         EPRole epUpdateRole = roleCreated.get(0);
813                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
814                                         dataAccessService.saveDomainObject(epUpdateRole, null);
815                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
816                                                         epAppRoleParams, null);
817                                 } else {
818                                         epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
819                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY,
820                                                         epAppPortalRoleParams, null);
821                                 }
822                                 // Add role in External Auth system
823                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
824                                         addNewRoleInExternalSystem(getRoleCreated, app);
825                                 }
826                                 result = true;
827                         } else { // if role already exists then update it
828                                 EPRole globalRole = null;
829                                 List<EPRole> applicationRoles;
830                                 List<EPRole> globalRoleList = getGlobalRolesOfPortal();
831                                 boolean isGlobalRole = false;
832                                 if (!globalRoleList.isEmpty()) {
833                                         EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
834                                                         .orElse(null);
835                                         if (role != null) {
836                                                 globalRole = role;
837                                                 isGlobalRole = true;
838                                         }
839                                 }
840                                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
841                                                 || (globalRole != null && app.getId() != globalRole.getAppId())) {
842                                         applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
843                                 } else {
844                                         applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
845                                 }
846                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
847                                         updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
848                                         // Add all user to the re-named role in external auth system
849                                         if (!applicationRoles.isEmpty()
850                                                         && !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
851                                                 bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
852                                                                 addRoleInDB.getName());
853                                         }
854                                 }
855                                 deleteRoleFunction(app, applicationRoles);
856                                 if (!applicationRoles.isEmpty()) {
857                                         epRole = applicationRoles.get(0);
858                                         epRole.setName(addRoleInDB.getName());
859                                         epRole.setPriority(addRoleInDB.getPriority());
860                                         epRole.setActive(addRoleInDB.getActive());
861                                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
862                                                 epRole.setAppId(null);
863                                                 epRole.setAppRoleId(null);
864                                         } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
865                                                         && applicationRoles.get(0).getAppRoleId() == null) {
866                                                 epRole.setAppRoleId(epRole.getId());
867                                         }
868                                         dataAccessService.saveDomainObject(epRole, null);
869                                 }
870                                 Long roleAppId = null;
871                                 if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
872                                         roleAppId = PortalConstants.PORTAL_APP_ID;
873                                 saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
874                                 result = true;
875                         }
876                 } catch (Exception e) {
877                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
878                         throw e;
879                 }
880                 return result;
881         }
882
883         /**
884          * 
885          * It validates whether role exists in external auth system
886          * 
887          * @param checkRole
888          * @param app
889          * @throws Exception If role exits
890          */
891         private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
892                 getNameSpaceIfExists(app);
893                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
894                 String roleName = app.getNameSpace() + "." + checkRole.getName()
895                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
896                 HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
897                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
898                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
899                 ResponseEntity<String> checkRoleInExternalSystem = template
900                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
901                                                 + roleName, HttpMethod.GET, checkRoleEntity, String.class);
902                 if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
903                         logger.debug(
904                                         "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
905                                         checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
906                         throw new ExternalAuthSystemException(" Role already exists in external system");
907                 }
908         }
909
910         /**
911          * It saves list of functions to the role in portal
912          * 
913          * @param roleFunctionListNew
914          * @param app
915          * @param applicationRoles
916          * @throws Exception
917          */
918         @SuppressWarnings("unchecked")
919         private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles,
920                         Long roleAppId) throws Exception {
921                 final Map<String, String> getAppFunctionParams = new HashMap<>();
922                 for (RoleFunction roleFunc : roleFunctionListNew) {
923                         String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
924                         EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
925                         appRoleFunc.setAppId(app.getId());
926                         appRoleFunc.setRoleId(applicationRoles.get(0).getId());
927                         appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
928                         getAppFunctionParams.put("appId", String.valueOf(app.getId()));
929                         getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
930                         // query to check if function code has pipes
931                         List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY,
932                                         getAppFunctionParams, null);
933                         if (roleFunction.isEmpty()) {
934                                 getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
935                                 roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
936                         }
937                         if (roleFunction.size() > 1) {
938                                 CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
939                                 appRoleFunc.setCode(getExactFunctionCode.getCode());
940                         } else {
941                                 appRoleFunc.setCode(roleFunction.get(0).getCode());
942                         }
943                         dataAccessService.saveDomainObject(appRoleFunc, null);
944                 }
945         }
946
947         /**
948          * 
949          * It filters the app functions which starts with similar name in the result set
950          * 
951          * @param roleFunc
952          * @param roleFunction
953          * @return CentralRoleFunction
954          */
955         private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
956                 final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>();
957                 final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>();
958                 CentralV2RoleFunction getExactFunctionCode = null;
959                 for (CentralV2RoleFunction cenRoleFunction : roleFunction) {
960                         appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
961                         appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
962                 }
963                 getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
964                 if (getExactFunctionCode == null) {
965                         getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
966                 }
967                 return getExactFunctionCode;
968         }
969
970         /**
971          * It deletes all EPAppRoleFunction records in the portal
972          * 
973          * @param app
974          * @param role
975          */
976         @SuppressWarnings("unchecked")
977         private void deleteRoleFunction(EPApp app, List<EPRole> role) {
978                 final Map<String, Long> appRoleFuncsParams = new HashMap<>();
979                 appRoleFuncsParams.put("appId", app.getId());
980                 appRoleFuncsParams.put("roleId", role.get(0).getId());
981                 List<EPAppRoleFunction> appRoleFunctionList = dataAccessService
982                                 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
983                 if (!appRoleFunctionList.isEmpty()) {
984                         for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
985                                 dataAccessService.deleteDomainObject(approleFunction, null);
986                         }
987                 }
988         }
989
990         @Override
991         @SuppressWarnings("unchecked")
992         public List<EPUser> getUser(String loginId) throws InvalidUserException {
993                 final Map<String, String> userParams = new HashMap<>();
994                 userParams.put("org_user_id", loginId);
995                 List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
996                 if (userList.isEmpty()) {
997                         throw new InvalidUserException("User not found");
998                 }
999                 return userList;
1000         }
1001
1002         @Override
1003         public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
1004                 final Map<String, String> params = new HashMap<>();
1005                 List<EPUser> userList = null;
1006                 CentralV2User cenV2User = null;
1007                 String result = null;
1008                 try {
1009                         params.put("orgUserIdValue", loginId);
1010                         List<EPApp> appList = getApp(uebkey);
1011                         if (!appList.isEmpty()) {
1012                                 userList = getUser(loginId);
1013                                 if (!userList.isEmpty()) {
1014                                         ObjectMapper mapper = new ObjectMapper();
1015                                         cenV2User = getV2UserAppRoles(loginId, uebkey);
1016                                         result = mapper.writeValueAsString(cenV2User);
1017                                 } else if (userList.isEmpty()) {
1018                                         throw new InvalidUserException("User not found");
1019                                 }
1020                         } else {
1021                                 throw new InactiveApplicationException("Application not found");
1022                         }
1023                 } catch (Exception e) {
1024                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
1025                         throw e;
1026                 }
1027                 return result;
1028         }
1029
1030         @Override
1031         public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
1032                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
1033                 List<CentralV2Role> roleList = new ArrayList<>();
1034                 final Map<String, Long> params = new HashMap<>();
1035                 try {
1036                         List<EPApp> app = getApp(uebkey);
1037                         List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
1038                         roleList = createCentralRoleObject(app, appRolesList, roleList, params);
1039                         if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1040                                 List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1041                                 List<EPRole> globalRolesList = getGlobalRolesOfPortal();
1042                                 List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
1043                                 if (!globalRolesList.isEmpty()) {
1044                                         for (EPRole eprole : globalRolesList) {
1045                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
1046                                                 portalsGlobalRolesFinlaList.add(cenRole);
1047                                         }
1048                                         roleList.addAll(globalRoleList);
1049                                         for (CentralV2Role role : portalsGlobalRolesFinlaList) {
1050                                                 CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
1051                                                                 .orElse(null);
1052                                                 if (result == null)
1053                                                         roleList.add(role);
1054                                         }
1055                                 } else {
1056                                         for (EPRole role : globalRolesList) {
1057                                                 CentralV2Role cenRole = convertRoleToCentralV2Role(role);
1058                                                 roleList.add(cenRole);
1059                                         }
1060                                 }
1061                         }
1062                 } catch (Exception e) {
1063                         logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
1064                         throw e;
1065                 }
1066                 logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
1067                 return roleList.stream().distinct().collect(Collectors.toList());
1068         }
1069
1070         @SuppressWarnings("unchecked")
1071         @Override
1072         public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
1073                 EPApp app = getApp(uebkey).get(0);
1074                 List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
1075                 final Map<String, Long> params = new HashMap<>();
1076                 params.put(APP_ID, app.getId());
1077                 List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
1078                                 null);
1079                 for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
1080                         String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
1081                         String type = "";
1082                         if (roleFuncItem.getCode().contains("|"))
1083                                 type = EcompPortalUtils.getFunctionType(roleFuncItem.getCode());
1084                         else
1085                                 type = getFunctionCodeType(roleFuncItem.getCode());
1086                         String action = getFunctionCodeAction(roleFuncItem.getCode());
1087                         roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
1088                         roleFuncItem.setType(type);
1089                         roleFuncItem.setAction(action);
1090                         finalRoleList.add(roleFuncItem);
1091                 }
1092                 return finalRoleList;
1093         }
1094
1095         @Override
1096         public String getFunctionCodeAction(String roleFuncItem) {
1097                 return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
1098         }
1099
1100         @Override
1101         public String getFunctionCodeType(String roleFuncItem) {
1102                 String type = null;
1103                 if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
1104                                 || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
1105                         type = "menu";
1106                 } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
1107                                 || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
1108                         type = "url";
1109                 } else if (roleFuncItem.contains(FUNCTION_PIPE)
1110                                 && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
1111                         type = EcompPortalUtils.getFunctionType(roleFuncItem);
1112                 }
1113                 return type;
1114         }
1115
1116         /**
1117          * 
1118          * It check whether function code has no pipes and no url string in it
1119          * 
1120          * @param roleFuncItem
1121          * @return true or false
1122          */
1123         private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
1124                 return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
1125         }
1126
1127         /**
1128          * 
1129          * It check whether function code has pipes and url string in it
1130          * 
1131          * @param roleFuncItem
1132          * @return true or false
1133          */
1134         private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
1135                 return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1136         }
1137
1138         /**
1139          * 
1140          * It check whether function code has no pipes and has url string in it
1141          * 
1142          * @param roleFuncItem
1143          * @return true or false
1144          */
1145         private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
1146                 return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
1147         }
1148
1149         /**
1150          * It returns user detail information which is deep copy of EPUser.class object
1151          * 
1152          * @param userInfo
1153          * @param userAppSet
1154          * @param app
1155          * @return
1156          * @throws Exception
1157          */
1158         @SuppressWarnings("unchecked")
1159         private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
1160                 final Map<String, Long> params = new HashMap<>();
1161                 CentralV2User userAppList = new CentralV2User();
1162                 CentralV2User user1 = null;
1163                 final Map<String, Long> params1 = new HashMap<>();
1164                 List<EPRole> globalRoleList = new ArrayList<>();
1165                 try {
1166                         if (app.getId() != PortalConstants.PORTAL_APP_ID) {
1167                                 params1.put("userId", userInfo.getId());
1168                                 params1.put("appId", app.getId());
1169                                 globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
1170                         }
1171                         userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
1172                         for (EPUserApp userApp : userAppSet) {
1173                                 if (userApp.getRole().getActive()) {
1174                                         EPApp epApp = userApp.getApp();
1175                                         String globalRole = userApp.getRole().getName().toLowerCase();
1176                                         if (((epApp.getId().equals(app.getId()))
1177                                                         && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
1178                                                         || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
1179                                                                         && (globalRole.toLowerCase().startsWith("global_")))) {
1180                                                 CentralV2UserApp cua = new CentralV2UserApp();
1181                                                 cua.setUserId(null);
1182                                                 CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
1183                                                                 epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
1184                                                                 epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
1185                                                                 epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
1186                                                                 epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
1187                                                                 String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
1188                                                                 epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
1189                                                                 epApp.getUebTopicName());
1190                                                 cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
1191                                                 cua.setApp(cenApp);
1192                                                 Long appId = null;
1193                                                 if (globalRole.toLowerCase().startsWith("global_")
1194                                                                 && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
1195                                                                 && !epApp.getId().equals(app.getId())) {
1196                                                         appId = app.getId();
1197                                                         EPRole result = null;
1198                                                         if (globalRoleList.size() > 0)
1199                                                                 result = globalRoleList.stream()
1200                                                                                 .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
1201                                                                                 .orElse(null);
1202                                                         if (result == null)
1203                                                                 continue;
1204                                                 } else {
1205                                                         appId = userApp.getApp().getId();
1206                                                 }
1207                                                 params.put("roleId", userApp.getRole().getId());
1208                                                 params.put(APP_ID, appId);
1209                                                 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
1210                                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
1211                                                 SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1212                                                 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
1213                                                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1214                                                         String type = getFunctionCodeType(roleFunc.getCode());
1215                                                         String action = getFunctionCodeAction(roleFunc.getCode());
1216                                                         CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
1217                                                                         functionCode, roleFunc.getName(), null, type, action, null);
1218                                                         roleFunctionSet.add(cenRoleFunc);
1219                                                 }
1220                                                 Long userRoleId = null;
1221                                                 if (globalRole.toLowerCase().startsWith("global_")
1222                                                                 || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1223                                                         userRoleId = userApp.getRole().getId();
1224                                                 } else {
1225                                                         userRoleId = userApp.getRole().getAppRoleId();
1226                                                 }
1227                                                 CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
1228                                                                 userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
1229                                                                 userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
1230                                                                 userApp.getRole().getName(), userApp.getRole().getActive(),
1231                                                                 userApp.getRole().getPriority(), roleFunctionSet, null, null);
1232                                                 cua.setRole(cenRole);
1233                                                 userAppList.getUserApps().add(cua);
1234                                         }
1235                                 }
1236                         }
1237                         user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
1238                                         userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
1239                                         userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
1240                                         userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
1241                                         userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
1242                                         userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
1243                                         userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
1244                                         userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
1245                                         userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
1246                                         userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
1247                                         userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
1248                                         userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
1249                                         userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
1250                                         userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
1251                                         userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
1252                 } catch (Exception e) {
1253                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
1254                         throw e;
1255                 }
1256                 return user1;
1257         }
1258
1259         @Override
1260         public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
1261                 final Map<String, Long> params = new HashMap<>();
1262                 List<CentralV2Role> roleList = new ArrayList<>();
1263                 CentralV2Role cenRole = new CentralV2Role();
1264                 List<EPRole> roleInfo = null;
1265                 List<EPApp> app = null;
1266                 try {
1267                         app = getApp(uebkey);
1268                         if (app.isEmpty()) {
1269                                 throw new InactiveApplicationException("Application not found");
1270                         }
1271                         if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
1272                                 List<EPRole> globalRoleList = new ArrayList<>();
1273                                 globalRoleList = getGlobalRolesOfPortal();
1274                                 if (globalRoleList.size() > 0) {
1275                                         EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
1276                                                         .orElse(null);
1277                                         if (result != null)
1278                                                 return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
1279                                 }
1280                         }
1281                         if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1282                                 roleInfo = getPortalAppRoleInfo(roleId);
1283                         } else {
1284                                 roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
1285                         }
1286                         roleList = createCentralRoleObject(app, roleInfo, roleList, params);
1287                         if (roleList.isEmpty()) {
1288                                 return cenRole;
1289                         }
1290                 } catch (Exception e) {
1291                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
1292                         throw e;
1293                 }
1294                 return roleList.get(0);
1295         }
1296
1297         @SuppressWarnings("unchecked")
1298         private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
1299                 List<EPRole> roleInfo;
1300                 final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
1301                 getPartnerAppRoleParams.put("appRoleId", roleId);
1302                 getPartnerAppRoleParams.put("appId", app.getId());
1303                 roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
1304                 if (roleInfo.isEmpty()) {
1305                         getPartnerAppRoleParams.put("appRoleId", roleId);
1306                         roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
1307                 }
1308                 return roleInfo;
1309         }
1310
1311         @Override
1312         @SuppressWarnings("unchecked")
1313         public List<EPRole> getPortalAppRoleInfo(Long roleId) {
1314                 List<EPRole> roleInfo;
1315                 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1316                 getPortalAppRoleParams.put("roleId", roleId);
1317                 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1318                 return roleInfo;
1319         }
1320
1321         /**
1322          * 
1323          * It returns list of app roles along with role functions and which went through
1324          * deep copy
1325          * 
1326          * @param app
1327          * @param roleInfo
1328          * @param roleList
1329          * @param params
1330          * @return
1331          * @throws DecoderException
1332          */
1333         @SuppressWarnings("unchecked")
1334         @Override
1335         public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1336                         List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1337                 for (EPRole role : roleInfo) {
1338                         params.put("roleId", role.getId());
1339                         params.put(APP_ID, app.get(0).getId());
1340                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1341                                         params, null);
1342                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1343                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1344                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1345                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1346                                 String type = getFunctionCodeType(roleFunc.getCode());
1347                                 String action = getFunctionCodeAction(roleFunc.getCode());
1348                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1349                                                 roleFunc.getName(), null, type, action, null);
1350                                 roleFunctionSet.add(cenRoleFunc);
1351                         }
1352                         SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1353                         SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1354                         CentralV2Role cenRole = null;
1355                         if (role.getAppRoleId() == null) {
1356                                 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1357                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1358                                                 roleFunctionSet, childRoles, parentRoles);
1359                         } else {
1360                                 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1361                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1362                                                 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1363                         }
1364                         roleList.add(cenRole);
1365                 }
1366                 return roleList;
1367         }
1368
1369         @SuppressWarnings("unchecked")
1370         @Override
1371         public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1372                 String code = EcompPortalUtils.getFunctionCode(functionCode);
1373                 String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
1374                 CentralV2RoleFunction roleFunc = null;
1375                 EPApp app = getApp(uebkey).get(0);
1376                 List<CentralV2RoleFunction> getRoleFuncList = null;
1377                 final Map<String, String> params = new HashMap<>();
1378                 try {
1379                         params.put(FUNCTION_CODE_PARAMS, functionCode);
1380                         params.put(APP_ID, String.valueOf(app.getId()));
1381                         getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1382                         if (getRoleFuncList.isEmpty()) {
1383                                 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1384                                 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1385                                 if (getRoleFuncList.isEmpty()) {
1386                                         return roleFunc;
1387                                 }
1388                         }
1389                         if (getRoleFuncList.size() > 1) {
1390                                 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1391                                 if (cenV2RoleFunction == null)
1392                                         return roleFunc;
1393                                 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1394                         } else {
1395                                 // Check even if single record have pipes
1396                                 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1397                                         roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1398                                 } else {
1399                                         roleFunc = getRoleFuncList.get(0);
1400                                 }
1401                         }
1402                 } catch (Exception e) {
1403                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1404                         throw e;
1405                 }
1406                 return roleFunc;
1407         }
1408
1409         private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1410                 CentralV2RoleFunction roleFunc;
1411                 String functionCodeFormat = getRoleFuncList.getCode();
1412                 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1413                         String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1414                         String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1415                         String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1416                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1417                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
1418                                         newfunctionActionFormat, getRoleFuncList.getEditUrl());
1419                 } else {
1420                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(),
1421                                         getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl());
1422                 }
1423                 return roleFunc;
1424         }
1425
1426         @Override
1427         public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1428                         throws Exception {
1429                 boolean saveOrUpdateFunction = false;
1430                 try {
1431                         if(EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getCode()))
1432                          domainCentralRoleFunction.setCode(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getCode()));
1433                         final Map<String, String> functionParams = new HashMap<>();
1434                         functionParams.put("appId", String.valueOf(app.getId()));
1435                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1436                                 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1437                         }
1438                         if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
1439                                 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE
1440                                                 + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction());
1441                         }
1442                         domainCentralRoleFunction.setAppId(app.getId());
1443                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1444                         saveOrUpdateFunction = true;
1445                 } catch (Exception e) {
1446                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1447                         throw e;
1448                 }
1449                 return saveOrUpdateFunction;
1450         }
1451
1452         /**
1453          * It creates application permission in external auth system
1454          * 
1455          * @param domainCentralRoleFunction
1456          * @param app
1457          * @throws Exception
1458          */
1459         private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1460                         throws Exception {
1461                 ObjectMapper mapper = new ObjectMapper();
1462                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1463                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1464                 String type = "";
1465                 String instance = "";
1466                 String action = "";
1467                 if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
1468                                 || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) {
1469                         type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1470                                         ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode())
1471                                         : domainCentralRoleFunction.getType();
1472                         instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1473                                         ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode())
1474                                         : domainCentralRoleFunction.getCode();
1475                         action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1476                                         ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode())
1477                                         : domainCentralRoleFunction.getAction();
1478                 } else {
1479                         type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1480                         instance = domainCentralRoleFunction.getCode();
1481                         action = "*";
1482                 }
1483                 // get Permissions from External Auth System
1484                 JSONArray extPermsList = getExtAuthPermissions(app);
1485                 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1486                 String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
1487                 boolean checkIfFunctionsExits = permsDetailList.stream()
1488                                 .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1489                 if (!checkIfFunctionsExits) {
1490                         try {
1491                                 extPerms.setAction(action);
1492                                 extPerms.setInstance(instance);
1493                                 extPerms.setType(app.getNameSpace() + "." + type);
1494                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1495                                 String addFunction = mapper.writeValueAsString(extPerms);
1496                                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1497                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
1498                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1499                                 ResponseEntity<String> addPermResponse = template.exchange(
1500                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1501                                                 HttpMethod.POST, entity, String.class);
1502                                 logger.debug(EELFLoggerDelegate.debugLogger,
1503                                                 "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
1504                                                 addPermResponse.getStatusCode().value(), addFunction);
1505                         } catch (HttpClientErrorException e) {
1506                                 logger.error(EELFLoggerDelegate.errorLogger,
1507                                                 "HttpClientErrorException - Failed to add function in external central auth system", e);
1508                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1509                                 throw e;
1510                         } catch (Exception e) {
1511                                 logger.error(EELFLoggerDelegate.errorLogger,
1512                                                 "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
1513                                 throw e;
1514                         }
1515                 } else {
1516                         try {
1517                                 extPerms.setAction(action);
1518                                 extPerms.setInstance(instance);
1519                                 extPerms.setType(app.getNameSpace() + "." + type);
1520                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1521                                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1522                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1523                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
1524                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1525                                 ResponseEntity<String> updatePermResponse = template.exchange(
1526                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1527                                                 HttpMethod.PUT, entity, String.class);
1528                                 logger.debug(EELFLoggerDelegate.debugLogger,
1529                                                 "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
1530                                                 updateRoleFunction, updatePermResponse.getStatusCode().value());
1531                         } catch (HttpClientErrorException e) {
1532                                 logger.error(EELFLoggerDelegate.errorLogger,
1533                                                 "HttpClientErrorException - Failed to add function in external central auth system", e);
1534                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1535                                 throw e;
1536                         } catch (Exception e) {
1537                                 logger.error(EELFLoggerDelegate.errorLogger,
1538                                                 "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1539                                                 e);
1540                                 throw e;
1541                         }
1542                 }
1543         }
1544
1545         @SuppressWarnings("unchecked")
1546         @Override
1547         @Transactional(rollbackFor = Exception.class)
1548         public boolean deleteCentralRoleFunction(String code, EPApp app) {
1549                 boolean deleteFunctionResponse = false;
1550                 try {
1551                         final Map<String, String> params = new HashMap<>();
1552                         params.put(FUNCTION_CODE_PARAMS, code);
1553                         params.put(APP_ID, String.valueOf(app.getId()));
1554                         List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1555                                         .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1556                         CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1557                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1558                                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1559                                 // Delete role function dependency records
1560                                 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1561                         }
1562                         dataAccessService.deleteDomainObject(appFunctionCode, null);
1563                         deleteFunctionResponse = true;
1564                 } catch (Exception e) {
1565                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1566                 }
1567                 return deleteFunctionResponse;
1568         }
1569
1570         /**
1571          * It deletes app function record in portal
1572          * 
1573          * @param code
1574          * @param app
1575          */
1576         private void deleteAppRoleFunctions(String code, EPApp app) {
1577                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1578                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1579         }
1580
1581         /**
1582          * 
1583          * It deletes permission in the external auth system
1584          * 
1585          * @param domainCentralRoleFunction
1586          * @param app
1587          * @throws Exception
1588          */
1589         private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1590                         throws Exception {
1591                 try {
1592                         ObjectMapper mapper = new ObjectMapper();
1593                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
1594                         String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1595                         String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1596                         String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1597                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1598                         extPerms.setAction(actionValue);
1599                         extPerms.setInstance(instanceValue);
1600                         extPerms.setType(app.getNameSpace() + "." + checkType);
1601                         extPerms.setDescription(domainCentralRoleFunction.getName());
1602                         String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1603                         HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1604                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1605                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1606                         ResponseEntity<String> delPermResponse = template
1607                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1608                                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1609                         logger.debug(EELFLoggerDelegate.debugLogger,
1610                                         "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1611                                         deleteRoleFunction, delPermResponse.getStatusCode().value());
1612                 } catch (HttpClientErrorException e) {
1613                         logger.error(EELFLoggerDelegate.errorLogger,
1614                                         "HttpClientErrorException - Failed to delete functions in External System", e);
1615                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1616                 } catch (Exception e) {
1617                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1618                                 logger.debug(EELFLoggerDelegate.debugLogger,
1619                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
1620                                                 e.getMessage());
1621                         } else {
1622                                 logger.error(EELFLoggerDelegate.errorLogger,
1623                                                 "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1624                         }
1625                 }
1626         }
1627
1628         @Override
1629         public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1630                 boolean response = false;
1631                 String message = "";
1632                 try {
1633                         EPApp app = getApp(uebkey).get(0);
1634                         addRoleInEcompDB(saveRole, app);
1635                         response = true;
1636                 } catch (Exception e) {
1637                         message = e.getMessage();
1638                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1639                 }
1640                 return new ExternalRequestFieldsValidator(response, message);
1641         }
1642
1643         @SuppressWarnings("unchecked")
1644         @Override
1645         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1646                 Session localSession = sessionFactory.openSession();
1647                 Transaction transaction = null;
1648                 boolean result = false;
1649                 try {
1650                         List<EPRole> epRoleList = null;
1651                         EPApp app = getApp(uebkey).get(0);
1652                         final Map<String, String> deleteRoleParams = new HashMap<>();
1653                         deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1654                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1655                                 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1656                         } else {
1657                                 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1658                                 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
1659                                                 deleteRoleParams, null);
1660                         }
1661                         if (!epRoleList.isEmpty()) {
1662                                 transaction = localSession.beginTransaction();
1663                                 // Delete app role functions before deleting role
1664                                 deleteRoleFunction(app, epRoleList);
1665                                 if (app.getId() == 1) {
1666                                         // Delete fn_user_ role
1667                                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1668                                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1669                                         boolean isPortalRequest = false;
1670                                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1671                                 }
1672                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1673                                 transaction.commit();
1674                                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1675                                 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1676                         }
1677                         result = true;
1678                 } catch (Exception e) {
1679                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1680                         result = false;
1681                 } finally {
1682                         localSession.close();
1683                 }
1684                 return result;
1685         }
1686
1687         /**
1688          * 
1689          * It deletes role for application in external auth system
1690          * 
1691          * @param epRoleList contains role information
1692          * @param app        contains application information
1693          * @throws Exception
1694          */
1695         private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1696                 ResponseEntity<String> deleteResponse;
1697                 ResponseEntity<String> res = getNameSpaceIfExists(app);
1698                 if (res.getStatusCode() == HttpStatus.OK) {
1699                         // Delete Role in External System
1700                         String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1701                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1702                         deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1703                         if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1704                                 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1705                                 logger.error(EELFLoggerDelegate.errorLogger,
1706                                                 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1707                                                 deleteResponse.getBody());
1708                         }
1709                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1710                 }
1711         }
1712
1713         /**
1714          * 
1715          * It deletes application user role in external auth system
1716          * 
1717          * @param role
1718          * @param app
1719          * @param LoginId
1720          * @throws Exception
1721          */
1722         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1723                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1724                 HttpEntity<String> entity = new HttpEntity<>(headers);
1725                 getNameSpaceIfExists(app);
1726                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1727                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1728                 ResponseEntity<String> getResponse = template.exchange(
1729                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1730                                                 + LoginId
1731                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1732                                                 + "/" + app.getNameSpace() + "."
1733                                                 + role.getName()
1734                                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1735                                 HttpMethod.GET, entity, String.class);
1736                 logger.debug(EELFLoggerDelegate.debugLogger,
1737                                 "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
1738                                 getResponse.getBody());
1739                 if (getResponse.getStatusCode().value() != 200) {
1740                         throw new ExternalAuthSystemException(getResponse.getBody());
1741                 }
1742                 String res = getResponse.getBody();
1743                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1744                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1745                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1746                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1747                         ResponseEntity<String> deleteResponse = template.exchange(
1748                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1749                                                         + LoginId
1750                                                         + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1751                                                         + "/" + app.getNameSpace() + "."
1752                                                         + role.getName().replaceAll(
1753                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1754                                         HttpMethod.DELETE, userRoleentity, String.class);
1755                         if (deleteResponse.getStatusCode().value() != 200) {
1756                                 throw new ExternalAuthSystemException("Failed to delete user role");
1757                         }
1758                         logger.debug(EELFLoggerDelegate.debugLogger,
1759                                         "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
1760                                         deleteResponse.getStatusCode().value());
1761                 }
1762         }
1763
1764         @SuppressWarnings("unchecked")
1765         @Override
1766         public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1767                 List<CentralV2Role> roleList = new ArrayList<>();
1768                 try {
1769                         List<EPApp> app = getApp(uebkey);
1770                         final Map<String, Long> params = new HashMap<>();
1771                         // check if portal
1772                         Long appId = null;
1773                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1774                                 appId = app.get(0).getId();
1775                         }
1776                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
1777                         Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1778                         Criterion appIdCrt;
1779                         if (appId == null)
1780                                 appIdCrt = Restrictions.isNull("appId");
1781                         else
1782                                 appIdCrt = Restrictions.eq("appId", appId);
1783                         Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1784                         restrictionsList.add(andCrit);
1785                         List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1786                         roleList = createCentralRoleObject(app, epRole, roleList, params);
1787                         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1788                         if (globalRoleList.size() > 0)
1789                                 roleList.addAll(globalRoleList);
1790                 } catch (Exception e) {
1791                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1792                         throw e;
1793                 }
1794                 return roleList;
1795         }
1796
1797         @Override
1798         @Transactional(rollbackFor = Exception.class)
1799         public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
1800                         throws Exception {
1801                 Session localSession = sessionFactory.openSession();
1802                 String message = "";
1803                 Transaction transaction = null;
1804                 boolean response = false;
1805                 EPApp app = null;
1806                 try {
1807                         transaction = localSession.beginTransaction();
1808                         List<EPRole> epRoleList = null;
1809                         app = getApp(uebkey).get(0);
1810                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1811                                 epRoleList = getPortalAppRoleInfo(roleId);
1812                         } else {
1813                                 epRoleList = getPartnerAppRoleInfo(roleId, app);
1814                         }
1815                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1816                                 // Delete User Role in External System before deleting role
1817                                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1818                         }
1819                         // Delete user app roles
1820                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1821                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1822                         boolean isPortalRequest = false;
1823                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1824                         transaction.commit();
1825                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1826                                 // Final call to delete role once all dependencies has been
1827                                 // deleted
1828                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1829                         }
1830                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null);
1831                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1832                         response = true;
1833                 } catch (HttpClientErrorException e) {
1834                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1835                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1836                         message = e.getMessage();
1837                 } catch (Exception e) {
1838                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1839                         EcompPortalUtils.rollbackTransaction(transaction,
1840                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1841                         message = e.getMessage();
1842                 } finally {
1843                         localSession.close();
1844                 }
1845                 return new ExternalRequestFieldsValidator(response, message);
1846         }
1847
1848         @Override
1849         @SuppressWarnings("unchecked")
1850         @Transactional
1851         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1852                 try {
1853                         // get Permissions from External Auth System
1854                         JSONArray extPerms = getExtAuthPermissions(app);
1855                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1856                         // get functions in DB
1857                         final Map<String, Long> params = new HashMap<>();
1858                         final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1859                         params.put(APP_ID, app.getId());
1860                         List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions",
1861                                         params, null);
1862                         if (!appFunctions.isEmpty()) {
1863                                 for (CentralV2RoleFunction roleFunc : appFunctions) {
1864                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
1865                                 }
1866                         }
1867                         // get Roles for portal in DB
1868                         List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1869                         final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1870                         for (EPRole epRole : portalRoleList) {
1871                                 existingPortalRolesMap.put(epRole.getName().replaceAll(
1872                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1873                         }
1874                         // get Roles in DB
1875                         final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
1876                         // store External Permissions with Pipe and without Pipe (just
1877                         // instance)
1878                         final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1879                         final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1880                         for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1881                                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1882                                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1883                                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1884                         }
1885                         // Add if new functions and app role functions were added in
1886                         // external auth system
1887                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1888                                 String code = permsDetail.getInstance();
1889                                 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1890                                 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1891                                                 getFunctionCodeKey);
1892                                 List<String> roles = permsDetail.getRoles();
1893                                 if (roles != null) {
1894                                         // Check if function has any roles and which does not exist
1895                                         // in External Auth System. If exists delete in local
1896                                         addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
1897                                                         existingPortalRolesMap);
1898                                 }
1899                         }
1900                         // Check if function does exits in External Auth System but exits in
1901                         // local then delete function and its dependencies
1902                         for (CentralV2RoleFunction roleFunc : appFunctions) {
1903                                 try {
1904                                         ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1905                                                         .get(roleFunc.getCode());
1906                                         if (null == getFunctionCodeContainsPipeKey) {
1907                                                 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1908                                                 if (null == getFunctionCodeKey) {
1909                                                         deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1910                                                 }
1911                                         }
1912                                 } catch (Exception e) {
1913                                         logger.error(EELFLoggerDelegate.errorLogger,
1914                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1915                                 }
1916                         }
1917                         logger.debug(EELFLoggerDelegate.debugLogger,
1918                                         "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1919                 } catch (Exception e) {
1920                         logger.error(EELFLoggerDelegate.errorLogger,
1921                                         "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1922                 }
1923         }
1924
1925         @SuppressWarnings("unchecked")
1926         private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
1927                         List<CentralV2RoleFunction> roleFunctionList, List<String> roles,
1928                         Map<String, EPRole> existingPortalRolesMap) throws Exception {
1929                 if (!roleFunctionList.isEmpty()) {
1930                         final Map<String, String> appRoleFuncParams = new HashMap<>();
1931                         final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1932                         final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1933                         appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
1934                         appRoleFuncParams.put("appId", String.valueOf(app.getId()));
1935                         List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
1936                                         appRoleFuncParams, null);
1937                         for (LocalRole localRole : localRoleList) {
1938                                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1939                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1940                         }
1941                         for (String addRole : roles) {
1942                                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
1943                         }
1944                         for (String extAuthrole : roles) {
1945                                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1946                                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
1947                                                 app.getNameSpace());
1948                                 if (isNameSpaceMatching) {
1949                                         if (!currentAppRoleFunctionsMap
1950                                                         .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
1951                                                 EPRole localAddFuntionRole = currentRolesInDB
1952                                                                 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
1953                                                 if (localAddFuntionRole == null) {
1954                                                         checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1955                                                 } else {
1956                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1957                                                         addAppRoleFunc.setAppId(app.getId());
1958                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1959                                                         addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
1960                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
1961                                                 }
1962                                         }
1963                                         // This block is to save global role function if exists
1964                                 } else {
1965                                         String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1966                                         boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1967                                         if (checkIfGlobalRoleExists) {
1968                                                 final Map<String, Long> params = new HashMap<>();
1969                                                 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1970                                                 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
1971                                                 params.put("appId", app.getId());
1972                                                 params.put("roleId", role.getId());
1973                                                 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService
1974                                                                 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
1975                                                 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
1976                                                                 .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode()
1977                                                                                 .equals(roleFunctionList.get(0).getCode()));
1978                                                 if (role != null && !checkIfRoleFunctionExists) {
1979                                                         addGlobalRoleFunctions.setAppId(app.getId());
1980                                                         addGlobalRoleFunctions.setRoleId(role.getId());
1981                                                         if (!app.getId().equals(role.getAppRoleId())) {
1982                                                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1983                                                         } else {
1984                                                                 addGlobalRoleFunctions.setRoleAppId(null);
1985                                                         }
1986                                                         addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
1987                                                         dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
1988                                                 }
1989                                         }
1990                                 }
1991                         }
1992                         for (LocalRole localRoleDelete : localRoleList) {
1993                                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
1994                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
1995                                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1996                                                         APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
1997                                                                         + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
1998                                                         null);
1999                                 }
2000                         }
2001                 }
2002         }
2003
2004         private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2005                 logger.debug(EELFLoggerDelegate.debugLogger,
2006                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode());
2007                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2008                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2009                 logger.debug(EELFLoggerDelegate.debugLogger,
2010                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode());
2011                 logger.debug(EELFLoggerDelegate.debugLogger,
2012                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode());
2013                 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2014                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2015                 logger.debug(EELFLoggerDelegate.debugLogger,
2016                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode());
2017         }
2018
2019         private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2020                         List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2021                 if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) {
2022                         Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
2023                         addRoleDescriptionInExtSystem(role, app);
2024                         if (!roleFunctionList.isEmpty()) {
2025                                 try {
2026                                         if (!roleFunctionList.isEmpty()) {
2027                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2028                                                 addAppRoleFunc.setAppId(app.getId());
2029                                                 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2030                                                 addAppRoleFunc.setRoleId(role.getId());
2031                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2032                                         }
2033                                 } catch (Exception e) {
2034                                         logger.error(EELFLoggerDelegate.errorLogger,
2035                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
2036                                 }
2037                         }
2038                 }
2039         }
2040
2041         @SuppressWarnings("unchecked")
2042         private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app,
2043                         final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
2044                         CentralV2RoleFunction getFunctionCodeKey) {
2045                 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2046                                 getFunctionCodeKey);
2047                 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2048                 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2049                 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2050                 List<CentralV2RoleFunction> roleFunctionList = null;
2051                 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2052                                 null);
2053                 if (roleFunctionList.isEmpty()) {
2054                         appSyncFuncsParams.put("functionCd", code);
2055                         roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2056                                         null);
2057                 }
2058                 return roleFunctionList;
2059         }
2060
2061         private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2062                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2063                 String finalFunctionCodeVal = "";
2064                 if (null == getFunctionCodeKey) {
2065                         finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2066                         CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2067                         // If function does not exist in local then add!
2068                         if (null == checkIfCodeStillExits) {
2069                                 logger.debug(EELFLoggerDelegate.debugLogger,
2070                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2071                                 addFunctionInEcompDB(app, permsDetail, code);
2072                                 logger.debug(EELFLoggerDelegate.debugLogger,
2073                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2074                         }
2075                 }
2076                 return finalFunctionCodeVal;
2077         }
2078
2079         @SuppressWarnings("unchecked")
2080         @Override
2081         public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) {
2082                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2083                 List<EPRole> getCurrentRoleList = null;
2084                 final Map<String, Long> appParams = new HashMap<>();
2085                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2086                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2087                 } else {
2088                         appParams.put("appId", app.getId());
2089                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2090                 }
2091                 for (EPRole role : getCurrentRoleList) {
2092                         currentRolesInDB.put(role.getName()
2093                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2094                 }
2095                 return currentRolesInDB;
2096         }
2097
2098         @SuppressWarnings("unchecked")
2099         private Map<String, EPRole> getAppRoleNamesMap(EPApp app) {
2100                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2101                 List<EPRole> getCurrentRoleList = null;
2102                 final Map<String, Long> appParams = new HashMap<>();
2103                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2104                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2105                 } else {
2106                         appParams.put("appId", app.getId());
2107                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2108                 }
2109                 for (EPRole role : getCurrentRoleList) {
2110                         currentRolesInDB.put(role.getName(), role);
2111                 }
2112                 return currentRolesInDB;
2113         }
2114
2115         private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException {
2116                 ExternalAccessPermsDetail permDetails = null;
2117                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2118                 for (int i = 0; i < extPerms.length(); i++) {
2119                         String description = null;
2120                         if (extPerms.getJSONObject(i).has("description")) {
2121                                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2122                         } else {
2123                                 description = extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + "|"
2124                                                 + extPerms.getJSONObject(i).getString("instance") + "|"
2125                                                 + extPerms.getJSONObject(i).getString("action");
2126                         }
2127                         if (extPerms.getJSONObject(i).has("roles")) {
2128                                 ObjectMapper rolesListMapper = new ObjectMapper();
2129                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2130                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2131                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2132                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2133                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2134                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2135                                                                 + extPerms.getJSONObject(i).getString("action"),
2136                                                 extPerms.getJSONObject(i).getString("action"), list, description);
2137                                 permsDetailList.add(permDetails);
2138                         } else {
2139                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2140                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2141                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2142                                                                 + extPerms.getJSONObject(i).getString("action"),
2143                                                 extPerms.getJSONObject(i).getString("action"), description);
2144                                 permsDetailList.add(permDetails);
2145                         }
2146                 }
2147                 return permsDetailList;
2148         }
2149
2150         private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2151                 ResponseEntity<String> response = null;
2152                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2153                 HttpEntity<String> entity = new HttpEntity<>(headers);
2154                 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2155                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2156                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2157                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2158                 String res = response.getBody();
2159                 logger.debug(EELFLoggerDelegate.debugLogger,
2160                                 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2161                                 response.getBody());
2162                 JSONObject jsonObj = new JSONObject(res);
2163                 JSONArray extPerms = jsonObj.getJSONArray("perm");
2164                 for (int i = 0; i < extPerms.length(); i++) {
2165                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2166                                 extPerms.remove(i);
2167                                 i--;
2168                         }
2169                 }
2170                 return extPerms;
2171         }
2172
2173         /**
2174          * 
2175          * Add function into local DB
2176          * 
2177          * @param app
2178          * @param permsDetail
2179          * @param code
2180          */
2181         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2182                 try {
2183                         CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2184                         addFunction.setAppId(app.getId());
2185                         addFunction.setCode(code);
2186                         addFunction.setName(permsDetail.getDescription());
2187                         dataAccessService.saveDomainObject(addFunction, null);
2188                 } catch (Exception e) {
2189                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2190                 }
2191         }
2192
2193         /**
2194          * 
2195          * It updates description of a role in external auth system
2196          * 
2197          * @param role
2198          * @param app
2199          * @throws Exception
2200          */
2201         private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception {
2202                 boolean status = false;
2203                 try {
2204                         String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2205                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2206                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2207                         template.exchange(
2208                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2209                                         HttpMethod.PUT, entity, String.class);
2210                         status = true;
2211                 } catch (HttpClientErrorException e) {
2212                         logger.error(EELFLoggerDelegate.errorLogger,
2213                                         "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
2214                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2215                 } catch (Exception e) {
2216                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
2217                 }
2218                 return status;
2219         }
2220
2221         /**
2222          * 
2223          * While sync functions form external auth system if new role found we should
2224          * add in local and return Role.class object
2225          * 
2226          * @param app
2227          * @param role
2228          * @return
2229          */
2230         @SuppressWarnings("unchecked")
2231         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2232                 Role setNewRole = new Role();
2233                 try {
2234                         // functions can have new role created in External Auth System
2235                         // prevent
2236                         // duplication here
2237                         boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2238                         final Map<String, String> getRoleByNameParams = new HashMap<>();
2239                         List<EPRole> getRoleCreated = null;
2240                         getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2241                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2242                                 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2243                                 List<EPRole> roleCreated = dataAccessService
2244                                                 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2245                                 if (!isCreated) {
2246                                         EPRole epUpdateRole = roleCreated.get(0);
2247                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2248                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2249                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2250                                                         getRoleByNameParams, null);
2251                                 } else {
2252                                         getRoleCreated = roleCreated;
2253                                 }
2254                         } else {
2255                                 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2256                                                 null);
2257                         }
2258                         if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2259                                 EPRole roleObject = getRoleCreated.get(0);
2260                                 setNewRole.setId(roleObject.getId());
2261                                 setNewRole.setName(roleObject.getName());
2262                                 setNewRole.setActive(roleObject.getActive());
2263                                 setNewRole.setPriority(roleObject.getPriority());
2264                         }
2265                 } catch (Exception e) {
2266                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2267                 }
2268                 return setNewRole;
2269         }
2270
2271         @SuppressWarnings("unchecked")
2272         private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2273                 boolean isCreated = false;
2274                 final Map<String, String> roleParams = new HashMap<>();
2275                 roleParams.put(APP_ROLE_NAME_PARAM, role);
2276                 List<EPRole> roleCreated = null;
2277                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2278                         roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2279                 } else {
2280                         roleParams.put("appId", String.valueOf(app.getId()));
2281                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2282                                         null);
2283                 }
2284                 if (roleCreated == null || roleCreated.isEmpty()) {
2285                         roleParams.put("appId", String.valueOf(app.getId()));
2286                         EPRole epRoleNew = new EPRole();
2287                         epRoleNew.setActive(true);
2288                         epRoleNew.setName(role);
2289                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2290                                 epRoleNew.setAppId(null);
2291                         } else {
2292                                 epRoleNew.setAppId(app.getId());
2293                         }
2294                         dataAccessService.saveDomainObject(epRoleNew, null);
2295                         isCreated = false;
2296                 } else {
2297                         isCreated = true;
2298                 }
2299                 return isCreated;
2300         }
2301
2302         @Override
2303         @SuppressWarnings("unchecked")
2304         public Integer bulkUploadFunctions(String uebkey) throws Exception {
2305                 EPApp app = getApp(uebkey).get(0);
2306                 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2307                 CentralV2RoleFunction cenRoleFunc = null;
2308                 Integer functionsAdded = 0;
2309                 try {
2310                         for (RoleFunction roleFunc : roleFuncList) {
2311                                 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2312                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2313                                 functionsAdded++;
2314                         }
2315                 } catch (HttpClientErrorException e) {
2316                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2317                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2318                 } catch (Exception e) {
2319                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2320                 }
2321                 return functionsAdded;
2322         }
2323
2324         @Override
2325         public Integer bulkUploadRoles(String uebkey) throws Exception {
2326                 List<EPApp> app = getApp(uebkey);
2327                 List<EPRole> roles = getAppRoles(app.get(0).getId());
2328                 List<CentralV2Role> cenRoleList = new ArrayList<>();
2329                 final Map<String, Long> params = new HashMap<>();
2330                 Integer rolesListAdded = 0;
2331                 try {
2332                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2333                         ObjectMapper mapper = new ObjectMapper();
2334                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2335                         String roleList = mapper.writeValueAsString(cenRoleList);
2336                         List<Role> roleObjectList = mapper.readValue(roleList,
2337                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2338                         for (Role role : roleObjectList) {
2339                                 addRoleInExternalSystem(role, app.get(0));
2340                                 rolesListAdded++;
2341                         }
2342                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2343                                 // Add Account Admin role in External AUTH System
2344                                 try {
2345                                         String addAccountAdminRole = "";
2346                                         ExternalAccessRole extRole = new ExternalAccessRole();
2347                                         extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2348                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2349                                         addAccountAdminRole = mapper.writeValueAsString(extRole);
2350                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2351                                         HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2352                                         template.exchange(
2353                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2354                                                         HttpMethod.POST, entity, String.class);
2355                                         rolesListAdded++;
2356                                 } catch (HttpClientErrorException e) {
2357                                         logger.error(EELFLoggerDelegate.errorLogger,
2358                                                         "HttpClientErrorException - Failed to create Account Admin role", e);
2359                                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2360                                 } catch (Exception e) {
2361                                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2362                                                 logger.error(EELFLoggerDelegate.errorLogger,
2363                                                                 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2364                                                                 e);
2365                                         } else {
2366                                                 logger.error(EELFLoggerDelegate.errorLogger,
2367                                                                 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2368                                         }
2369                                 }
2370                         }
2371                 } catch (Exception e) {
2372                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2373                         throw e;
2374                 }
2375                 return rolesListAdded;
2376         }
2377
2378         /**
2379          * It creating new role in external auth system while doing bulk upload
2380          * 
2381          * @param role
2382          * @param app
2383          * @throws Exception
2384          */
2385         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2386                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2387                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2388                 try {
2389                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2390                         template.exchange(
2391                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2392                                         HttpMethod.POST, entity, String.class);
2393                 } catch (HttpClientErrorException e) {
2394                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
2395                                         e);
2396                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2397                 } catch (Exception e) {
2398                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2399                                 logger.error(EELFLoggerDelegate.errorLogger,
2400                                                 "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2401                         } else {
2402                                 logger.error(EELFLoggerDelegate.errorLogger,
2403                                                 "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2404                         }
2405                 }
2406         }
2407
2408         @Override
2409         @SuppressWarnings("unchecked")
2410         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2411                 EPApp app = getApp(uebkey).get(0);
2412                 List<EPRole> roles = getAppRoles(app.getId());
2413                 final Map<String, Long> params = new HashMap<>();
2414                 Integer roleFunctions = 0;
2415                 try {
2416                         for (EPRole role : roles) {
2417                                 params.put("roleId", role.getId());
2418                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2419                                                 params, null);
2420                                 if (!appRoleFunc.isEmpty()) {
2421                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2422                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2423                                                 roleFunctions++;
2424                                         }
2425                                 }
2426                         }
2427                 } catch (HttpClientErrorException e) {
2428                         logger.error(EELFLoggerDelegate.errorLogger,
2429                                         "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2430                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2431                 } catch (Exception e) {
2432                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2433                 }
2434                 return roleFunctions;
2435         }
2436
2437         /**
2438          * Its adding a role function while doing bulk upload
2439          * 
2440          * @param addRoleFunc
2441          * @param role
2442          * @param app
2443          */
2444         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2445                 String type = "";
2446                 String instance = "";
2447                 String action = "";
2448                 if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2449                         type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2450                         instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2451                         action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2452                 } else {
2453                         type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2454                         instance = addRoleFunc.getFunctionCd();
2455                         action = "*";
2456                 }
2457                 ExternalAccessRolePerms extRolePerms = null;
2458                 ExternalAccessPerms extPerms = null;
2459                 ObjectMapper mapper = new ObjectMapper();
2460                 try {
2461                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2462                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2463                                         addRoleFunc.getFunctionName());
2464                         extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName()
2465                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2466                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2467                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2468                         template.exchange(
2469                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2470                                         HttpMethod.POST, entity, String.class);
2471                 } catch (Exception e) {
2472                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2473                                 logger.error(EELFLoggerDelegate.errorLogger,
2474                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
2475                                                 e);
2476                         } else {
2477                                 logger.error(EELFLoggerDelegate.errorLogger,
2478                                                 "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
2479                         }
2480                 }
2481         }
2482
2483         @SuppressWarnings("unchecked")
2484         @Override
2485         public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2486                 EPApp app = getApp(uebkey).get(0);
2487                 final Map<String, Long> params = new HashMap<>();
2488                 params.put("appId", app.getId());
2489                 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2490                                 null);
2491                 Integer functionsAdded = 0;
2492                 try {
2493                         for (CentralV2RoleFunction roleFunc : roleFuncList) {
2494                                 addFunctionInExternalSystem(roleFunc, app);
2495                                 functionsAdded++;
2496                         }
2497                 } catch (HttpClientErrorException e) {
2498                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
2499                                         e);
2500                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2501                 } catch (Exception e) {
2502                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2503                 }
2504                 return functionsAdded;
2505         }
2506
2507         private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2508                 ObjectMapper mapper = new ObjectMapper();
2509                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2510                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2511                 String type = "";
2512                 String instance = "";
2513                 String action = "";
2514                 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2515                                 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2516                         type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2517                         instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2518                         action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2519                 } else {
2520                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2521                         instance = roleFunc.getCode();
2522                         action = "*";
2523                 }
2524                 try {
2525                         extPerms.setAction(action);
2526                         extPerms.setInstance(instance);
2527                         extPerms.setType(app.getNameSpace() + "." + type);
2528                         extPerms.setDescription(roleFunc.getName());
2529                         String addFunction = mapper.writeValueAsString(extPerms);
2530                         HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2531                         logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2532                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2533                         ResponseEntity<String> addPermResponse = template.exchange(
2534                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2535                                         HttpMethod.POST, entity, String.class);
2536                         logger.debug(EELFLoggerDelegate.debugLogger,
2537                                         "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2538                                         addPermResponse.getStatusCode().value(), addFunction);
2539                 } catch (HttpClientErrorException e) {
2540                         logger.error(EELFLoggerDelegate.errorLogger,
2541                                         "HttpClientErrorException - Failed to add function in external central auth system", e);
2542                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2543                         throw e;
2544                 } catch (Exception e) {
2545                         logger.error(EELFLoggerDelegate.errorLogger,
2546                                         "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2547                         throw e;
2548                 }
2549         }
2550
2551         @Override
2552         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2553                 EPApp app = getApp(uebkey).get(0);
2554                 for (Role role : roleList) {
2555                         addRoleInExternalSystem(role, app);
2556                 }
2557         }
2558
2559         @SuppressWarnings("unchecked")
2560         @Override
2561         public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2562                 EPApp app = getApp(uebkey).get(0);
2563                 List<EPRole> roles = getAppRoles(app.getId());
2564                 final Map<String, Long> params = new HashMap<>();
2565                 Integer roleFunctions = 0;
2566                 try {
2567                         for (EPRole role : roles) {
2568                                 params.put("roleId", role.getId());
2569                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService
2570                                                 .executeNamedQuery("uploadPartnerRoleFunctions", params, null);
2571                                 if (!appRoleFunc.isEmpty()) {
2572                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2573                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2574                                                 roleFunctions++;
2575                                         }
2576                                 }
2577                         }
2578                         // upload global role functions to ext auth system
2579                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2580                                 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2581                         }
2582                 } catch (HttpClientErrorException e) {
2583                         logger.error(EELFLoggerDelegate.errorLogger,
2584                                         "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2585                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2586                 } catch (Exception e) {
2587                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2588                 }
2589                 return roleFunctions;
2590         }
2591
2592         @SuppressWarnings("unchecked")
2593         private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2594                 try {
2595                         EPApp portalApp = epAppService.getApp(1l);
2596                         final Map<String, Long> params = new HashMap<>();
2597                         params.put("appId", app.getId());
2598                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2599                                         .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2600                         ObjectMapper mapper = new ObjectMapper();
2601                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2602                         for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2603                                 ExternalAccessRolePerms extRolePerms;
2604                                 ExternalAccessPerms extPerms;
2605                                 String type = "";
2606                                 String instance = "";
2607                                 String action = "";
2608                                 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2609                                         type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2610                                         instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2611                                         action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2612                                 } else {
2613                                         type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2614                                         instance = globalRoleFunc.getFunctionCd();
2615                                         action = "*";
2616                                 }
2617                                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2618                                 extRolePerms = new ExternalAccessRolePerms(extPerms,
2619                                                 portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName().replaceAll(
2620                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2621                                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2622                                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2623                                 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2624                                 roleFunctions++;
2625                         }
2626                 } catch (HttpClientErrorException e) {
2627                         logger.error(EELFLoggerDelegate.errorLogger,
2628                                         "HttpClientErrorException - Failed to add role function in external central auth system", e);
2629                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2630                         throw e;
2631                 } catch (Exception e) {
2632                         logger.error(EELFLoggerDelegate.errorLogger,
2633                                         "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2634                         throw e;
2635                 }
2636                 return roleFunctions;
2637         }
2638
2639         @Override
2640         @Transactional
2641         public void syncApplicationRolesWithEcompDB(EPApp app) {
2642                 try {
2643                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2644                         // Sync functions and roles assigned to it which also creates new roles if does
2645                         // not exits in portal
2646                         syncRoleFunctionFromExternalAccessSystem(app);
2647                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2648                         ObjectMapper mapper = new ObjectMapper();
2649                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2650                         // Get Permissions from External Auth System
2651                         JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2652                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2653                         // refactoring done
2654                         List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
2655                         List<EPRole> finalRoleList = new ArrayList<>();
2656                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2657                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2658                                 finalRoleList.add(ecompRole);
2659                         }
2660                         List<EPRole> applicationRolesList;
2661                         applicationRolesList = getAppRoles(app.getId());
2662                         List<String> applicationRoleIdList = new ArrayList<>();
2663                         for (EPRole applicationRole : applicationRolesList) {
2664                                 applicationRoleIdList.add(applicationRole.getName());
2665                         }
2666                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2667                         for (EPRole aafRole : finalRoleList) {
2668                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
2669                                         roleListToBeAddInEcompDB.add(aafRole);
2670                                 }
2671                         }
2672                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2673                         // Check if roles exits in external Access system and if not make inactive in DB
2674                         inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2675                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2676                         // Add new roles in DB and updates role description in External Auth System
2677                         addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2678                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2679                 } catch (HttpClientErrorException e) {
2680                         logger.error(EELFLoggerDelegate.errorLogger,
2681                                         "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2682                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2683                 } catch (Exception e) {
2684                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2685                 }
2686         }
2687
2688         /**
2689          * 
2690          * It adds new roles in DB and updates description in External Auth System
2691          * 
2692          * @param app
2693          * @param roleListToBeAddInEcompDB
2694          */
2695         @SuppressWarnings("unchecked")
2696         private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2697                 EPRole roleToBeAddedInEcompDB;
2698                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2699                         try {
2700                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2701                                 if (app.getId() == 1) {
2702                                         roleToBeAddedInEcompDB.setAppRoleId(null);
2703                                 }
2704                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2705                                 List<EPRole> getRoleCreatedInSync = null;
2706                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2707                                         final Map<String, String> globalRoleParams = new HashMap<>();
2708                                         globalRoleParams.put("appId", String.valueOf(app.getId()));
2709                                         globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2710                                         getRoleCreatedInSync = dataAccessService
2711                                                         .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2712                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2713                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2714                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2715                                 }
2716                                 List<EPRole> roleList = new ArrayList<>();
2717                                 final Map<String, String> params = new HashMap<>();
2718                                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2719                                 boolean isPortalRole = false;
2720                                 if (app.getId() == 1) {
2721                                         isPortalRole = true;
2722                                         roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2723                                 } else {
2724                                         isPortalRole = false;
2725                                         params.put(APP_ID, app.getId().toString());
2726                                         roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params,
2727                                                         null);
2728                                 }
2729                                 EPRole role = roleList.get(0);
2730                                 Role aaFrole = new Role();
2731                                 aaFrole.setId(role.getId());
2732                                 aaFrole.setActive(role.getActive());
2733                                 aaFrole.setPriority(role.getPriority());
2734                                 aaFrole.setName(role.getName());
2735                                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2736                         } catch (Exception e) {
2737                                 logger.error(EELFLoggerDelegate.errorLogger,
2738                                                 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2739                         }
2740                 }
2741         }
2742
2743         /**
2744          * 
2745          * It de-activates application roles in DB if not present in External Auth
2746          * system
2747          * 
2748          * @param app
2749          * @param finalRoleList        contains list of current roles present in
2750          *                             External Auth System
2751          * @param applicationRolesList contains list of current roles present in DB
2752          */
2753         @SuppressWarnings("unchecked")
2754         private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2755                         List<EPRole> applicationRolesList) {
2756                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2757                 for (EPRole extrole : finalRoleList) {
2758                         checkRolesInactive.put(extrole.getName(), extrole);
2759                 }
2760                 for (EPRole role : applicationRolesList) {
2761                         try {
2762                                 final Map<String, String> extRoleParams = new HashMap<>();
2763                                 List<EPRole> roleList = null;
2764                                 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2765                                 if (!checkRolesInactive.containsKey(role.getName())) {
2766                                         if (app.getId() == 1) {
2767                                                 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2768                                         } else {
2769                                                 extRoleParams.put(APP_ID, app.getId().toString());
2770                                                 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2771                                                                 extRoleParams, null);
2772                                         }
2773                                         if (!roleList.isEmpty()) {
2774                                                 EPRole updateRoleInactive = roleList.get(0);
2775                                                 updateRoleInactive.setActive(false);
2776                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
2777                                         }
2778                                 }
2779                         } catch (Exception e) {
2780                                 logger.error(EELFLoggerDelegate.errorLogger,
2781                                                 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2782                         }
2783                 }
2784         }
2785
2786         @Override
2787         @SuppressWarnings("unchecked")
2788         public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole)
2789                         throws IOException {
2790                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2791                 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2792                 List<String> functionCodelist = new ArrayList<>();
2793                 Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app);
2794                 Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
2795                 for (int i = 0; i < extRole.length(); i++) {
2796                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2797                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2798                         JSONObject Role = (JSONObject) extRole.get(i);
2799                         String name = extRole.getJSONObject(i).getString(ROLE_NAME);
2800                         String actualRoleName = name.substring(app.getNameSpace().length() + 1);
2801                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2802                                 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2803                         }
2804                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2805                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2806                                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2807                                 for (int j = 0; j < extPerm.length(); j++) {
2808                                         JSONObject perms = extPerm.getJSONObject(j);
2809                                         boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2810                                                         app.getNameSpace());
2811                                         if (isNamespaceMatching) {
2812                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2813                                                                 perms.getString("instance"), perms.getString("action"));
2814                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2815                                                 functionCodelist.add(ePAppRoleFunction.getCode());
2816                                                 externalAccessPermsOfRole.add(externalAccessPerms);
2817                                         }
2818                                 }
2819                         }
2820                         externalRoleDetail.setActive(true);
2821                         externalRoleDetail.setName(actualRoleName);
2822                         if (app.getId() == 1) {
2823                                 externalRoleDetail.setAppId(null);
2824                         } else {
2825                                 externalRoleDetail.setAppId(app.getId());
2826                         }
2827                         EPRole currRole = null;
2828                         currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
2829                                         ? curRolesUnderscoreMap.get(actualRoleName)
2830                                         : curRolesMap.get(actualRoleName);
2831                         Long roleId = null;
2832                         if (currRole != null)
2833                                 roleId = currRole.getId();
2834                         final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2835                         final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2836                         if (roleId != null) {
2837                                 appRoleFuncsParams.put("appId", app.getId());
2838                                 appRoleFuncsParams.put("roleId", roleId);
2839                                 // get role functions from DB
2840                                 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2841                                                 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2842                                 if (!appRoleFunctions.isEmpty()) {
2843                                         for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2844                                                 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2845                                         }
2846                                 }
2847                         }
2848                         if (!externalAccessPermsOfRole.isEmpty()) {
2849                                 // Adding functions to role
2850                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2851                                         EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2852                                         if (checkRoleFunctionExits == null) {
2853                                                 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2854                                                                 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2855                                                                 + externalpermission.getAction();
2856                                                 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2857                                                 if (checkRoleFunctionPipeExits == null) {
2858                                                         try {
2859                                                                 final Map<String, String> appFuncsParams = new HashMap<>();
2860                                                                 appFuncsParams.put("appId", String.valueOf(app.getId()));
2861                                                                 appFuncsParams.put("functionCd", externalpermission.getInstance());
2862                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
2863                                                                                 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2864                                                                                 externalpermission.getInstance());
2865                                                                 List<CentralV2RoleFunction> roleFunction = null;
2866                                                                 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2867                                                                                 appFuncsParams, null);
2868                                                                 if (roleFunction.isEmpty()) {
2869                                                                         appFuncsParams.put("functionCd", funcCode);
2870                                                                         roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2871                                                                                         appFuncsParams, null);
2872                                                                 }
2873                                                                 if (!roleFunction.isEmpty()) {
2874                                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2875                                                                         apRoleFunction.setAppId(app.getId());
2876                                                                         apRoleFunction.setRoleId(roleId);
2877                                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
2878                                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
2879                                                                 }
2880                                                         } catch (Exception e) {
2881                                                                 logger.error(EELFLoggerDelegate.errorLogger,
2882                                                                                 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2883                                                         }
2884                                                 }
2885                                         }
2886                                 }
2887                         }
2888                         externalRoleDetailsList.add(externalRoleDetail);
2889                 }
2890                 return externalRoleDetailsList;
2891         }
2892
2893         @Override
2894         public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2895                 ResponseEntity<String> response = null;
2896                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2897                 HttpEntity<String> entity = new HttpEntity<>(headers);
2898                 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2899                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2900                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2901                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2902                 String res = response.getBody();
2903                 logger.debug(EELFLoggerDelegate.debugLogger,
2904                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2905                                 res);
2906                 JSONObject jsonObj = new JSONObject(res);
2907                 JSONArray extRole = jsonObj.getJSONArray("role");
2908                 for (int i = 0; i < extRole.length(); i++) {
2909                         if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2910                                         || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2911                                         || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2912                                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2913                                 extRole.remove(i);
2914                                 i--;
2915                         }
2916                 }
2917                 return extRole;
2918         }
2919
2920         @Override
2921         public JSONArray getAllUsersByRole(String roleName) throws Exception {
2922                 ResponseEntity<String> response = null;
2923                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2924                 HttpEntity<String> entity = new HttpEntity<>(headers);
2925                 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2926                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2927                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2928                                 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2929                 String res = response.getBody();
2930                 logger.debug(EELFLoggerDelegate.debugLogger,
2931                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2932                                 res);
2933                 if (res == null || res.trim().isEmpty())
2934                         return null;
2935                 JSONObject jsonObj = new JSONObject(res);
2936                 JSONArray extRole = jsonObj.getJSONArray("userRole");
2937                 return extRole;
2938         }
2939
2940         /**
2941          * 
2942          * It converts from ExternalRoleDetails.class object to EPRole.class object
2943          * 
2944          * @param externalRoleDetails
2945          * @return EPRole object
2946          */
2947         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2948                 EPRole role = new EPRole();
2949                 role.setActive(true);
2950                 role.setAppId(externalRoleDetails.getAppId());
2951                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2952                 role.setName(externalRoleDetails.getName());
2953                 role.setPriority(externalRoleDetails.getPriority());
2954                 return role;
2955         }
2956
2957         @SuppressWarnings("unchecked")
2958         @Override
2959         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2960                 EPApp app = getApp(uebkey).get(0);
2961                 final Map<String, String> params = new HashMap<>();
2962                 params.put("uebKey", app.getUebKey());
2963                 List<BulkUploadUserRoles> userRolesList = null;
2964                 Integer userRolesAdded = 0;
2965                 if (app.getCentralAuth()) {
2966                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2967                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2968                                 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
2969                                         addUserRoleInExternalSystem(userRolesUpload);
2970                                         userRolesAdded++;
2971                                 }
2972                         }
2973                 }
2974                 return userRolesAdded;
2975         }
2976
2977         /**
2978          * Its adding a user role in external auth system while doing bulk upload
2979          * 
2980          * @param userRolesUpload
2981          */
2982         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2983                 try {
2984                         String name = "";
2985                         ObjectMapper mapper = new ObjectMapper();
2986                         if (EPCommonSystemProperties
2987                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2988                                 name = userRolesUpload.getOrgUserId()
2989                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2990                         }
2991                         ExternalAccessUser extUser = new ExternalAccessUser(name,
2992                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
2993                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2994                         String userRole = mapper.writeValueAsString(extUser);
2995                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2996                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2997                         template.exchange(
2998                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2999                                         HttpMethod.POST, entity, String.class);
3000                 } catch (HttpClientErrorException e) {
3001                         logger.error(EELFLoggerDelegate.errorLogger,
3002                                         "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3003                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3004                 } catch (Exception e) {
3005                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3006                                 logger.error(EELFLoggerDelegate.errorLogger,
3007                                                 "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3008                         } else {
3009                                 logger.error(EELFLoggerDelegate.errorLogger,
3010                                                 "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3011                         }
3012                 }
3013         }
3014
3015         @Override
3016         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest)
3017                         throws Exception {
3018                 try {
3019                         String sql = "";
3020                         Query query = null;
3021                         // It should delete only when it portal's roleId
3022                         if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
3023                                 // Delete from fn_role_function
3024                                 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3025                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3026                                 query = localSession.createSQLQuery(sql);
3027                                 query.executeUpdate();
3028                                 // Delete from fn_role_composite
3029                                 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3030                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3031                                 query = localSession.createSQLQuery(sql);
3032                                 query.executeUpdate();
3033                         }
3034                         // Delete from ep_app_role_function
3035                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3036                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3037                         query = localSession.createSQLQuery(sql);
3038                         query.executeUpdate();
3039                         // Delete from ep_role_notification
3040                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3041                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3042                         query = localSession.createSQLQuery(sql);
3043                         query.executeUpdate();
3044                         // Delete from fn_user_pseudo_role
3045                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3046                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3047                         query = localSession.createSQLQuery(sql);
3048                         query.executeUpdate();
3049                         // Delete form EP_WIDGET_CATALOG_ROLE
3050                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3051                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3052                         query = localSession.createSQLQuery(sql);
3053                         query.executeUpdate();
3054                         // Delete form EP_WIDGET_CATALOG_ROLE
3055                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3056                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3057                         query = localSession.createSQLQuery(sql);
3058                         query.executeUpdate();
3059                         if (!isPortalRequest) {
3060                                 // Delete form fn_menu_functional_roles
3061                                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3062                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3063                                 query = localSession.createSQLQuery(sql);
3064                                 query.executeUpdate();
3065                         }
3066                 } catch (Exception e) {
3067                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3068                         throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3069                 }
3070         }
3071
3072         @SuppressWarnings("unchecked")
3073         @Override
3074         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3075                 List<String> appMenuFunctionsList = null;
3076                 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3077                 try {
3078                         EPApp app = getApp(uebkey).get(0);
3079                         final Map<String, Long> appParams = new HashMap<>();
3080                         appParams.put(APP_ID, app.getId());
3081                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3082                         for (String appMenuFunction : appMenuFunctionsList) {
3083                                 if (appMenuFunction.contains(FUNCTION_PIPE)) {
3084                                         appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3085                                 } else {
3086                                         appMenuFunctionsFinalList.add(appMenuFunction);
3087                                 }
3088                         }
3089                 } catch (Exception e) {
3090                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3091                         return appMenuFunctionsFinalList;
3092                 }
3093                 return appMenuFunctionsFinalList;
3094         }
3095
3096         @SuppressWarnings({ "unchecked" })
3097         @Override
3098         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3099                 List<String> usersList = new ArrayList<>();
3100                 List<EcompUser> usersfinalList = new ArrayList<>();
3101                 try {
3102                         EPApp app = getApp(uebkey).get(0);
3103                         final Map<String, Long> appParams = new HashMap<>();
3104                         appParams.put("appId", app.getId());
3105                         List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3106                                         .executeNamedQuery("ApplicationUserRoles", appParams, null);
3107                         for (EcompUserRoles ecompUserRole : userList) {
3108                                 boolean found = false;
3109                                 Set<EcompRole> roles = null;
3110                                 for (EcompUser user : usersfinalList) {
3111                                         if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3112                                                 EcompRole ecompRole = new EcompRole();
3113                                                 ecompRole.setId(ecompUserRole.getRoleId());
3114                                                 ecompRole.setName(ecompUserRole.getRoleName());
3115                                                 roles = user.getRoles();
3116                                                 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
3117                                                                 .findAny().orElse(null);
3118                                                 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3119                                                 if (role != null) {
3120                                                         roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3121                                                 }
3122                                                 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3123                                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3124                                                 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3125                                                 epRoleFunction.setName(ecompUserRole.getFunctionName());
3126                                                 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3127                                                 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3128                                                 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3129                                                 roleFunctionSet.add(epRoleFunction);
3130                                                 ecompRole.setRoleFunctions(roleFunctionSet);
3131                                                 roles.add(ecompRole);
3132                                                 user.setRoles(roles);
3133                                                 found = true;
3134                                                 break;
3135                                         }
3136                                 }
3137                                 if (!found) {
3138                                         EcompUser epUser = new EcompUser();
3139                                         epUser.setOrgId(ecompUserRole.getOrgId());
3140                                         epUser.setManagerId(ecompUserRole.getManagerId());
3141                                         epUser.setFirstName(ecompUserRole.getFirstName());
3142                                         epUser.setLastName(ecompUserRole.getLastName());
3143                                         epUser.setPhone(ecompUserRole.getPhone());
3144                                         epUser.setEmail(ecompUserRole.getEmail());
3145                                         epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3146                                         epUser.setOrgCode(ecompUserRole.getOrgCode());
3147                                         epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3148                                         epUser.setJobTitle(ecompUserRole.getJobTitle());
3149                                         epUser.setLoginId(ecompUserRole.getLoginId());
3150                                         epUser.setActive(true);
3151                                         roles = new HashSet<>();
3152                                         EcompRole ecompRole = new EcompRole();
3153                                         ecompRole.setId(ecompUserRole.getRoleId());
3154                                         ecompRole.setName(ecompUserRole.getRoleName());
3155                                         SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3156                                         String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3157                                         functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3158                                         EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3159                                         epRoleFunction.setName(ecompUserRole.getFunctionName());
3160                                         epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3161                                         epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3162                                         epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3163                                         roleFunctionSet.add(epRoleFunction);
3164                                         ecompRole.setRoleFunctions(roleFunctionSet);
3165                                         roles.add(ecompRole);
3166                                         epUser.setRoles(roles);
3167                                         usersfinalList.add(epUser);
3168                                 }
3169                         }
3170                         ObjectMapper mapper = new ObjectMapper();
3171                         for (EcompUser u1 : usersfinalList) {
3172                                 String str = mapper.writeValueAsString(u1);
3173                                 usersList.add(str);
3174                         }
3175                 } catch (Exception e) {
3176                         logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3177                         throw e;
3178                 }
3179                 return usersfinalList;
3180         }
3181
3182         @Override
3183         public Role ConvertCentralRoleToRole(String result) {
3184                 ObjectMapper mapper = new ObjectMapper();
3185                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3186                 Role newRole = new Role();
3187                 try {
3188                         newRole = mapper.readValue(result, Role.class);
3189                 } catch (IOException e) {
3190                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3191                 }
3192                 if (newRole.getRoleFunctions() != null) {
3193                         @SuppressWarnings("unchecked")
3194                         Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3195                         Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3196                         Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3197                         while (itetaror.hasNext()) {
3198                                 Object nextValue = itetaror.next();
3199                                 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3200                                 roleFunctionListNew.add(roleFun);
3201                         }
3202                         newRole.setRoleFunctions(roleFunctionListNew);
3203                 }
3204                 return newRole;
3205         }
3206
3207         @Override
3208         @SuppressWarnings("unchecked")
3209         public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3210                 Map<String, String> params = new HashMap<>();
3211                 params.put("userId", userId);
3212                 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3213                 try {
3214                         centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null);
3215                 } catch (Exception e) {
3216                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3217                 }
3218                 return centralizedAppsList;
3219         }
3220
3221         @SuppressWarnings("unchecked")
3222         public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3223                 Map<String, Long> params = new HashMap<>();
3224                 params.put("appId", appId);
3225                 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3226                 try {
3227                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3228                                         null);
3229                 } catch (Exception e) {
3230                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3231                 }
3232                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3233                 if (globalRoles.size() > 0)
3234                         rolesfinalList = finalListOfCentralRoles(globalRoles);
3235                 return rolesfinalList;
3236         }
3237
3238         @SuppressWarnings("unchecked")
3239         private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3240                 CentralV2Role finalGlobalrole = null;
3241                 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3242                 Map<String, Long> params = new HashMap<>();
3243                 params.put("roleId", roleId);
3244                 params.put("requestedAppId", requestedAppId);
3245                 try {
3246                         roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3247                                         params, null);
3248                 } catch (Exception e) {
3249                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3250                 }
3251                 if (roleWithApplicationRoleFucntions.size() > 0) {
3252                         List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3253                         finalGlobalrole = rolesfinalList.get(0);
3254                 } else {
3255                         List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3256                         finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3257                 }
3258                 return finalGlobalrole;
3259         }
3260
3261         private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3262                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3263                 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3264                         boolean found = false;
3265                         for (CentralV2Role cenRole : rolesfinalList) {
3266                                 if (role.getRoleId().equals(cenRole.getId())) {
3267                                         SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3268                                         CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3269                                         roleFunctions.add(cenRoleFun);
3270                                         cenRole.setRoleFunctions(roleFunctions);
3271                                         found = true;
3272                                         break;
3273                                 }
3274                         }
3275                         if (!found) {
3276                                 CentralV2Role cenrole = new CentralV2Role();
3277                                 cenrole.setName(role.getRoleName());
3278                                 cenrole.setId(role.getRoleId());
3279                                 cenrole.setActive(role.isActive());
3280                                 cenrole.setPriority(role.getPriority());
3281                                 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3282                                 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3283                                 roleFunctions.add(cenRoleFun);
3284                                 cenrole.setRoleFunctions(roleFunctions);
3285                                 rolesfinalList.add(cenrole);
3286                         }
3287                 }
3288                 return rolesfinalList;
3289         }
3290
3291         private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3292                 String instance;
3293                 String type;
3294                 String action;
3295                 CentralV2RoleFunction cenRoleFun;
3296                 if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
3297                         instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3298                         type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3299                         action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3300                         cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3301                 } else {
3302                         type = getFunctionCodeType(role.getFunctionCd());
3303                         action = getFunctionCodeAction(role.getFunctionCd());
3304                         cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type,
3305                                         action, null);
3306                 }
3307                 return cenRoleFun;
3308         }
3309
3310         @SuppressWarnings("unchecked")
3311         @Override
3312         public List<EPRole> getGlobalRolesOfPortal() {
3313                 List<EPRole> globalRoles = new ArrayList<>();
3314                 try {
3315                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3316                 } catch (Exception e) {
3317                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3318                 }
3319                 return globalRoles;
3320         }
3321
3322         private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3323                 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3324                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3325                                 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3326         }
3327
3328         @Override
3329         public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
3330                         List<CentralV2RoleFunction> answer) {
3331                 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3332                 for (CentralV2RoleFunction cenRoleFunc : answer) {
3333                         CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3334                         setRoleFunc.setCode(cenRoleFunc.getCode());
3335                         setRoleFunc.setName(cenRoleFunc.getName());
3336                         addRoleFuncList.add(setRoleFunc);
3337                 }
3338                 return addRoleFuncList;
3339         }
3340
3341         @Override
3342         public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3343                 CentralUser sendUserRoles = null;
3344                 try {
3345                         CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3346                         sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3347                 } catch (Exception e) {
3348                         logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3349                         throw e;
3350                 }
3351                 return sendUserRoles;
3352         }
3353
3354         /**
3355          * 
3356          * It returns V2 CentralUser object if user has any roles and permissions
3357          * 
3358          * @param loginId
3359          * @param uebkey
3360          * @return CentralUser object
3361          * @throws Exception
3362          */
3363         private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3364                 EPApp app;
3365                 List<EPUser> epUserList;
3366                 List<EPApp> appList = getApp(uebkey);
3367                 app = appList.get(0);
3368                 epUserList = getUser(loginId);
3369                 EPUser user = epUserList.get(0);
3370                 Set<EPUserApp> userAppSet = user.getEPUserApps();
3371                 return createEPUser(user, userAppSet, app);
3372         }
3373
3374         private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) {
3375                 final Map<String, Long> userParams = new HashMap<>();
3376                 userParams.put("appId", app.getId());
3377                 userParams.put("userId", user.getId());
3378                 @SuppressWarnings("unchecked")
3379                 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles",
3380                                 userParams, null);
3381                 List<EcompRole> setUserRoles = new ArrayList<>();
3382                 for (EPUserAppCurrentRoles role : userAppsRolesList) {
3383                         logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
3384                                         role.getRoleName());
3385                         EcompRole ecompRole = new EcompRole();
3386                         ecompRole.setId(role.getRoleId());
3387                         ecompRole.setName(role.getRoleName());
3388                         setUserRoles.add(ecompRole);
3389                 }
3390                 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
3391                                 setUserRoles.size());
3392                 return setUserRoles;
3393         }
3394
3395         @Override
3396         public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
3397                         throws Exception {
3398                 List<EPApp> appList = getApp(uebkey);
3399                 EPApp app = appList.get(0);
3400                 List<EPUser> epUserList;
3401                 epUserList = getUser(loginId);
3402                 List<EcompRole> missingUserAppRoles = new ArrayList<>();
3403                 List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
3404                 logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
3405                 List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
3406                 if (userApplicationsRolesfromDB.size() > 0) {
3407                         missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
3408                                         .collect(Collectors.toList());
3409                 }
3410                 List<String> MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
3411                                 .collect(Collectors.toList());
3412                 logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList);
3413
3414                 List<EcompRole> finalMissingRoleList = new ArrayList<>();
3415                 if (missingUserAppRoles.size() > 0) {
3416                         final Map<String, Long> params = new HashMap<>();
3417                         for (EcompRole role : missingUserAppRoles) {
3418                                 params.put("roleId", role.getId());
3419                                 params.put(APP_ID, app.getId());
3420
3421                                 EcompRole epRole = new EcompRole();
3422                                 epRole.setId(role.getId());
3423                                 epRole.setName(role.getName());
3424                                 @SuppressWarnings("unchecked")
3425                                 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
3426                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
3427                                 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3428                                 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
3429                                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
3430                                         String type = getFunctionCodeType(roleFunc.getCode());
3431                                         String action = getFunctionCodeAction(roleFunc.getCode());
3432                                         EcompRoleFunction fun = new EcompRoleFunction();
3433                                         fun.setAction(action);
3434                                         fun.setCode(functionCode);
3435                                         fun.setType(type);
3436                                         fun.setName(roleFunc.getName());
3437                                         roleFunctionSet.add(fun);
3438
3439                                 }
3440                                 epRole.setRoleFunctions(roleFunctionSet);
3441                                 finalMissingRoleList.add(epRole);
3442                         }
3443                 }
3444
3445                 return finalMissingRoleList;
3446         }
3447
3448         /**
3449          * It converts V2 CentralUser object to old version CentralUser object
3450          * 
3451          * @param cenV2User
3452          * @return EPUser object
3453          */
3454         private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3455                 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3456                 Set<CentralUserApp> userApps = new TreeSet<>();
3457                 for (CentralV2UserApp userApp : userV2Apps) {
3458                         CentralApp app = userApp.getApp();
3459                         CentralUserApp cua = new CentralUserApp();
3460                         cua.setUserId(null);
3461                         cua.setApp(app);
3462                         SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3463                         for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) {
3464                                 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(),
3465                                                 cenV2RoleFunc.getName());
3466                                 cenRoleFunction.add(cenRoleFunc);
3467                         }
3468                         CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
3469                                         userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction);
3470                         cua.setRole(role);
3471                         userApps.add(cua);
3472                 }
3473         return new CentralUser.CentralUserBuilder().setId(cenV2User.getId()).setCreated(cenV2User.getCreated())
3474                 .setModified(cenV2User.getModified()).setCreatedId(cenV2User.getCreatedId())
3475                 .setModifiedId(cenV2User.getModifiedId()).setRowNum(cenV2User.getRowNum())
3476                 .setOrgId(cenV2User.getOrgId()).setManagerId(cenV2User.getManagerId())
3477                 .setFirstName(cenV2User.getFirstName()).setMiddleInitial(cenV2User.getMiddleInitial())
3478                 .setLastName(cenV2User.getLastName()).setPhone(cenV2User.getPhone()).setFax(cenV2User.getFax())
3479                 .setCellular(cenV2User.getCellular()).setEmail(cenV2User.getEmail())
3480                 .setAddressId(cenV2User.getAddressId()).setAlertMethodCd(cenV2User.getAlertMethodCd())
3481                 .setHrid(cenV2User.getHrid()).setOrgUserId(cenV2User.getOrgUserId()).setOrgCode(cenV2User.getOrgCode())
3482                 .setAddress1(cenV2User.getAddress1()).setAddress2(cenV2User.getAddress2()).setCity(cenV2User.getCity())
3483                 .setState(cenV2User.getState()).setZipCode(cenV2User.getZipCode()).setCountry(cenV2User.getCountry())
3484                 .setOrgManagerUserId(cenV2User.getOrgManagerUserId()).setLocationClli(cenV2User.getLocationClli())
3485                 .setBusinessCountryCode(cenV2User.getBusinessCountryCode())
3486                 .setBusinessCountryName(cenV2User.getBusinessCountryName()).setBusinessUnit(cenV2User.getBusinessUnit())
3487                 .setBusinessUnitName(cenV2User.getBusinessUnitName()).setDepartment(cenV2User.getDepartment())
3488                 .setDepartmentName(cenV2User.getDepartmentName()).setCompanyCode(cenV2User.getCompanyCode())
3489                 .setCompany(cenV2User.getCompany()).setZipCodeSuffix(cenV2User.getZipCodeSuffix())
3490                 .setJobTitle(cenV2User.getJobTitle()).setCommandChain(cenV2User.getCommandChain())
3491                 .setSiloStatus(cenV2User.getSiloStatus()).setCostCenter(cenV2User.getCostCenter())
3492                 .setFinancialLocCode(cenV2User.getFinancialLocCode()).setLoginId(cenV2User.getLoginId())
3493                 .setLoginPwd(cenV2User.getLoginPwd()).setLastLoginDate(cenV2User.getLastLoginDate())
3494                 .setActive(cenV2User.isActive()).setInternal(cenV2User.isInternal())
3495                 .setSelectedProfileId(cenV2User.getSelectedProfileId()).setTimeZoneId(cenV2User.getTimeZoneId())
3496                 .setOnline(cenV2User.isOnline()).setChatId(cenV2User.getChatId()).setUserApps(userApps)
3497                 .createCentralUser();
3498         }
3499
3500         @Override
3501         public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3502                 List<CentralRole> cenRoleList = new ArrayList<>();
3503                 for (CentralV2Role v2CenRole : v2CenRoleList) {
3504                         SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3505                         for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3506                                 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(),
3507                                                 v2CenRoleFunc.getName());
3508                                 cenRoleFuncList.add(roleFunc);
3509                         }
3510                         CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(),
3511                                         v2CenRole.getPriority(), cenRoleFuncList);
3512                         cenRoleList.add(role);
3513                 }
3514                 return cenRoleList;
3515         }
3516
3517         @Override
3518         public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3519                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3520                 HttpEntity<String> entity = new HttpEntity<>(headers);
3521                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3522                 ResponseEntity<String> response = null;
3523                 try {
3524                         response = template
3525                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3526                                                         + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3527                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3528                                         response.getStatusCode().value());
3529                 } catch (HttpClientErrorException e) {
3530                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3531                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3532                         if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3533                                 throw new InvalidApplicationException("Invalid NameSpace");
3534                         else
3535                                 throw e;
3536                 }
3537                 return response;
3538         }
3539
3540         @Override
3541         public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3542                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3543                 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3544                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3545                         cenRoleFuncList.add(roleFunc);
3546                 }
3547                 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3548                                 cenRoleFuncList);
3549         }
3550
3551         @SuppressWarnings("unchecked")
3552         @Override
3553         public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3554                 EPApp app = getApp(uebkey).get(0);
3555                 final Map<String, String> params = new HashMap<>();
3556                 params.put("uebKey", app.getUebKey());
3557                 params.put("roleId", String.valueOf(roleId));
3558                 List<BulkUploadUserRoles> userRolesList = null;
3559                 Integer userRolesAdded = 0;
3560                 if (app.getCentralAuth()) {
3561                         userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3562                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3563                                 userRolesUpload.setRoleName(modifiedRoleName);
3564                                 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
3565                                         addUserRoleInExternalSystem(userRolesUpload);
3566                                         userRolesAdded++;
3567                                 }
3568                         }
3569                 }
3570                 return userRolesAdded;
3571         }
3572
3573         @Override
3574         public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3575                 ObjectMapper mapper = new ObjectMapper();
3576                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3577                 try {
3578                         ExternalAccessRolePerms extRolePerms;
3579                         ExternalAccessPerms extPerms;
3580                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(),
3581                                         EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction());
3582                         String appNameSpace = "";
3583                         if (data.getIsGlobalRolePartnerFunc()) {
3584                                 appNameSpace = epAppService.getApp(1l).getNameSpace();
3585                         } else {
3586                                 appNameSpace = app.getNameSpace();
3587                         }
3588                         extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
3589                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3590                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3591                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3592                         updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3593                 } catch (HttpClientErrorException e) {
3594                         logger.error(EELFLoggerDelegate.errorLogger,
3595                                         "HttpClientErrorException - Failed to add role function in external central auth system", e);
3596                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3597                         throw e;
3598                 } catch (Exception e) {
3599                         logger.error(EELFLoggerDelegate.errorLogger,
3600                                         "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3601                         throw e;
3602                 }
3603         }
3604
3605         private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3606                 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3607                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3608                 ResponseEntity<String> addPermResponse = template.exchange(
3609                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3610                                 HttpMethod.POST, entity, String.class);
3611                 logger.debug(EELFLoggerDelegate.debugLogger,
3612                                 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3613                                 addPermResponse.getStatusCode().value(), updateRolePerms);
3614         }
3615
3616         @Override
3617         public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3618                 String name = "";
3619                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3620                         name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3621                 }
3622                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3623                 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3624                 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3625                 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3626                 String res = getResponse.getBody();
3627                 JSONObject jsonObj = null;
3628                 JSONArray extRoles = null;
3629                 if (!res.equals("{}")) {
3630                         jsonObj = new JSONObject(res);
3631                         extRoles = jsonObj.getJSONArray("role");
3632                 }
3633                 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3634         }
3635
3636         @SuppressWarnings("unchecked")
3637         private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3638                         String loginId) throws InvalidUserException {
3639                 HashMap<String, String> userParams = new HashMap<>();
3640                 userParams.put("orgUserId", loginId);
3641                 // Get all centralized applications existing user roles from local
3642                 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3643                                 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3644                 EPUser user = getUser(loginId).get(0);
3645                 // Get all centralized applications roles from local
3646                 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3647                 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3648                                 currentUserAppRoles);
3649                 // Get all centralized applications + admin role from local
3650                 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3651                 if (extRoles != null) {
3652                         ExternalAccessUserRoleDetail userRoleDetail = null;
3653                         for (int i = 0; i < extRoles.length(); i++) {
3654                                 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3655                                                 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3656                                         userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3657                                                         null);
3658                                         userRoleDetailList.add(userRoleDetail);
3659                                 }
3660                         }
3661                         addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3662                                         centralisedAppsMap);
3663                 }
3664         }
3665
3666         private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3667                         HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3668                         HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3669                         HashMap<String, EPApp> centralisedAppsMap) {
3670                 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3671                         try {
3672                                 // check if user already has role in local
3673                                 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3674                                         CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3675                                         if (getCenAppRole != null) {
3676                                                 logger.debug(EELFLoggerDelegate.debugLogger,
3677                                                                 "addUserRolesInLocal: Adding user role from external auth system  {}",
3678                                                                 extUserRoleDetail.toString());
3679                                                 EPUserApp userApp = new EPUserApp();
3680                                                 EPApp app = new EPApp();
3681                                                 app.setId(getCenAppRole.getAppId());
3682                                                 EPRole epRole = new EPRole();
3683                                                 epRole.setId(getCenAppRole.getRoleId());
3684                                                 userApp.setApp(app);
3685                                                 userApp.setUserId(user.getId());
3686                                                 userApp.setRole(epRole);
3687                                                 dataAccessService.saveDomainObject(userApp, null);
3688                                                 logger.debug(EELFLoggerDelegate.debugLogger,
3689                                                                 "addUserRolesInLocal: Finished user role from external auth system  {}",
3690                                                                 extUserRoleDetail.toString());
3691                                         } else if (getCenAppRole == null // check if user has app
3692                                                                                                                 // account admin role
3693                                                         && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3694                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3695                                                 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3696                                                 if (app != null) {
3697                                                         logger.debug(EELFLoggerDelegate.debugLogger,
3698                                                                         "addUserRolesInLocal: Adding user role from external auth system  {}",
3699                                                                         extUserRoleDetail.toString());
3700                                                         EPUserApp userApp = new EPUserApp();
3701                                                         EPRole epRole = new EPRole();
3702                                                         epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3703                                                         userApp.setApp(app);
3704                                                         userApp.setUserId(user.getId());
3705                                                         userApp.setRole(epRole);
3706                                                         dataAccessService.saveDomainObject(userApp, null);
3707                                                         logger.debug(EELFLoggerDelegate.debugLogger,
3708                                                                         "addUserRolesInLocal: Finished user role from external auth system  {}",
3709                                                                         extUserRoleDetail.toString());
3710                                                 }
3711                                         }
3712                                 }
3713                         } catch (Exception e) {
3714                                 logger.error(EELFLoggerDelegate.errorLogger,
3715                                                 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3716                                                 extUserRoleDetail.toString(), e);
3717                         }
3718                 }
3719         }
3720
3721         @SuppressWarnings("unchecked")
3722         private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3723                 List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
3724                 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3725                 for (EPApp cenApp : centralizedApps) {
3726                         centralisedAppsMap.put(
3727                                         cenApp.getNameSpace() + "."
3728                                                         + PortalConstants.ADMIN_ROLE.replaceAll(
3729                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3730                                         cenApp);
3731                 }
3732                 return centralisedAppsMap;
3733         }
3734
3735         private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3736                         List<CentralizedAppRoles> currentUserAppRoles) {
3737                 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3738                 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3739                         currentCentralizedUserAppRolesMap.put(
3740                                         cenAppUserRole.getAppNameSpace() + "."
3741                                                         + cenAppUserRole.getRoleName().replaceAll(
3742                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3743                                         cenAppUserRole);
3744                 }
3745                 return currentCentralizedUserAppRolesMap;
3746         }
3747
3748         @SuppressWarnings("unchecked")
3749         private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3750                 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3751                                 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3752                 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3753                 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3754                         cenAppRolesMap.put(
3755                                         CentralizedAppRole.getAppNameSpace() + "."
3756                                                         + CentralizedAppRole.getRoleName().replaceAll(
3757                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3758                                         CentralizedAppRole);
3759                 }
3760                 return cenAppRolesMap;
3761         }
3762
3763         @Override
3764         public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3765                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3766                 ResponseEntity<String> getResponse = template
3767                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3768                                                 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3769                 if (getResponse.getStatusCode().value() == 200) {
3770                         logger.debug(EELFLoggerDelegate.debugLogger,
3771                                         "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3772                                         getResponse.getBody());
3773                 } else {
3774                         logger.error(EELFLoggerDelegate.errorLogger,
3775                                         "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
3776                                         getResponse.getBody());
3777                         EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
3778                 }
3779                 return getResponse;
3780         }
3781
3782         @Override
3783         public Integer updateAppRoleDescription(String uebkey) {
3784                 Integer roleDescUpdated = 0;
3785                 EPApp app;
3786                 try {
3787                         app = getApp(uebkey).get(0);
3788                         List<EPRole> roles = getAppRoles(app.getId());
3789                         for (EPRole epRole : roles) {
3790                                 Role role = new Role();
3791                                 role.setName(epRole.getName());
3792                                 boolean status = addRoleDescriptionInExtSystem(role, app);
3793                                 if (status)
3794                                         roleDescUpdated++;
3795                         }
3796                 } catch (Exception e) {
3797                         logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
3798                 }
3799                 return roleDescUpdated;
3800         }
3801
3802 }