d5a873a23578a87e66159fc0e80b9df2e70bc5a0
[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         @SuppressWarnings("unchecked")
1312         private List<EPRole> getPortalAppRoleInfo(Long roleId) {
1313                 List<EPRole> roleInfo;
1314                 final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
1315                 getPortalAppRoleParams.put("roleId", roleId);
1316                 roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
1317                 return roleInfo;
1318         }
1319
1320         /**
1321          * 
1322          * It returns list of app roles along with role functions and which went through
1323          * deep copy
1324          * 
1325          * @param app
1326          * @param roleInfo
1327          * @param roleList
1328          * @param params
1329          * @return
1330          * @throws DecoderException
1331          */
1332         @SuppressWarnings("unchecked")
1333         @Override
1334         public List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
1335                         List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
1336                 for (EPRole role : roleInfo) {
1337                         params.put("roleId", role.getId());
1338                         params.put(APP_ID, app.get(0).getId());
1339                         List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
1340                                         params, null);
1341                         SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
1342                         for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
1343                                 String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
1344                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1345                                 String type = getFunctionCodeType(roleFunc.getCode());
1346                                 String action = getFunctionCodeAction(roleFunc.getCode());
1347                                 CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
1348                                                 roleFunc.getName(), null, type, action, null);
1349                                 roleFunctionSet.add(cenRoleFunc);
1350                         }
1351                         SortedSet<CentralV2Role> childRoles = new TreeSet<>();
1352                         SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
1353                         CentralV2Role cenRole = null;
1354                         if (role.getAppRoleId() == null) {
1355                                 cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
1356                                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
1357                                                 roleFunctionSet, childRoles, parentRoles);
1358                         } else {
1359                                 cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
1360                                                 role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
1361                                                 role.getPriority(), roleFunctionSet, childRoles, parentRoles);
1362                         }
1363                         roleList.add(cenRole);
1364                 }
1365                 return roleList;
1366         }
1367
1368         @SuppressWarnings("unchecked")
1369         @Override
1370         public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
1371                 String code = EcompPortalUtils.getFunctionCode(functionCode);
1372                 String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
1373                 CentralV2RoleFunction roleFunc = null;
1374                 EPApp app = getApp(uebkey).get(0);
1375                 List<CentralV2RoleFunction> getRoleFuncList = null;
1376                 final Map<String, String> params = new HashMap<>();
1377                 try {
1378                         params.put(FUNCTION_CODE_PARAMS, functionCode);
1379                         params.put(APP_ID, String.valueOf(app.getId()));
1380                         getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1381                         if (getRoleFuncList.isEmpty()) {
1382                                 params.put(FUNCTION_CODE_PARAMS, encodedCode);
1383                                 getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1384                                 if (getRoleFuncList.isEmpty()) {
1385                                         return roleFunc;
1386                                 }
1387                         }
1388                         if (getRoleFuncList.size() > 1) {
1389                                 CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
1390                                 if (cenV2RoleFunction == null)
1391                                         return roleFunc;
1392                                 roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
1393                         } else {
1394                                 // Check even if single record have pipes
1395                                 if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
1396                                         roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
1397                                 } else {
1398                                         roleFunc = getRoleFuncList.get(0);
1399                                 }
1400                         }
1401                 } catch (Exception e) {
1402                         logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
1403                         throw e;
1404                 }
1405                 return roleFunc;
1406         }
1407
1408         private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
1409                 CentralV2RoleFunction roleFunc;
1410                 String functionCodeFormat = getRoleFuncList.getCode();
1411                 if (functionCodeFormat.contains(FUNCTION_PIPE)) {
1412                         String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
1413                         String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
1414                         String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
1415                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
1416                                         getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
1417                                         newfunctionActionFormat, getRoleFuncList.getEditUrl());
1418                 } else {
1419                         roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat, getRoleFuncList.getName(),
1420                                         getRoleFuncList.getAppId(), getRoleFuncList.getEditUrl());
1421                 }
1422                 return roleFunc;
1423         }
1424
1425         @Override
1426         public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1427                         throws Exception {
1428                 boolean saveOrUpdateFunction = false;
1429                 try {
1430                         if(EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getCode()))
1431                          domainCentralRoleFunction.setCode(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getCode()));
1432                         final Map<String, String> functionParams = new HashMap<>();
1433                         functionParams.put("appId", String.valueOf(app.getId()));
1434                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1435                                 addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
1436                         }
1437                         if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
1438                                 domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType() + FUNCTION_PIPE
1439                                                 + domainCentralRoleFunction.getCode() + FUNCTION_PIPE + domainCentralRoleFunction.getAction());
1440                         }
1441                         domainCentralRoleFunction.setAppId(app.getId());
1442                         dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
1443                         saveOrUpdateFunction = true;
1444                 } catch (Exception e) {
1445                         logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
1446                         throw e;
1447                 }
1448                 return saveOrUpdateFunction;
1449         }
1450
1451         /**
1452          * It creates application permission in external auth system
1453          * 
1454          * @param domainCentralRoleFunction
1455          * @param app
1456          * @throws Exception
1457          */
1458         private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1459                         throws Exception {
1460                 ObjectMapper mapper = new ObjectMapper();
1461                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
1462                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1463                 String type = "";
1464                 String instance = "";
1465                 String action = "";
1466                 if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
1467                                 || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)) {
1468                         type = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1469                                         ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode())
1470                                         : domainCentralRoleFunction.getType();
1471                         instance = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1472                                         ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode())
1473                                         : domainCentralRoleFunction.getCode();
1474                         action = domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)
1475                                         ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode())
1476                                         : domainCentralRoleFunction.getAction();
1477                 } else {
1478                         type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
1479                         instance = domainCentralRoleFunction.getCode();
1480                         action = "*";
1481                 }
1482                 // get Permissions from External Auth System
1483                 JSONArray extPermsList = getExtAuthPermissions(app);
1484                 List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
1485                 String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
1486                 boolean checkIfFunctionsExits = permsDetailList.stream()
1487                                 .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
1488                 if (!checkIfFunctionsExits) {
1489                         try {
1490                                 extPerms.setAction(action);
1491                                 extPerms.setInstance(instance);
1492                                 extPerms.setType(app.getNameSpace() + "." + type);
1493                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1494                                 String addFunction = mapper.writeValueAsString(extPerms);
1495                                 HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
1496                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
1497                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
1498                                 ResponseEntity<String> addPermResponse = template.exchange(
1499                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1500                                                 HttpMethod.POST, entity, String.class);
1501                                 logger.debug(EELFLoggerDelegate.debugLogger,
1502                                                 "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
1503                                                 addPermResponse.getStatusCode().value(), addFunction);
1504                         } catch (HttpClientErrorException e) {
1505                                 logger.error(EELFLoggerDelegate.errorLogger,
1506                                                 "HttpClientErrorException - Failed to add function in external central auth system", e);
1507                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1508                                 throw e;
1509                         } catch (Exception e) {
1510                                 logger.error(EELFLoggerDelegate.errorLogger,
1511                                                 "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
1512                                 throw e;
1513                         }
1514                 } else {
1515                         try {
1516                                 extPerms.setAction(action);
1517                                 extPerms.setInstance(instance);
1518                                 extPerms.setType(app.getNameSpace() + "." + type);
1519                                 extPerms.setDescription(domainCentralRoleFunction.getName());
1520                                 String updateRoleFunction = mapper.writeValueAsString(extPerms);
1521                                 HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
1522                                 logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
1523                                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
1524                                 ResponseEntity<String> updatePermResponse = template.exchange(
1525                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
1526                                                 HttpMethod.PUT, entity, String.class);
1527                                 logger.debug(EELFLoggerDelegate.debugLogger,
1528                                                 "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
1529                                                 updateRoleFunction, updatePermResponse.getStatusCode().value());
1530                         } catch (HttpClientErrorException e) {
1531                                 logger.error(EELFLoggerDelegate.errorLogger,
1532                                                 "HttpClientErrorException - Failed to add function in external central auth system", e);
1533                                 EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1534                                 throw e;
1535                         } catch (Exception e) {
1536                                 logger.error(EELFLoggerDelegate.errorLogger,
1537                                                 "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
1538                                                 e);
1539                                 throw e;
1540                         }
1541                 }
1542         }
1543
1544         @SuppressWarnings("unchecked")
1545         @Override
1546         @Transactional(rollbackFor = Exception.class)
1547         public boolean deleteCentralRoleFunction(String code, EPApp app) {
1548                 boolean deleteFunctionResponse = false;
1549                 try {
1550                         final Map<String, String> params = new HashMap<>();
1551                         params.put(FUNCTION_CODE_PARAMS, code);
1552                         params.put(APP_ID, String.valueOf(app.getId()));
1553                         List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
1554                                         .executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
1555                         CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
1556                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1557                                 deleteRoleFunctionInExternalSystem(appFunctionCode, app);
1558                                 // Delete role function dependency records
1559                                 deleteAppRoleFunctions(appFunctionCode.getCode(), app);
1560                         }
1561                         dataAccessService.deleteDomainObject(appFunctionCode, null);
1562                         deleteFunctionResponse = true;
1563                 } catch (Exception e) {
1564                         logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
1565                 }
1566                 return deleteFunctionResponse;
1567         }
1568
1569         /**
1570          * It deletes app function record in portal
1571          * 
1572          * @param code
1573          * @param app
1574          */
1575         private void deleteAppRoleFunctions(String code, EPApp app) {
1576                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1577                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
1578         }
1579
1580         /**
1581          * 
1582          * It deletes permission in the external auth system
1583          * 
1584          * @param domainCentralRoleFunction
1585          * @param app
1586          * @throws Exception
1587          */
1588         private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
1589                         throws Exception {
1590                 try {
1591                         ObjectMapper mapper = new ObjectMapper();
1592                         ExternalAccessPerms extPerms = new ExternalAccessPerms();
1593                         String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
1594                         String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
1595                         String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
1596                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1597                         extPerms.setAction(actionValue);
1598                         extPerms.setInstance(instanceValue);
1599                         extPerms.setType(app.getNameSpace() + "." + checkType);
1600                         extPerms.setDescription(domainCentralRoleFunction.getName());
1601                         String deleteRoleFunction = mapper.writeValueAsString(extPerms);
1602                         HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
1603                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
1604                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
1605                         ResponseEntity<String> delPermResponse = template
1606                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1607                                                         + "perm?force=true", HttpMethod.DELETE, entity, String.class);
1608                         logger.debug(EELFLoggerDelegate.debugLogger,
1609                                         "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
1610                                         deleteRoleFunction, delPermResponse.getStatusCode().value());
1611                 } catch (HttpClientErrorException e) {
1612                         logger.error(EELFLoggerDelegate.errorLogger,
1613                                         "HttpClientErrorException - Failed to delete functions in External System", e);
1614                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1615                 } catch (Exception e) {
1616                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1617                                 logger.debug(EELFLoggerDelegate.debugLogger,
1618                                                 " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
1619                                                 e.getMessage());
1620                         } else {
1621                                 logger.error(EELFLoggerDelegate.errorLogger,
1622                                                 "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
1623                         }
1624                 }
1625         }
1626
1627         @Override
1628         public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
1629                 boolean response = false;
1630                 String message = "";
1631                 try {
1632                         EPApp app = getApp(uebkey).get(0);
1633                         addRoleInEcompDB(saveRole, app);
1634                         response = true;
1635                 } catch (Exception e) {
1636                         message = e.getMessage();
1637                         logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
1638                 }
1639                 return new ExternalRequestFieldsValidator(response, message);
1640         }
1641
1642         @SuppressWarnings("unchecked")
1643         @Override
1644         public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
1645                 Session localSession = sessionFactory.openSession();
1646                 Transaction transaction = null;
1647                 boolean result = false;
1648                 try {
1649                         List<EPRole> epRoleList = null;
1650                         EPApp app = getApp(uebkey).get(0);
1651                         final Map<String, String> deleteRoleParams = new HashMap<>();
1652                         deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
1653                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1654                                 epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
1655                         } else {
1656                                 deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
1657                                 epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
1658                                                 deleteRoleParams, null);
1659                         }
1660                         if (!epRoleList.isEmpty()) {
1661                                 transaction = localSession.beginTransaction();
1662                                 // Delete app role functions before deleting role
1663                                 deleteRoleFunction(app, epRoleList);
1664                                 if (app.getId() == 1) {
1665                                         // Delete fn_user_ role
1666                                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1667                                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1668                                         boolean isPortalRequest = false;
1669                                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1670                                 }
1671                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1672                                 transaction.commit();
1673                                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
1674                                 dataAccessService.deleteDomainObject(epRoleList.get(0), null);
1675                         }
1676                         result = true;
1677                 } catch (Exception e) {
1678                         logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
1679                         result = false;
1680                 } finally {
1681                         localSession.close();
1682                 }
1683                 return result;
1684         }
1685
1686         /**
1687          * 
1688          * It deletes role for application in external auth system
1689          * 
1690          * @param epRoleList contains role information
1691          * @param app        contains application information
1692          * @throws Exception
1693          */
1694         private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
1695                 ResponseEntity<String> deleteResponse;
1696                 ResponseEntity<String> res = getNameSpaceIfExists(app);
1697                 if (res.getStatusCode() == HttpStatus.OK) {
1698                         // Delete Role in External System
1699                         String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
1700                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
1701                         deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
1702                         if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
1703                                 EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
1704                                 logger.error(EELFLoggerDelegate.errorLogger,
1705                                                 "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
1706                                                 deleteResponse.getBody());
1707                         }
1708                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
1709                 }
1710         }
1711
1712         /**
1713          * 
1714          * It deletes application user role in external auth system
1715          * 
1716          * @param role
1717          * @param app
1718          * @param LoginId
1719          * @throws Exception
1720          */
1721         private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
1722                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1723                 HttpEntity<String> entity = new HttpEntity<>(headers);
1724                 getNameSpaceIfExists(app);
1725                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1726                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1727                 ResponseEntity<String> getResponse = template.exchange(
1728                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1729                                                 + LoginId
1730                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1731                                                 + "/" + app.getNameSpace() + "."
1732                                                 + role.getName()
1733                                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1734                                 HttpMethod.GET, entity, String.class);
1735                 logger.debug(EELFLoggerDelegate.debugLogger,
1736                                 "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
1737                                 getResponse.getBody());
1738                 if (getResponse.getStatusCode().value() != 200) {
1739                         throw new ExternalAuthSystemException(getResponse.getBody());
1740                 }
1741                 String res = getResponse.getBody();
1742                 if (!res.equals(IS_EMPTY_JSON_STRING)) {
1743                         HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
1744                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
1745                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
1746                         ResponseEntity<String> deleteResponse = template.exchange(
1747                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
1748                                                         + LoginId
1749                                                         + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
1750                                                         + "/" + app.getNameSpace() + "."
1751                                                         + role.getName().replaceAll(
1752                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
1753                                         HttpMethod.DELETE, userRoleentity, String.class);
1754                         if (deleteResponse.getStatusCode().value() != 200) {
1755                                 throw new ExternalAuthSystemException("Failed to delete user role");
1756                         }
1757                         logger.debug(EELFLoggerDelegate.debugLogger,
1758                                         "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
1759                                         deleteResponse.getStatusCode().value());
1760                 }
1761         }
1762
1763         @SuppressWarnings("unchecked")
1764         @Override
1765         public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
1766                 List<CentralV2Role> roleList = new ArrayList<>();
1767                 try {
1768                         List<EPApp> app = getApp(uebkey);
1769                         final Map<String, Long> params = new HashMap<>();
1770                         // check if portal
1771                         Long appId = null;
1772                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
1773                                 appId = app.get(0).getId();
1774                         }
1775                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
1776                         Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
1777                         Criterion appIdCrt;
1778                         if (appId == null)
1779                                 appIdCrt = Restrictions.isNull("appId");
1780                         else
1781                                 appIdCrt = Restrictions.eq("appId", appId);
1782                         Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
1783                         restrictionsList.add(andCrit);
1784                         List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
1785                         roleList = createCentralRoleObject(app, epRole, roleList, params);
1786                         List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
1787                         if (globalRoleList.size() > 0)
1788                                 roleList.addAll(globalRoleList);
1789                 } catch (Exception e) {
1790                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
1791                         throw e;
1792                 }
1793                 return roleList;
1794         }
1795
1796         @Override
1797         @Transactional(rollbackFor = Exception.class)
1798         public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
1799                         throws Exception {
1800                 Session localSession = sessionFactory.openSession();
1801                 String message = "";
1802                 Transaction transaction = null;
1803                 boolean response = false;
1804                 EPApp app = null;
1805                 try {
1806                         transaction = localSession.beginTransaction();
1807                         List<EPRole> epRoleList = null;
1808                         app = getApp(uebkey).get(0);
1809                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
1810                                 epRoleList = getPortalAppRoleInfo(roleId);
1811                         } else {
1812                                 epRoleList = getPartnerAppRoleInfo(roleId, app);
1813                         }
1814                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1815                                 // Delete User Role in External System before deleting role
1816                                 deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
1817                         }
1818                         // Delete user app roles
1819                         dataAccessService.deleteDomainObjects(EPUserApp.class,
1820                                         APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
1821                         boolean isPortalRequest = false;
1822                         deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
1823                         transaction.commit();
1824                         if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1825                                 // Final call to delete role once all dependencies has been
1826                                 // deleted
1827                                 deleteRoleInExternalAuthSystem(epRoleList, app);
1828                         }
1829                         dataAccessService.deleteDomainObjects(EPRole.class, " role_id = " + epRoleList.get(0).getId(), null);
1830                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
1831                         response = true;
1832                 } catch (HttpClientErrorException e) {
1833                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
1834                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
1835                         message = e.getMessage();
1836                 } catch (Exception e) {
1837                         logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
1838                         EcompPortalUtils.rollbackTransaction(transaction,
1839                                         "deleteDependencyRoleRecord rollback, exception = " + e.toString());
1840                         message = e.getMessage();
1841                 } finally {
1842                         localSession.close();
1843                 }
1844                 return new ExternalRequestFieldsValidator(response, message);
1845         }
1846
1847         @Override
1848         @SuppressWarnings("unchecked")
1849         @Transactional
1850         public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
1851                 try {
1852                         // get Permissions from External Auth System
1853                         JSONArray extPerms = getExtAuthPermissions(app);
1854                         List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
1855                         // get functions in DB
1856                         final Map<String, Long> params = new HashMap<>();
1857                         final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
1858                         params.put(APP_ID, app.getId());
1859                         List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions",
1860                                         params, null);
1861                         if (!appFunctions.isEmpty()) {
1862                                 for (CentralV2RoleFunction roleFunc : appFunctions) {
1863                                         roleFuncMap.put(roleFunc.getCode(), roleFunc);
1864                                 }
1865                         }
1866                         // get Roles for portal in DB
1867                         List<EPRole> portalRoleList = getGlobalRolesOfPortal();
1868                         final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
1869                         for (EPRole epRole : portalRoleList) {
1870                                 existingPortalRolesMap.put(epRole.getName().replaceAll(
1871                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
1872                         }
1873                         // get Roles in DB
1874                         final Map<String, EPRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
1875                         // store External Permissions with Pipe and without Pipe (just
1876                         // instance)
1877                         final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
1878                         final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
1879                         for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
1880                                 extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
1881                                 String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
1882                                 extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
1883                         }
1884                         // Add if new functions and app role functions were added in
1885                         // external auth system
1886                         for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
1887                                 String code = permsDetail.getInstance();
1888                                 CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
1889                                 List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
1890                                                 getFunctionCodeKey);
1891                                 List<String> roles = permsDetail.getRoles();
1892                                 if (roles != null) {
1893                                         // Check if function has any roles and which does not exist
1894                                         // in External Auth System. If exists delete in local
1895                                         addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
1896                                                         existingPortalRolesMap);
1897                                 }
1898                         }
1899                         // Check if function does exits in External Auth System but exits in
1900                         // local then delete function and its dependencies
1901                         for (CentralV2RoleFunction roleFunc : appFunctions) {
1902                                 try {
1903                                         ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
1904                                                         .get(roleFunc.getCode());
1905                                         if (null == getFunctionCodeContainsPipeKey) {
1906                                                 ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
1907                                                 if (null == getFunctionCodeKey) {
1908                                                         deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
1909                                                 }
1910                                         }
1911                                 } catch (Exception e) {
1912                                         logger.error(EELFLoggerDelegate.errorLogger,
1913                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
1914                                 }
1915                         }
1916                         logger.debug(EELFLoggerDelegate.debugLogger,
1917                                         "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
1918                 } catch (Exception e) {
1919                         logger.error(EELFLoggerDelegate.errorLogger,
1920                                         "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
1921                 }
1922         }
1923
1924         @SuppressWarnings("unchecked")
1925         private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
1926                         List<CentralV2RoleFunction> roleFunctionList, List<String> roles,
1927                         Map<String, EPRole> existingPortalRolesMap) throws Exception {
1928                 if (!roleFunctionList.isEmpty()) {
1929                         final Map<String, String> appRoleFuncParams = new HashMap<>();
1930                         final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
1931                         final Map<String, String> currentRolesInExtSystem = new HashMap<>();
1932                         appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
1933                         appRoleFuncParams.put("appId", String.valueOf(app.getId()));
1934                         List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
1935                                         appRoleFuncParams, null);
1936                         for (LocalRole localRole : localRoleList) {
1937                                 currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
1938                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
1939                         }
1940                         for (String addRole : roles) {
1941                                 currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
1942                         }
1943                         for (String extAuthrole : roles) {
1944                                 String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
1945                                 boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
1946                                                 app.getNameSpace());
1947                                 if (isNameSpaceMatching) {
1948                                         if (!currentAppRoleFunctionsMap
1949                                                         .containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
1950                                                 EPRole localAddFuntionRole = currentRolesInDB
1951                                                                 .get(extAuthrole.substring(app.getNameSpace().length() + 1));
1952                                                 if (localAddFuntionRole == null) {
1953                                                         checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
1954                                                 } else {
1955                                                         EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
1956                                                         addAppRoleFunc.setAppId(app.getId());
1957                                                         addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
1958                                                         addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
1959                                                         dataAccessService.saveDomainObject(addAppRoleFunc, null);
1960                                                 }
1961                                         }
1962                                         // This block is to save global role function if exists
1963                                 } else {
1964                                         String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
1965                                         boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
1966                                         if (checkIfGlobalRoleExists) {
1967                                                 final Map<String, Long> params = new HashMap<>();
1968                                                 EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
1969                                                 EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
1970                                                 params.put("appId", app.getId());
1971                                                 params.put("roleId", role.getId());
1972                                                 List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService
1973                                                                 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);
1974                                                 boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
1975                                                                 .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode()
1976                                                                                 .equals(roleFunctionList.get(0).getCode()));
1977                                                 if (role != null && !checkIfRoleFunctionExists) {
1978                                                         addGlobalRoleFunctions.setAppId(app.getId());
1979                                                         addGlobalRoleFunctions.setRoleId(role.getId());
1980                                                         if (!app.getId().equals(role.getAppRoleId())) {
1981                                                                 addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
1982                                                         } else {
1983                                                                 addGlobalRoleFunctions.setRoleAppId(null);
1984                                                         }
1985                                                         addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
1986                                                         dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
1987                                                 }
1988                                         }
1989                                 }
1990                         }
1991                         for (LocalRole localRoleDelete : localRoleList) {
1992                                 if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
1993                                                 .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
1994                                         dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
1995                                                         APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
1996                                                                         + "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
1997                                                         null);
1998                                 }
1999                         }
2000                 }
2001         }
2002
2003         private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
2004                 logger.debug(EELFLoggerDelegate.debugLogger,
2005                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc.getCode());
2006                 dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
2007                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2008                 logger.debug(EELFLoggerDelegate.debugLogger,
2009                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc.getCode());
2010                 logger.debug(EELFLoggerDelegate.debugLogger,
2011                                 "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc.getCode());
2012                 dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
2013                                 APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() + "'", null);
2014                 logger.debug(EELFLoggerDelegate.debugLogger,
2015                                 "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc.getCode());
2016         }
2017
2018         private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
2019                         List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
2020                 if (!currentRolesInDB.containsKey(roleList.substring(app.getNameSpace().length() + 1))) {
2021                         Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1));
2022                         addRoleDescriptionInExtSystem(role, app);
2023                         if (!roleFunctionList.isEmpty()) {
2024                                 try {
2025                                         if (!roleFunctionList.isEmpty()) {
2026                                                 EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
2027                                                 addAppRoleFunc.setAppId(app.getId());
2028                                                 addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
2029                                                 addAppRoleFunc.setRoleId(role.getId());
2030                                                 dataAccessService.saveDomainObject(addAppRoleFunc, null);
2031                                         }
2032                                 } catch (Exception e) {
2033                                         logger.error(EELFLoggerDelegate.errorLogger,
2034                                                         "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
2035                                 }
2036                         }
2037                 }
2038         }
2039
2040         @SuppressWarnings("unchecked")
2041         private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app,
2042                         final Map<String, CentralV2RoleFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
2043                         CentralV2RoleFunction getFunctionCodeKey) {
2044                 String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
2045                                 getFunctionCodeKey);
2046                 final Map<String, String> appSyncFuncsParams = new HashMap<>();
2047                 appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
2048                 appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
2049                 List<CentralV2RoleFunction> roleFunctionList = null;
2050                 roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2051                                 null);
2052                 if (roleFunctionList.isEmpty()) {
2053                         appSyncFuncsParams.put("functionCd", code);
2054                         roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
2055                                         null);
2056                 }
2057                 return roleFunctionList;
2058         }
2059
2060         private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
2061                         ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
2062                 String finalFunctionCodeVal = "";
2063                 if (null == getFunctionCodeKey) {
2064                         finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
2065                         CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
2066                         // If function does not exist in local then add!
2067                         if (null == checkIfCodeStillExits) {
2068                                 logger.debug(EELFLoggerDelegate.debugLogger,
2069                                                 "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
2070                                 addFunctionInEcompDB(app, permsDetail, code);
2071                                 logger.debug(EELFLoggerDelegate.debugLogger,
2072                                                 "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
2073                         }
2074                 }
2075                 return finalFunctionCodeVal;
2076         }
2077
2078         @SuppressWarnings("unchecked")
2079         @Override
2080         public Map<String, EPRole> getAppRoleNamesWithUnderscoreMap(EPApp app) {
2081                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2082                 List<EPRole> getCurrentRoleList = null;
2083                 final Map<String, Long> appParams = new HashMap<>();
2084                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2085                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2086                 } else {
2087                         appParams.put("appId", app.getId());
2088                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2089                 }
2090                 for (EPRole role : getCurrentRoleList) {
2091                         currentRolesInDB.put(role.getName()
2092                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
2093                 }
2094                 return currentRolesInDB;
2095         }
2096
2097         @SuppressWarnings("unchecked")
2098         private Map<String, EPRole> getAppRoleNamesMap(EPApp app) {
2099                 final Map<String, EPRole> currentRolesInDB = new HashMap<>();
2100                 List<EPRole> getCurrentRoleList = null;
2101                 final Map<String, Long> appParams = new HashMap<>();
2102                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2103                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
2104                 } else {
2105                         appParams.put("appId", app.getId());
2106                         getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
2107                 }
2108                 for (EPRole role : getCurrentRoleList) {
2109                         currentRolesInDB.put(role.getName(), role);
2110                 }
2111                 return currentRolesInDB;
2112         }
2113
2114         private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms) throws IOException {
2115                 ExternalAccessPermsDetail permDetails = null;
2116                 List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
2117                 for (int i = 0; i < extPerms.length(); i++) {
2118                         String description = null;
2119                         if (extPerms.getJSONObject(i).has("description")) {
2120                                 description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2121                         } else {
2122                                 description = extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + "|"
2123                                                 + extPerms.getJSONObject(i).getString("instance") + "|"
2124                                                 + extPerms.getJSONObject(i).getString("action");
2125                         }
2126                         if (extPerms.getJSONObject(i).has("roles")) {
2127                                 ObjectMapper rolesListMapper = new ObjectMapper();
2128                                 JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
2129                                 List<String> list = rolesListMapper.readValue(resRoles.toString(),
2130                                                 TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
2131                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2132                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2133                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2134                                                                 + extPerms.getJSONObject(i).getString("action"),
2135                                                 extPerms.getJSONObject(i).getString("action"), list, description);
2136                                 permsDetailList.add(permDetails);
2137                         } else {
2138                                 permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
2139                                                 extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
2140                                                                 + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
2141                                                                 + extPerms.getJSONObject(i).getString("action"),
2142                                                 extPerms.getJSONObject(i).getString("action"), description);
2143                                 permsDetailList.add(permDetails);
2144                         }
2145                 }
2146                 return permsDetailList;
2147         }
2148
2149         private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
2150                 ResponseEntity<String> response = null;
2151                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2152                 HttpEntity<String> entity = new HttpEntity<>(headers);
2153                 logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
2154                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2155                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2156                                 + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2157                 String res = response.getBody();
2158                 logger.debug(EELFLoggerDelegate.debugLogger,
2159                                 "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
2160                                 response.getBody());
2161                 JSONObject jsonObj = new JSONObject(res);
2162                 JSONArray extPerms = jsonObj.getJSONArray("perm");
2163                 for (int i = 0; i < extPerms.length(); i++) {
2164                         if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
2165                                 extPerms.remove(i);
2166                                 i--;
2167                         }
2168                 }
2169                 return extPerms;
2170         }
2171
2172         /**
2173          * 
2174          * Add function into local DB
2175          * 
2176          * @param app
2177          * @param permsDetail
2178          * @param code
2179          */
2180         private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
2181                 try {
2182                         CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
2183                         addFunction.setAppId(app.getId());
2184                         addFunction.setCode(code);
2185                         addFunction.setName(permsDetail.getDescription());
2186                         dataAccessService.saveDomainObject(addFunction, null);
2187                 } catch (Exception e) {
2188                         logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
2189                 }
2190         }
2191
2192         /**
2193          * 
2194          * It updates description of a role in external auth system
2195          * 
2196          * @param role
2197          * @param app
2198          * @throws Exception
2199          */
2200         private boolean addRoleDescriptionInExtSystem(Role role, EPApp app) throws Exception {
2201                 boolean status = false;
2202                 try {
2203                         String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2204                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2205                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2206                         template.exchange(
2207                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2208                                         HttpMethod.PUT, entity, String.class);
2209                         status = true;
2210                 } catch (HttpClientErrorException e) {
2211                         logger.error(EELFLoggerDelegate.errorLogger,
2212                                         "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
2213                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2214                 } catch (Exception e) {
2215                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
2216                 }
2217                 return status;
2218         }
2219
2220         /**
2221          * 
2222          * While sync functions form external auth system if new role found we should
2223          * add in local and return Role.class object
2224          * 
2225          * @param app
2226          * @param role
2227          * @return
2228          */
2229         @SuppressWarnings("unchecked")
2230         private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
2231                 Role setNewRole = new Role();
2232                 try {
2233                         // functions can have new role created in External Auth System
2234                         // prevent
2235                         // duplication here
2236                         boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
2237                         final Map<String, String> getRoleByNameParams = new HashMap<>();
2238                         List<EPRole> getRoleCreated = null;
2239                         getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
2240                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2241                                 getRoleByNameParams.put("appId", String.valueOf(app.getId()));
2242                                 List<EPRole> roleCreated = dataAccessService
2243                                                 .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
2244                                 if (!isCreated) {
2245                                         EPRole epUpdateRole = roleCreated.get(0);
2246                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2247                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2248                                         getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2249                                                         getRoleByNameParams, null);
2250                                 } else {
2251                                         getRoleCreated = roleCreated;
2252                                 }
2253                         } else {
2254                                 getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
2255                                                 null);
2256                         }
2257                         if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
2258                                 EPRole roleObject = getRoleCreated.get(0);
2259                                 setNewRole.setId(roleObject.getId());
2260                                 setNewRole.setName(roleObject.getName());
2261                                 setNewRole.setActive(roleObject.getActive());
2262                                 setNewRole.setPriority(roleObject.getPriority());
2263                         }
2264                 } catch (Exception e) {
2265                         logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
2266                 }
2267                 return setNewRole;
2268         }
2269
2270         @SuppressWarnings("unchecked")
2271         private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
2272                 boolean isCreated = false;
2273                 final Map<String, String> roleParams = new HashMap<>();
2274                 roleParams.put(APP_ROLE_NAME_PARAM, role);
2275                 List<EPRole> roleCreated = null;
2276                 if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2277                         roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
2278                 } else {
2279                         roleParams.put("appId", String.valueOf(app.getId()));
2280                         roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
2281                                         null);
2282                 }
2283                 if (roleCreated == null || roleCreated.isEmpty()) {
2284                         roleParams.put("appId", String.valueOf(app.getId()));
2285                         EPRole epRoleNew = new EPRole();
2286                         epRoleNew.setActive(true);
2287                         epRoleNew.setName(role);
2288                         if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2289                                 epRoleNew.setAppId(null);
2290                         } else {
2291                                 epRoleNew.setAppId(app.getId());
2292                         }
2293                         dataAccessService.saveDomainObject(epRoleNew, null);
2294                         isCreated = false;
2295                 } else {
2296                         isCreated = true;
2297                 }
2298                 return isCreated;
2299         }
2300
2301         @Override
2302         @SuppressWarnings("unchecked")
2303         public Integer bulkUploadFunctions(String uebkey) throws Exception {
2304                 EPApp app = getApp(uebkey).get(0);
2305                 List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
2306                 CentralV2RoleFunction cenRoleFunc = null;
2307                 Integer functionsAdded = 0;
2308                 try {
2309                         for (RoleFunction roleFunc : roleFuncList) {
2310                                 cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
2311                                 addRoleFunctionInExternalSystem(cenRoleFunc, app);
2312                                 functionsAdded++;
2313                         }
2314                 } catch (HttpClientErrorException e) {
2315                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
2316                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2317                 } catch (Exception e) {
2318                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
2319                 }
2320                 return functionsAdded;
2321         }
2322
2323         @Override
2324         public Integer bulkUploadRoles(String uebkey) throws Exception {
2325                 List<EPApp> app = getApp(uebkey);
2326                 List<EPRole> roles = getAppRoles(app.get(0).getId());
2327                 List<CentralV2Role> cenRoleList = new ArrayList<>();
2328                 final Map<String, Long> params = new HashMap<>();
2329                 Integer rolesListAdded = 0;
2330                 try {
2331                         cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
2332                         ObjectMapper mapper = new ObjectMapper();
2333                         mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
2334                         String roleList = mapper.writeValueAsString(cenRoleList);
2335                         List<Role> roleObjectList = mapper.readValue(roleList,
2336                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
2337                         for (Role role : roleObjectList) {
2338                                 addRoleInExternalSystem(role, app.get(0));
2339                                 rolesListAdded++;
2340                         }
2341                         if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
2342                                 // Add Account Admin role in External AUTH System
2343                                 try {
2344                                         String addAccountAdminRole = "";
2345                                         ExternalAccessRole extRole = new ExternalAccessRole();
2346                                         extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
2347                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2348                                         addAccountAdminRole = mapper.writeValueAsString(extRole);
2349                                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2350                                         HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
2351                                         template.exchange(
2352                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2353                                                         HttpMethod.POST, entity, String.class);
2354                                         rolesListAdded++;
2355                                 } catch (HttpClientErrorException e) {
2356                                         logger.error(EELFLoggerDelegate.errorLogger,
2357                                                         "HttpClientErrorException - Failed to create Account Admin role", e);
2358                                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2359                                 } catch (Exception e) {
2360                                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2361                                                 logger.error(EELFLoggerDelegate.errorLogger,
2362                                                                 "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
2363                                                                 e);
2364                                         } else {
2365                                                 logger.error(EELFLoggerDelegate.errorLogger,
2366                                                                 "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
2367                                         }
2368                                 }
2369                         }
2370                 } catch (Exception e) {
2371                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
2372                         throw e;
2373                 }
2374                 return rolesListAdded;
2375         }
2376
2377         /**
2378          * It creating new role in external auth system while doing bulk upload
2379          * 
2380          * @param role
2381          * @param app
2382          * @throws Exception
2383          */
2384         private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
2385                 String addRoleNew = updateExistingRoleInExternalSystem(role, app);
2386                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2387                 try {
2388                         HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
2389                         template.exchange(
2390                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
2391                                         HttpMethod.POST, entity, String.class);
2392                 } catch (HttpClientErrorException e) {
2393                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
2394                                         e);
2395                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2396                 } catch (Exception e) {
2397                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2398                                 logger.error(EELFLoggerDelegate.errorLogger,
2399                                                 "addRoleInExternalSystem: Role already exits but does not break functionality", e);
2400                         } else {
2401                                 logger.error(EELFLoggerDelegate.errorLogger,
2402                                                 "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
2403                         }
2404                 }
2405         }
2406
2407         @Override
2408         @SuppressWarnings("unchecked")
2409         public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
2410                 EPApp app = getApp(uebkey).get(0);
2411                 List<EPRole> roles = getAppRoles(app.getId());
2412                 final Map<String, Long> params = new HashMap<>();
2413                 Integer roleFunctions = 0;
2414                 try {
2415                         for (EPRole role : roles) {
2416                                 params.put("roleId", role.getId());
2417                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
2418                                                 params, null);
2419                                 if (!appRoleFunc.isEmpty()) {
2420                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2421                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2422                                                 roleFunctions++;
2423                                         }
2424                                 }
2425                         }
2426                 } catch (HttpClientErrorException e) {
2427                         logger.error(EELFLoggerDelegate.errorLogger,
2428                                         "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2429                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2430                 } catch (Exception e) {
2431                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2432                 }
2433                 return roleFunctions;
2434         }
2435
2436         /**
2437          * Its adding a role function while doing bulk upload
2438          * 
2439          * @param addRoleFunc
2440          * @param role
2441          * @param app
2442          */
2443         private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
2444                 String type = "";
2445                 String instance = "";
2446                 String action = "";
2447                 if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2448                         type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
2449                         instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
2450                         action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
2451                 } else {
2452                         type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2453                         instance = addRoleFunc.getFunctionCd();
2454                         action = "*";
2455                 }
2456                 ExternalAccessRolePerms extRolePerms = null;
2457                 ExternalAccessPerms extPerms = null;
2458                 ObjectMapper mapper = new ObjectMapper();
2459                 try {
2460                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2461                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
2462                                         addRoleFunc.getFunctionName());
2463                         extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName()
2464                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2465                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2466                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2467                         template.exchange(
2468                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
2469                                         HttpMethod.POST, entity, String.class);
2470                 } catch (Exception e) {
2471                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
2472                                 logger.error(EELFLoggerDelegate.errorLogger,
2473                                                 "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
2474                                                 e);
2475                         } else {
2476                                 logger.error(EELFLoggerDelegate.errorLogger,
2477                                                 "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
2478                         }
2479                 }
2480         }
2481
2482         @SuppressWarnings("unchecked")
2483         @Override
2484         public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
2485                 EPApp app = getApp(uebkey).get(0);
2486                 final Map<String, Long> params = new HashMap<>();
2487                 params.put("appId", app.getId());
2488                 List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
2489                                 null);
2490                 Integer functionsAdded = 0;
2491                 try {
2492                         for (CentralV2RoleFunction roleFunc : roleFuncList) {
2493                                 addFunctionInExternalSystem(roleFunc, app);
2494                                 functionsAdded++;
2495                         }
2496                 } catch (HttpClientErrorException e) {
2497                         logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
2498                                         e);
2499                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2500                 } catch (Exception e) {
2501                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
2502                 }
2503                 return functionsAdded;
2504         }
2505
2506         private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
2507                 ObjectMapper mapper = new ObjectMapper();
2508                 ExternalAccessPerms extPerms = new ExternalAccessPerms();
2509                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2510                 String type = "";
2511                 String instance = "";
2512                 String action = "";
2513                 if ((roleFunc.getCode().contains(FUNCTION_PIPE))
2514                                 || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
2515                         type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
2516                         instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
2517                         action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
2518                 } else {
2519                         type = roleFunc.getCode().contains("menu") ? "menu" : "url";
2520                         instance = roleFunc.getCode();
2521                         action = "*";
2522                 }
2523                 try {
2524                         extPerms.setAction(action);
2525                         extPerms.setInstance(instance);
2526                         extPerms.setType(app.getNameSpace() + "." + type);
2527                         extPerms.setDescription(roleFunc.getName());
2528                         String addFunction = mapper.writeValueAsString(extPerms);
2529                         HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
2530                         logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
2531                                         CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
2532                         ResponseEntity<String> addPermResponse = template.exchange(
2533                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
2534                                         HttpMethod.POST, entity, String.class);
2535                         logger.debug(EELFLoggerDelegate.debugLogger,
2536                                         "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
2537                                         addPermResponse.getStatusCode().value(), addFunction);
2538                 } catch (HttpClientErrorException e) {
2539                         logger.error(EELFLoggerDelegate.errorLogger,
2540                                         "HttpClientErrorException - Failed to add function in external central auth system", e);
2541                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2542                         throw e;
2543                 } catch (Exception e) {
2544                         logger.error(EELFLoggerDelegate.errorLogger,
2545                                         "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
2546                         throw e;
2547                 }
2548         }
2549
2550         @Override
2551         public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
2552                 EPApp app = getApp(uebkey).get(0);
2553                 for (Role role : roleList) {
2554                         addRoleInExternalSystem(role, app);
2555                 }
2556         }
2557
2558         @SuppressWarnings("unchecked")
2559         @Override
2560         public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
2561                 EPApp app = getApp(uebkey).get(0);
2562                 List<EPRole> roles = getAppRoles(app.getId());
2563                 final Map<String, Long> params = new HashMap<>();
2564                 Integer roleFunctions = 0;
2565                 try {
2566                         for (EPRole role : roles) {
2567                                 params.put("roleId", role.getId());
2568                                 List<BulkUploadRoleFunction> appRoleFunc = dataAccessService
2569                                                 .executeNamedQuery("uploadPartnerRoleFunctions", params, null);
2570                                 if (!appRoleFunc.isEmpty()) {
2571                                         for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
2572                                                 addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
2573                                                 roleFunctions++;
2574                                         }
2575                                 }
2576                         }
2577                         // upload global role functions to ext auth system
2578                         if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2579                                 roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
2580                         }
2581                 } catch (HttpClientErrorException e) {
2582                         logger.error(EELFLoggerDelegate.errorLogger,
2583                                         "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
2584                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2585                 } catch (Exception e) {
2586                         logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
2587                 }
2588                 return roleFunctions;
2589         }
2590
2591         @SuppressWarnings("unchecked")
2592         private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
2593                 try {
2594                         EPApp portalApp = epAppService.getApp(1l);
2595                         final Map<String, Long> params = new HashMap<>();
2596                         params.put("appId", app.getId());
2597                         List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
2598                                         .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
2599                         ObjectMapper mapper = new ObjectMapper();
2600                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2601                         for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
2602                                 ExternalAccessRolePerms extRolePerms;
2603                                 ExternalAccessPerms extPerms;
2604                                 String type = "";
2605                                 String instance = "";
2606                                 String action = "";
2607                                 if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
2608                                         type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
2609                                         instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
2610                                         action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
2611                                 } else {
2612                                         type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
2613                                         instance = globalRoleFunc.getFunctionCd();
2614                                         action = "*";
2615                                 }
2616                                 extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
2617                                 extRolePerms = new ExternalAccessRolePerms(extPerms,
2618                                                 portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName().replaceAll(
2619                                                                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2620                                 String updateRolePerms = mapper.writeValueAsString(extRolePerms);
2621                                 HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
2622                                 updateRoleFunctionInExternalSystem(updateRolePerms, entity);
2623                                 roleFunctions++;
2624                         }
2625                 } catch (HttpClientErrorException e) {
2626                         logger.error(EELFLoggerDelegate.errorLogger,
2627                                         "HttpClientErrorException - Failed to add role function in external central auth system", e);
2628                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2629                         throw e;
2630                 } catch (Exception e) {
2631                         logger.error(EELFLoggerDelegate.errorLogger,
2632                                         "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
2633                         throw e;
2634                 }
2635                 return roleFunctions;
2636         }
2637
2638         @Override
2639         @Transactional
2640         public void syncApplicationRolesWithEcompDB(EPApp app) {
2641                 try {
2642                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
2643                         // Sync functions and roles assigned to it which also creates new roles if does
2644                         // not exits in portal
2645                         syncRoleFunctionFromExternalAccessSystem(app);
2646                         logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
2647                         ObjectMapper mapper = new ObjectMapper();
2648                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
2649                         // Get Permissions from External Auth System
2650                         JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
2651                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
2652                         // refactoring done
2653                         List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
2654                         List<EPRole> finalRoleList = new ArrayList<>();
2655                         for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
2656                                 EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
2657                                 finalRoleList.add(ecompRole);
2658                         }
2659                         List<EPRole> applicationRolesList;
2660                         applicationRolesList = getAppRoles(app.getId());
2661                         List<String> applicationRoleIdList = new ArrayList<>();
2662                         for (EPRole applicationRole : applicationRolesList) {
2663                                 applicationRoleIdList.add(applicationRole.getName());
2664                         }
2665                         List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
2666                         for (EPRole aafRole : finalRoleList) {
2667                                 if (!applicationRoleIdList.contains(aafRole.getName())) {
2668                                         roleListToBeAddInEcompDB.add(aafRole);
2669                                 }
2670                         }
2671                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
2672                         // Check if roles exits in external Access system and if not make inactive in DB
2673                         inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);
2674                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
2675                         // Add new roles in DB and updates role description in External Auth System
2676                         addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
2677                         logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
2678                 } catch (HttpClientErrorException e) {
2679                         logger.error(EELFLoggerDelegate.errorLogger,
2680                                         "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
2681                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
2682                 } catch (Exception e) {
2683                         logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
2684                 }
2685         }
2686
2687         /**
2688          * 
2689          * It adds new roles in DB and updates description in External Auth System
2690          * 
2691          * @param app
2692          * @param roleListToBeAddInEcompDB
2693          */
2694         @SuppressWarnings("unchecked")
2695         private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
2696                 EPRole roleToBeAddedInEcompDB;
2697                 for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
2698                         try {
2699                                 roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
2700                                 if (app.getId() == 1) {
2701                                         roleToBeAddedInEcompDB.setAppRoleId(null);
2702                                 }
2703                                 dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
2704                                 List<EPRole> getRoleCreatedInSync = null;
2705                                 if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
2706                                         final Map<String, String> globalRoleParams = new HashMap<>();
2707                                         globalRoleParams.put("appId", String.valueOf(app.getId()));
2708                                         globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
2709                                         getRoleCreatedInSync = dataAccessService
2710                                                         .executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
2711                                         EPRole epUpdateRole = getRoleCreatedInSync.get(0);
2712                                         epUpdateRole.setAppRoleId(epUpdateRole.getId());
2713                                         dataAccessService.saveDomainObject(epUpdateRole, null);
2714                                 }
2715                                 List<EPRole> roleList = new ArrayList<>();
2716                                 final Map<String, String> params = new HashMap<>();
2717                                 params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
2718                                 boolean isPortalRole = false;
2719                                 if (app.getId() == 1) {
2720                                         isPortalRole = true;
2721                                         roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
2722                                 } else {
2723                                         isPortalRole = false;
2724                                         params.put(APP_ID, app.getId().toString());
2725                                         roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params,
2726                                                         null);
2727                                 }
2728                                 EPRole role = roleList.get(0);
2729                                 Role aaFrole = new Role();
2730                                 aaFrole.setId(role.getId());
2731                                 aaFrole.setActive(role.getActive());
2732                                 aaFrole.setPriority(role.getPriority());
2733                                 aaFrole.setName(role.getName());
2734                                 updateRoleInExternalSystem(aaFrole, app, isPortalRole);
2735                         } catch (Exception e) {
2736                                 logger.error(EELFLoggerDelegate.errorLogger,
2737                                                 "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
2738                         }
2739                 }
2740         }
2741
2742         /**
2743          * 
2744          * It de-activates application roles in DB if not present in External Auth
2745          * system
2746          * 
2747          * @param app
2748          * @param finalRoleList        contains list of current roles present in
2749          *                             External Auth System
2750          * @param applicationRolesList contains list of current roles present in DB
2751          */
2752         @SuppressWarnings("unchecked")
2753         private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
2754                         List<EPRole> applicationRolesList) {
2755                 final Map<String, EPRole> checkRolesInactive = new HashMap<>();
2756                 for (EPRole extrole : finalRoleList) {
2757                         checkRolesInactive.put(extrole.getName(), extrole);
2758                 }
2759                 for (EPRole role : applicationRolesList) {
2760                         try {
2761                                 final Map<String, String> extRoleParams = new HashMap<>();
2762                                 List<EPRole> roleList = null;
2763                                 extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
2764                                 if (!checkRolesInactive.containsKey(role.getName())) {
2765                                         if (app.getId() == 1) {
2766                                                 roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
2767                                         } else {
2768                                                 extRoleParams.put(APP_ID, app.getId().toString());
2769                                                 roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
2770                                                                 extRoleParams, null);
2771                                         }
2772                                         if (!roleList.isEmpty()) {
2773                                                 EPRole updateRoleInactive = roleList.get(0);
2774                                                 updateRoleInactive.setActive(false);
2775                                                 dataAccessService.saveDomainObject(updateRoleInactive, null);
2776                                         }
2777                                 }
2778                         } catch (Exception e) {
2779                                 logger.error(EELFLoggerDelegate.errorLogger,
2780                                                 "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
2781                         }
2782                 }
2783         }
2784
2785         @Override
2786         @SuppressWarnings("unchecked")
2787         public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app, ObjectMapper mapper, JSONArray extRole)
2788                         throws IOException {
2789                 List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
2790                 ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
2791                 List<String> functionCodelist = new ArrayList<>();
2792                 Map<String, EPRole> curRolesMap = getAppRoleNamesMap(app);
2793                 Map<String, EPRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
2794                 for (int i = 0; i < extRole.length(); i++) {
2795                         ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
2796                         EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
2797                         JSONObject Role = (JSONObject) extRole.get(i);
2798                         String name = extRole.getJSONObject(i).getString(ROLE_NAME);
2799                         String actualRoleName = name.substring(app.getNameSpace().length() + 1);
2800                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
2801                                 actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
2802                         }
2803                         SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
2804                         if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
2805                                 JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
2806                                 for (int j = 0; j < extPerm.length(); j++) {
2807                                         JSONObject perms = extPerm.getJSONObject(j);
2808                                         boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
2809                                                         app.getNameSpace());
2810                                         if (isNamespaceMatching) {
2811                                                 externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
2812                                                                 perms.getString("instance"), perms.getString("action"));
2813                                                 ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
2814                                                 functionCodelist.add(ePAppRoleFunction.getCode());
2815                                                 externalAccessPermsOfRole.add(externalAccessPerms);
2816                                         }
2817                                 }
2818                         }
2819                         externalRoleDetail.setActive(true);
2820                         externalRoleDetail.setName(actualRoleName);
2821                         if (app.getId() == 1) {
2822                                 externalRoleDetail.setAppId(null);
2823                         } else {
2824                                 externalRoleDetail.setAppId(app.getId());
2825                         }
2826                         EPRole currRole = null;
2827                         currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
2828                                         ? curRolesUnderscoreMap.get(actualRoleName)
2829                                         : curRolesMap.get(actualRoleName);
2830                         Long roleId = null;
2831                         if (currRole != null)
2832                                 roleId = currRole.getId();
2833                         final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
2834                         final Map<String, Long> appRoleFuncsParams = new HashMap<>();
2835                         if (roleId != null) {
2836                                 appRoleFuncsParams.put("appId", app.getId());
2837                                 appRoleFuncsParams.put("roleId", roleId);
2838                                 // get role functions from DB
2839                                 List<EPAppRoleFunction> appRoleFunctions = dataAccessService
2840                                                 .executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
2841                                 if (!appRoleFunctions.isEmpty()) {
2842                                         for (EPAppRoleFunction roleFunc : appRoleFunctions) {
2843                                                 roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
2844                                         }
2845                                 }
2846                         }
2847                         if (!externalAccessPermsOfRole.isEmpty()) {
2848                                 // Adding functions to role
2849                                 for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
2850                                         EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
2851                                         if (checkRoleFunctionExits == null) {
2852                                                 String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
2853                                                                 + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
2854                                                                 + externalpermission.getAction();
2855                                                 EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
2856                                                 if (checkRoleFunctionPipeExits == null) {
2857                                                         try {
2858                                                                 final Map<String, String> appFuncsParams = new HashMap<>();
2859                                                                 appFuncsParams.put("appId", String.valueOf(app.getId()));
2860                                                                 appFuncsParams.put("functionCd", externalpermission.getInstance());
2861                                                                 logger.debug(EELFLoggerDelegate.debugLogger,
2862                                                                                 "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
2863                                                                                 externalpermission.getInstance());
2864                                                                 List<CentralV2RoleFunction> roleFunction = null;
2865                                                                 roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2866                                                                                 appFuncsParams, null);
2867                                                                 if (roleFunction.isEmpty()) {
2868                                                                         appFuncsParams.put("functionCd", funcCode);
2869                                                                         roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
2870                                                                                         appFuncsParams, null);
2871                                                                 }
2872                                                                 if (!roleFunction.isEmpty()) {
2873                                                                         EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
2874                                                                         apRoleFunction.setAppId(app.getId());
2875                                                                         apRoleFunction.setRoleId(roleId);
2876                                                                         apRoleFunction.setCode(roleFunction.get(0).getCode());
2877                                                                         dataAccessService.saveDomainObject(apRoleFunction, null);
2878                                                                 }
2879                                                         } catch (Exception e) {
2880                                                                 logger.error(EELFLoggerDelegate.errorLogger,
2881                                                                                 "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
2882                                                         }
2883                                                 }
2884                                         }
2885                                 }
2886                         }
2887                         externalRoleDetailsList.add(externalRoleDetail);
2888                 }
2889                 return externalRoleDetailsList;
2890         }
2891
2892         @Override
2893         public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
2894                 ResponseEntity<String> response = null;
2895                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2896                 HttpEntity<String> entity = new HttpEntity<>(headers);
2897                 logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
2898                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2899                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2900                                 + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
2901                 String res = response.getBody();
2902                 logger.debug(EELFLoggerDelegate.debugLogger,
2903                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2904                                 res);
2905                 JSONObject jsonObj = new JSONObject(res);
2906                 JSONArray extRole = jsonObj.getJSONArray("role");
2907                 for (int i = 0; i < extRole.length(); i++) {
2908                         if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
2909                                         || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
2910                                         || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
2911                                                         && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
2912                                 extRole.remove(i);
2913                                 i--;
2914                         }
2915                 }
2916                 return extRole;
2917         }
2918
2919         @Override
2920         public JSONArray getAllUsersByRole(String roleName) throws Exception {
2921                 ResponseEntity<String> response = null;
2922                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2923                 HttpEntity<String> entity = new HttpEntity<>(headers);
2924                 logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
2925                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
2926                 response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
2927                                 + "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
2928                 String res = response.getBody();
2929                 logger.debug(EELFLoggerDelegate.debugLogger,
2930                                 "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
2931                                 res);
2932                 if (res == null || res.trim().isEmpty())
2933                         return null;
2934                 JSONObject jsonObj = new JSONObject(res);
2935                 JSONArray extRole = jsonObj.getJSONArray("userRole");
2936                 return extRole;
2937         }
2938
2939         /**
2940          * 
2941          * It converts from ExternalRoleDetails.class object to EPRole.class object
2942          * 
2943          * @param externalRoleDetails
2944          * @return EPRole object
2945          */
2946         private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
2947                 EPRole role = new EPRole();
2948                 role.setActive(true);
2949                 role.setAppId(externalRoleDetails.getAppId());
2950                 role.setAppRoleId(externalRoleDetails.getAppRoleId());
2951                 role.setName(externalRoleDetails.getName());
2952                 role.setPriority(externalRoleDetails.getPriority());
2953                 return role;
2954         }
2955
2956         @SuppressWarnings("unchecked")
2957         @Override
2958         public Integer bulkUploadUserRoles(String uebkey) throws Exception {
2959                 EPApp app = getApp(uebkey).get(0);
2960                 final Map<String, String> params = new HashMap<>();
2961                 params.put("uebKey", app.getUebKey());
2962                 List<BulkUploadUserRoles> userRolesList = null;
2963                 Integer userRolesAdded = 0;
2964                 if (app.getCentralAuth()) {
2965                         userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
2966                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
2967                                 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
2968                                         addUserRoleInExternalSystem(userRolesUpload);
2969                                         userRolesAdded++;
2970                                 }
2971                         }
2972                 }
2973                 return userRolesAdded;
2974         }
2975
2976         /**
2977          * Its adding a user role in external auth system while doing bulk upload
2978          * 
2979          * @param userRolesUpload
2980          */
2981         private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
2982                 try {
2983                         String name = "";
2984                         ObjectMapper mapper = new ObjectMapper();
2985                         if (EPCommonSystemProperties
2986                                         .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
2987                                 name = userRolesUpload.getOrgUserId()
2988                                                 + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
2989                         }
2990                         ExternalAccessUser extUser = new ExternalAccessUser(name,
2991                                         userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
2992                                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
2993                         String userRole = mapper.writeValueAsString(extUser);
2994                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
2995                         HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
2996                         template.exchange(
2997                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
2998                                         HttpMethod.POST, entity, String.class);
2999                 } catch (HttpClientErrorException e) {
3000                         logger.error(EELFLoggerDelegate.errorLogger,
3001                                         "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
3002                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3003                 } catch (Exception e) {
3004                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
3005                                 logger.error(EELFLoggerDelegate.errorLogger,
3006                                                 "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
3007                         } else {
3008                                 logger.error(EELFLoggerDelegate.errorLogger,
3009                                                 "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
3010                         }
3011                 }
3012         }
3013
3014         @Override
3015         public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest)
3016                         throws Exception {
3017                 try {
3018                         String sql = "";
3019                         Query query = null;
3020                         // It should delete only when it portal's roleId
3021                         if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
3022                                 // Delete from fn_role_function
3023                                 sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
3024                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3025                                 query = localSession.createSQLQuery(sql);
3026                                 query.executeUpdate();
3027                                 // Delete from fn_role_composite
3028                                 sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
3029                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3030                                 query = localSession.createSQLQuery(sql);
3031                                 query.executeUpdate();
3032                         }
3033                         // Delete from ep_app_role_function
3034                         sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
3035                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3036                         query = localSession.createSQLQuery(sql);
3037                         query.executeUpdate();
3038                         // Delete from ep_role_notification
3039                         sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
3040                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3041                         query = localSession.createSQLQuery(sql);
3042                         query.executeUpdate();
3043                         // Delete from fn_user_pseudo_role
3044                         sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
3045                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3046                         query = localSession.createSQLQuery(sql);
3047                         query.executeUpdate();
3048                         // Delete form EP_WIDGET_CATALOG_ROLE
3049                         sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
3050                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3051                         query = localSession.createSQLQuery(sql);
3052                         query.executeUpdate();
3053                         // Delete form EP_WIDGET_CATALOG_ROLE
3054                         sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
3055                         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3056                         query = localSession.createSQLQuery(sql);
3057                         query.executeUpdate();
3058                         if (!isPortalRequest) {
3059                                 // Delete form fn_menu_functional_roles
3060                                 sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
3061                                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
3062                                 query = localSession.createSQLQuery(sql);
3063                                 query.executeUpdate();
3064                         }
3065                 } catch (Exception e) {
3066                         logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
3067                         throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
3068                 }
3069         }
3070
3071         @SuppressWarnings("unchecked")
3072         @Override
3073         public List<String> getMenuFunctionsList(String uebkey) throws Exception {
3074                 List<String> appMenuFunctionsList = null;
3075                 List<String> appMenuFunctionsFinalList = new ArrayList<>();
3076                 try {
3077                         EPApp app = getApp(uebkey).get(0);
3078                         final Map<String, Long> appParams = new HashMap<>();
3079                         appParams.put(APP_ID, app.getId());
3080                         appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
3081                         for (String appMenuFunction : appMenuFunctionsList) {
3082                                 if (appMenuFunction.contains(FUNCTION_PIPE)) {
3083                                         appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
3084                                 } else {
3085                                         appMenuFunctionsFinalList.add(appMenuFunction);
3086                                 }
3087                         }
3088                 } catch (Exception e) {
3089                         logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
3090                         return appMenuFunctionsFinalList;
3091                 }
3092                 return appMenuFunctionsFinalList;
3093         }
3094
3095         @SuppressWarnings({ "unchecked" })
3096         @Override
3097         public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
3098                 List<String> usersList = new ArrayList<>();
3099                 List<EcompUser> usersfinalList = new ArrayList<>();
3100                 try {
3101                         EPApp app = getApp(uebkey).get(0);
3102                         final Map<String, Long> appParams = new HashMap<>();
3103                         appParams.put("appId", app.getId());
3104                         List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
3105                                         .executeNamedQuery("ApplicationUserRoles", appParams, null);
3106                         for (EcompUserRoles ecompUserRole : userList) {
3107                                 boolean found = false;
3108                                 Set<EcompRole> roles = null;
3109                                 for (EcompUser user : usersfinalList) {
3110                                         if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
3111                                                 EcompRole ecompRole = new EcompRole();
3112                                                 ecompRole.setId(ecompUserRole.getRoleId());
3113                                                 ecompRole.setName(ecompUserRole.getRoleName());
3114                                                 roles = user.getRoles();
3115                                                 EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
3116                                                                 .findAny().orElse(null);
3117                                                 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3118                                                 if (role != null) {
3119                                                         roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
3120                                                 }
3121                                                 String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3122                                                 functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3123                                                 EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3124                                                 epRoleFunction.setName(ecompUserRole.getFunctionName());
3125                                                 epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3126                                                 epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3127                                                 epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3128                                                 roleFunctionSet.add(epRoleFunction);
3129                                                 ecompRole.setRoleFunctions(roleFunctionSet);
3130                                                 roles.add(ecompRole);
3131                                                 user.setRoles(roles);
3132                                                 found = true;
3133                                                 break;
3134                                         }
3135                                 }
3136                                 if (!found) {
3137                                         EcompUser epUser = new EcompUser();
3138                                         epUser.setOrgId(ecompUserRole.getOrgId());
3139                                         epUser.setManagerId(ecompUserRole.getManagerId());
3140                                         epUser.setFirstName(ecompUserRole.getFirstName());
3141                                         epUser.setLastName(ecompUserRole.getLastName());
3142                                         epUser.setPhone(ecompUserRole.getPhone());
3143                                         epUser.setEmail(ecompUserRole.getEmail());
3144                                         epUser.setOrgUserId(ecompUserRole.getOrgUserId());
3145                                         epUser.setOrgCode(ecompUserRole.getOrgCode());
3146                                         epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
3147                                         epUser.setJobTitle(ecompUserRole.getJobTitle());
3148                                         epUser.setLoginId(ecompUserRole.getLoginId());
3149                                         epUser.setActive(true);
3150                                         roles = new HashSet<>();
3151                                         EcompRole ecompRole = new EcompRole();
3152                                         ecompRole.setId(ecompUserRole.getRoleId());
3153                                         ecompRole.setName(ecompUserRole.getRoleName());
3154                                         SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3155                                         String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
3156                                         functionCode = EPUserUtils.decodeFunctionCode(functionCode);
3157                                         EcompRoleFunction epRoleFunction = new EcompRoleFunction();
3158                                         epRoleFunction.setName(ecompUserRole.getFunctionName());
3159                                         epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
3160                                         epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
3161                                         epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
3162                                         roleFunctionSet.add(epRoleFunction);
3163                                         ecompRole.setRoleFunctions(roleFunctionSet);
3164                                         roles.add(ecompRole);
3165                                         epUser.setRoles(roles);
3166                                         usersfinalList.add(epUser);
3167                                 }
3168                         }
3169                         ObjectMapper mapper = new ObjectMapper();
3170                         for (EcompUser u1 : usersfinalList) {
3171                                 String str = mapper.writeValueAsString(u1);
3172                                 usersList.add(str);
3173                         }
3174                 } catch (Exception e) {
3175                         logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
3176                         throw e;
3177                 }
3178                 return usersfinalList;
3179         }
3180
3181         @Override
3182         public Role ConvertCentralRoleToRole(String result) {
3183                 ObjectMapper mapper = new ObjectMapper();
3184                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
3185                 Role newRole = new Role();
3186                 try {
3187                         newRole = mapper.readValue(result, Role.class);
3188                 } catch (IOException e) {
3189                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
3190                 }
3191                 if (newRole.getRoleFunctions() != null) {
3192                         @SuppressWarnings("unchecked")
3193                         Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
3194                         Set<RoleFunction> roleFunctionListNew = new HashSet<>();
3195                         Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
3196                         while (itetaror.hasNext()) {
3197                                 Object nextValue = itetaror.next();
3198                                 RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
3199                                 roleFunctionListNew.add(roleFun);
3200                         }
3201                         newRole.setRoleFunctions(roleFunctionListNew);
3202                 }
3203                 return newRole;
3204         }
3205
3206         @Override
3207         @SuppressWarnings("unchecked")
3208         public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
3209                 Map<String, String> params = new HashMap<>();
3210                 params.put("userId", userId);
3211                 List<CentralizedApp> centralizedAppsList = new ArrayList<>();
3212                 try {
3213                         centralizedAppsList = dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null);
3214                 } catch (Exception e) {
3215                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3216                 }
3217                 return centralizedAppsList;
3218         }
3219
3220         @SuppressWarnings("unchecked")
3221         public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
3222                 Map<String, Long> params = new HashMap<>();
3223                 params.put("appId", appId);
3224                 List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
3225                 try {
3226                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
3227                                         null);
3228                 } catch (Exception e) {
3229                         logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
3230                 }
3231                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3232                 if (globalRoles.size() > 0)
3233                         rolesfinalList = finalListOfCentralRoles(globalRoles);
3234                 return rolesfinalList;
3235         }
3236
3237         @SuppressWarnings("unchecked")
3238         private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
3239                 CentralV2Role finalGlobalrole = null;
3240                 List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
3241                 Map<String, Long> params = new HashMap<>();
3242                 params.put("roleId", roleId);
3243                 params.put("requestedAppId", requestedAppId);
3244                 try {
3245                         roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
3246                                         params, null);
3247                 } catch (Exception e) {
3248                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
3249                 }
3250                 if (roleWithApplicationRoleFucntions.size() > 0) {
3251                         List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
3252                         finalGlobalrole = rolesfinalList.get(0);
3253                 } else {
3254                         List<EPRole> roleList = getPortalAppRoleInfo(roleId);
3255                         finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
3256                 }
3257                 return finalGlobalrole;
3258         }
3259
3260         private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
3261                 List<CentralV2Role> rolesfinalList = new ArrayList<>();
3262                 for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
3263                         boolean found = false;
3264                         for (CentralV2Role cenRole : rolesfinalList) {
3265                                 if (role.getRoleId().equals(cenRole.getId())) {
3266                                         SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
3267                                         CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3268                                         roleFunctions.add(cenRoleFun);
3269                                         cenRole.setRoleFunctions(roleFunctions);
3270                                         found = true;
3271                                         break;
3272                                 }
3273                         }
3274                         if (!found) {
3275                                 CentralV2Role cenrole = new CentralV2Role();
3276                                 cenrole.setName(role.getRoleName());
3277                                 cenrole.setId(role.getRoleId());
3278                                 cenrole.setActive(role.isActive());
3279                                 cenrole.setPriority(role.getPriority());
3280                                 SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
3281                                 CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
3282                                 roleFunctions.add(cenRoleFun);
3283                                 cenrole.setRoleFunctions(roleFunctions);
3284                                 rolesfinalList.add(cenrole);
3285                         }
3286                 }
3287                 return rolesfinalList;
3288         }
3289
3290         private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
3291                 String instance;
3292                 String type;
3293                 String action;
3294                 CentralV2RoleFunction cenRoleFun;
3295                 if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
3296                         instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
3297                         type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
3298                         action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
3299                         cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
3300                 } else {
3301                         type = getFunctionCodeType(role.getFunctionCd());
3302                         action = getFunctionCodeAction(role.getFunctionCd());
3303                         cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type,
3304                                         action, null);
3305                 }
3306                 return cenRoleFun;
3307         }
3308
3309         @SuppressWarnings("unchecked")
3310         @Override
3311         public List<EPRole> getGlobalRolesOfPortal() {
3312                 List<EPRole> globalRoles = new ArrayList<>();
3313                 try {
3314                         globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
3315                 } catch (Exception e) {
3316                         logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
3317                 }
3318                 return globalRoles;
3319         }
3320
3321         private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
3322                 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
3323                                 role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
3324                                 new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
3325         }
3326
3327         @Override
3328         public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
3329                         List<CentralV2RoleFunction> answer) {
3330                 List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
3331                 for (CentralV2RoleFunction cenRoleFunc : answer) {
3332                         CentralRoleFunction setRoleFunc = new CentralRoleFunction();
3333                         setRoleFunc.setCode(cenRoleFunc.getCode());
3334                         setRoleFunc.setName(cenRoleFunc.getName());
3335                         addRoleFuncList.add(setRoleFunc);
3336                 }
3337                 return addRoleFuncList;
3338         }
3339
3340         @Override
3341         public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
3342                 CentralUser sendUserRoles = null;
3343                 try {
3344                         CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
3345                         sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
3346                 } catch (Exception e) {
3347                         logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
3348                         throw e;
3349                 }
3350                 return sendUserRoles;
3351         }
3352
3353         /**
3354          * 
3355          * It returns V2 CentralUser object if user has any roles and permissions
3356          * 
3357          * @param loginId
3358          * @param uebkey
3359          * @return CentralUser object
3360          * @throws Exception
3361          */
3362         private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
3363                 EPApp app;
3364                 List<EPUser> epUserList;
3365                 List<EPApp> appList = getApp(uebkey);
3366                 app = appList.get(0);
3367                 epUserList = getUser(loginId);
3368                 EPUser user = epUserList.get(0);
3369                 Set<EPUserApp> userAppSet = user.getEPUserApps();
3370                 return createEPUser(user, userAppSet, app);
3371         }
3372
3373         private List<EcompRole> getUserAppRoles(EPApp app, EPUser user) {
3374                 final Map<String, Long> userParams = new HashMap<>();
3375                 userParams.put("appId", app.getId());
3376                 userParams.put("userId", user.getId());
3377                 @SuppressWarnings("unchecked")
3378                 List<EPUserAppCurrentRoles> userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles",
3379                                 userParams, null);
3380                 List<EcompRole> setUserRoles = new ArrayList<>();
3381                 for (EPUserAppCurrentRoles role : userAppsRolesList) {
3382                         logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
3383                                         role.getRoleName());
3384                         EcompRole ecompRole = new EcompRole();
3385                         ecompRole.setId(role.getRoleId());
3386                         ecompRole.setName(role.getRoleName());
3387                         setUserRoles.add(ecompRole);
3388                 }
3389                 logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
3390                                 setUserRoles.size());
3391                 return setUserRoles;
3392         }
3393
3394         @Override
3395         public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
3396                         throws Exception {
3397                 List<EPApp> appList = getApp(uebkey);
3398                 EPApp app = appList.get(0);
3399                 List<EPUser> epUserList;
3400                 epUserList = getUser(loginId);
3401                 List<EcompRole> missingUserAppRoles = new ArrayList<>();
3402                 List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
3403                 logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
3404                 List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
3405                 if (userApplicationsRolesfromDB.size() > 0) {
3406                         missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
3407                                         .collect(Collectors.toList());
3408                 }
3409                 List<String> MissingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
3410                                 .collect(Collectors.toList());
3411                 logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + MissingroleNamesList);
3412
3413                 List<EcompRole> finalMissingRoleList = new ArrayList<>();
3414                 if (missingUserAppRoles.size() > 0) {
3415                         final Map<String, Long> params = new HashMap<>();
3416                         for (EcompRole role : missingUserAppRoles) {
3417                                 params.put("roleId", role.getId());
3418                                 params.put(APP_ID, app.getId());
3419
3420                                 EcompRole epRole = new EcompRole();
3421                                 epRole.setId(role.getId());
3422                                 epRole.setName(role.getName());
3423                                 @SuppressWarnings("unchecked")
3424                                 List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
3425                                                 .executeNamedQuery("getAppRoleFunctionList", params, null);
3426                                 SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
3427                                 for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
3428                                         String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
3429                                         String type = getFunctionCodeType(roleFunc.getCode());
3430                                         String action = getFunctionCodeAction(roleFunc.getCode());
3431                                         EcompRoleFunction fun = new EcompRoleFunction();
3432                                         fun.setAction(action);
3433                                         fun.setCode(functionCode);
3434                                         fun.setType(type);
3435                                         fun.setName(roleFunc.getName());
3436                                         roleFunctionSet.add(fun);
3437
3438                                 }
3439                                 epRole.setRoleFunctions(roleFunctionSet);
3440                                 finalMissingRoleList.add(epRole);
3441                         }
3442                 }
3443
3444                 return finalMissingRoleList;
3445         }
3446
3447         /**
3448          * It converts V2 CentralUser object to old version CentralUser object
3449          * 
3450          * @param cenV2User
3451          * @return EPUser object
3452          */
3453         private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
3454                 Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
3455                 Set<CentralUserApp> userApps = new TreeSet<>();
3456                 for (CentralV2UserApp userApp : userV2Apps) {
3457                         CentralApp app = userApp.getApp();
3458                         CentralUserApp cua = new CentralUserApp();
3459                         cua.setUserId(null);
3460                         cua.setApp(app);
3461                         SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
3462                         for (CentralV2RoleFunction cenV2RoleFunc : userApp.getRole().getRoleFunctions()) {
3463                                 CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(),
3464                                                 cenV2RoleFunc.getName());
3465                                 cenRoleFunction.add(cenRoleFunc);
3466                         }
3467                         CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
3468                                         userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction);
3469                         cua.setRole(role);
3470                         userApps.add(cua);
3471                 }
3472         return new CentralUser.CentralUserBuilder().setId(cenV2User.getId()).setCreated(cenV2User.getCreated())
3473                 .setModified(cenV2User.getModified()).setCreatedId(cenV2User.getCreatedId())
3474                 .setModifiedId(cenV2User.getModifiedId()).setRowNum(cenV2User.getRowNum())
3475                 .setOrgId(cenV2User.getOrgId()).setManagerId(cenV2User.getManagerId())
3476                 .setFirstName(cenV2User.getFirstName()).setMiddleInitial(cenV2User.getMiddleInitial())
3477                 .setLastName(cenV2User.getLastName()).setPhone(cenV2User.getPhone()).setFax(cenV2User.getFax())
3478                 .setCellular(cenV2User.getCellular()).setEmail(cenV2User.getEmail())
3479                 .setAddressId(cenV2User.getAddressId()).setAlertMethodCd(cenV2User.getAlertMethodCd())
3480                 .setHrid(cenV2User.getHrid()).setOrgUserId(cenV2User.getOrgUserId()).setOrgCode(cenV2User.getOrgCode())
3481                 .setAddress1(cenV2User.getAddress1()).setAddress2(cenV2User.getAddress2()).setCity(cenV2User.getCity())
3482                 .setState(cenV2User.getState()).setZipCode(cenV2User.getZipCode()).setCountry(cenV2User.getCountry())
3483                 .setOrgManagerUserId(cenV2User.getOrgManagerUserId()).setLocationClli(cenV2User.getLocationClli())
3484                 .setBusinessCountryCode(cenV2User.getBusinessCountryCode())
3485                 .setBusinessCountryName(cenV2User.getBusinessCountryName()).setBusinessUnit(cenV2User.getBusinessUnit())
3486                 .setBusinessUnitName(cenV2User.getBusinessUnitName()).setDepartment(cenV2User.getDepartment())
3487                 .setDepartmentName(cenV2User.getDepartmentName()).setCompanyCode(cenV2User.getCompanyCode())
3488                 .setCompany(cenV2User.getCompany()).setZipCodeSuffix(cenV2User.getZipCodeSuffix())
3489                 .setJobTitle(cenV2User.getJobTitle()).setCommandChain(cenV2User.getCommandChain())
3490                 .setSiloStatus(cenV2User.getSiloStatus()).setCostCenter(cenV2User.getCostCenter())
3491                 .setFinancialLocCode(cenV2User.getFinancialLocCode()).setLoginId(cenV2User.getLoginId())
3492                 .setLoginPwd(cenV2User.getLoginPwd()).setLastLoginDate(cenV2User.getLastLoginDate())
3493                 .setActive(cenV2User.isActive()).setInternal(cenV2User.isInternal())
3494                 .setSelectedProfileId(cenV2User.getSelectedProfileId()).setTimeZoneId(cenV2User.getTimeZoneId())
3495                 .setOnline(cenV2User.isOnline()).setChatId(cenV2User.getChatId()).setUserApps(userApps)
3496                 .createCentralUser();
3497         }
3498
3499         @Override
3500         public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
3501                 List<CentralRole> cenRoleList = new ArrayList<>();
3502                 for (CentralV2Role v2CenRole : v2CenRoleList) {
3503                         SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3504                         for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3505                                 CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(),
3506                                                 v2CenRoleFunc.getName());
3507                                 cenRoleFuncList.add(roleFunc);
3508                         }
3509                         CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(),
3510                                         v2CenRole.getPriority(), cenRoleFuncList);
3511                         cenRoleList.add(role);
3512                 }
3513                 return cenRoleList;
3514         }
3515
3516         @Override
3517         public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
3518                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3519                 HttpEntity<String> entity = new HttpEntity<>(headers);
3520                 logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
3521                 ResponseEntity<String> response = null;
3522                 try {
3523                         response = template
3524                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3525                                                         + "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
3526                         logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
3527                                         response.getStatusCode().value());
3528                 } catch (HttpClientErrorException e) {
3529                         logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
3530                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3531                         if (e.getStatusCode() == HttpStatus.NOT_FOUND)
3532                                 throw new InvalidApplicationException("Invalid NameSpace");
3533                         else
3534                                 throw e;
3535                 }
3536                 return response;
3537         }
3538
3539         @Override
3540         public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
3541                 SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
3542                 for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
3543                         CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
3544                         cenRoleFuncList.add(roleFunc);
3545                 }
3546                 return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
3547                                 cenRoleFuncList);
3548         }
3549
3550         @SuppressWarnings("unchecked")
3551         @Override
3552         public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
3553                 EPApp app = getApp(uebkey).get(0);
3554                 final Map<String, String> params = new HashMap<>();
3555                 params.put("uebKey", app.getUebKey());
3556                 params.put("roleId", String.valueOf(roleId));
3557                 List<BulkUploadUserRoles> userRolesList = null;
3558                 Integer userRolesAdded = 0;
3559                 if (app.getCentralAuth()) {
3560                         userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
3561                         for (BulkUploadUserRoles userRolesUpload : userRolesList) {
3562                                 userRolesUpload.setRoleName(modifiedRoleName);
3563                                 if (!userRolesUpload.getOrgUserId().equals("su1234")) {
3564                                         addUserRoleInExternalSystem(userRolesUpload);
3565                                         userRolesAdded++;
3566                                 }
3567                         }
3568                 }
3569                 return userRolesAdded;
3570         }
3571
3572         @Override
3573         public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
3574                 ObjectMapper mapper = new ObjectMapper();
3575                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3576                 try {
3577                         ExternalAccessRolePerms extRolePerms;
3578                         ExternalAccessPerms extPerms;
3579                         extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(),
3580                                         EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction());
3581                         String appNameSpace = "";
3582                         if (data.getIsGlobalRolePartnerFunc()) {
3583                                 appNameSpace = epAppService.getApp(1l).getNameSpace();
3584                         } else {
3585                                 appNameSpace = app.getNameSpace();
3586                         }
3587                         extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
3588                                         .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
3589                         String updateRolePerms = mapper.writeValueAsString(extRolePerms);
3590                         HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
3591                         updateRoleFunctionInExternalSystem(updateRolePerms, entity);
3592                 } catch (HttpClientErrorException e) {
3593                         logger.error(EELFLoggerDelegate.errorLogger,
3594                                         "HttpClientErrorException - Failed to add role function in external central auth system", e);
3595                         EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
3596                         throw e;
3597                 } catch (Exception e) {
3598                         logger.error(EELFLoggerDelegate.errorLogger,
3599                                         "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
3600                         throw e;
3601                 }
3602         }
3603
3604         private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
3605                 logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
3606                                 CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
3607                 ResponseEntity<String> addPermResponse = template.exchange(
3608                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
3609                                 HttpMethod.POST, entity, String.class);
3610                 logger.debug(EELFLoggerDelegate.debugLogger,
3611                                 "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
3612                                 addPermResponse.getStatusCode().value(), updateRolePerms);
3613         }
3614
3615         @Override
3616         public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
3617                 String name = "";
3618                 if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
3619                         name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
3620                 }
3621                 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
3622                 HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
3623                 ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
3624                 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
3625                 String res = getResponse.getBody();
3626                 JSONObject jsonObj = null;
3627                 JSONArray extRoles = null;
3628                 if (!res.equals("{}")) {
3629                         jsonObj = new JSONObject(res);
3630                         extRoles = jsonObj.getJSONArray("role");
3631                 }
3632                 updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
3633         }
3634
3635         @SuppressWarnings("unchecked")
3636         private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
3637                         String loginId) throws InvalidUserException {
3638                 HashMap<String, String> userParams = new HashMap<>();
3639                 userParams.put("orgUserId", loginId);
3640                 // Get all centralized applications existing user roles from local
3641                 List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
3642                                 .executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
3643                 EPUser user = getUser(loginId).get(0);
3644                 // Get all centralized applications roles from local
3645                 HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
3646                 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
3647                                 currentUserAppRoles);
3648                 // Get all centralized applications + admin role from local
3649                 HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
3650                 if (extRoles != null) {
3651                         ExternalAccessUserRoleDetail userRoleDetail = null;
3652                         for (int i = 0; i < extRoles.length(); i++) {
3653                                 if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
3654                                                 && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
3655                                         userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
3656                                                         null);
3657                                         userRoleDetailList.add(userRoleDetail);
3658                                 }
3659                         }
3660                         addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
3661                                         centralisedAppsMap);
3662                 }
3663         }
3664
3665         private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
3666                         HashMap<String, CentralizedAppRoles> cenAppRolesMap,
3667                         HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
3668                         HashMap<String, EPApp> centralisedAppsMap) {
3669                 for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
3670                         try {
3671                                 // check if user already has role in local
3672                                 if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
3673                                         CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
3674                                         if (getCenAppRole != null) {
3675                                                 logger.debug(EELFLoggerDelegate.debugLogger,
3676                                                                 "addUserRolesInLocal: Adding user role from external auth system  {}",
3677                                                                 extUserRoleDetail.toString());
3678                                                 EPUserApp userApp = new EPUserApp();
3679                                                 EPApp app = new EPApp();
3680                                                 app.setId(getCenAppRole.getAppId());
3681                                                 EPRole epRole = new EPRole();
3682                                                 epRole.setId(getCenAppRole.getRoleId());
3683                                                 userApp.setApp(app);
3684                                                 userApp.setUserId(user.getId());
3685                                                 userApp.setRole(epRole);
3686                                                 dataAccessService.saveDomainObject(userApp, null);
3687                                                 logger.debug(EELFLoggerDelegate.debugLogger,
3688                                                                 "addUserRolesInLocal: Finished user role from external auth system  {}",
3689                                                                 extUserRoleDetail.toString());
3690                                         } else if (getCenAppRole == null // check if user has app
3691                                                                                                                 // account admin role
3692                                                         && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
3693                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
3694                                                 EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
3695                                                 if (app != null) {
3696                                                         logger.debug(EELFLoggerDelegate.debugLogger,
3697                                                                         "addUserRolesInLocal: Adding user role from external auth system  {}",
3698                                                                         extUserRoleDetail.toString());
3699                                                         EPUserApp userApp = new EPUserApp();
3700                                                         EPRole epRole = new EPRole();
3701                                                         epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
3702                                                         userApp.setApp(app);
3703                                                         userApp.setUserId(user.getId());
3704                                                         userApp.setRole(epRole);
3705                                                         dataAccessService.saveDomainObject(userApp, null);
3706                                                         logger.debug(EELFLoggerDelegate.debugLogger,
3707                                                                         "addUserRolesInLocal: Finished user role from external auth system  {}",
3708                                                                         extUserRoleDetail.toString());
3709                                                 }
3710                                         }
3711                                 }
3712                         } catch (Exception e) {
3713                                 logger.error(EELFLoggerDelegate.errorLogger,
3714                                                 "addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
3715                                                 extUserRoleDetail.toString(), e);
3716                         }
3717                 }
3718         }
3719
3720         @SuppressWarnings("unchecked")
3721         private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
3722                 List<EPApp> centralizedApps = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
3723                 HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
3724                 for (EPApp cenApp : centralizedApps) {
3725                         centralisedAppsMap.put(
3726                                         cenApp.getNameSpace() + "."
3727                                                         + PortalConstants.ADMIN_ROLE.replaceAll(
3728                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3729                                         cenApp);
3730                 }
3731                 return centralisedAppsMap;
3732         }
3733
3734         private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
3735                         List<CentralizedAppRoles> currentUserAppRoles) {
3736                 HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
3737                 for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
3738                         currentCentralizedUserAppRolesMap.put(
3739                                         cenAppUserRole.getAppNameSpace() + "."
3740                                                         + cenAppUserRole.getRoleName().replaceAll(
3741                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3742                                         cenAppUserRole);
3743                 }
3744                 return currentCentralizedUserAppRolesMap;
3745         }
3746
3747         @SuppressWarnings("unchecked")
3748         private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
3749                 List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
3750                                 .executeNamedQuery("getAllCentralizedAppsRoles", null, null);
3751                 HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
3752                 for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
3753                         cenAppRolesMap.put(
3754                                         CentralizedAppRole.getAppNameSpace() + "."
3755                                                         + CentralizedAppRole.getRoleName().replaceAll(
3756                                                                         EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
3757                                         CentralizedAppRole);
3758                 }
3759                 return cenAppRolesMap;
3760         }
3761
3762         @Override
3763         public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
3764                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
3765                 ResponseEntity<String> getResponse = template
3766                                 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
3767                                                 + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
3768                 if (getResponse.getStatusCode().value() == 200) {
3769                         logger.debug(EELFLoggerDelegate.debugLogger,
3770                                         "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
3771                                         getResponse.getBody());
3772                 } else {
3773                         logger.error(EELFLoggerDelegate.errorLogger,
3774                                         "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
3775                                         getResponse.getBody());
3776                         EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
3777                 }
3778                 return getResponse;
3779         }
3780
3781         @Override
3782         public Integer updateAppRoleDescription(String uebkey) {
3783                 Integer roleDescUpdated = 0;
3784                 EPApp app;
3785                 try {
3786                         app = getApp(uebkey).get(0);
3787                         List<EPRole> roles = getAppRoles(app.getId());
3788                         for (EPRole epRole : roles) {
3789                                 Role role = new Role();
3790                                 role.setName(epRole.getName());
3791                                 boolean status = addRoleDescriptionInExtSystem(role, app);
3792                                 if (status)
3793                                         roleDescUpdated++;
3794                         }
3795                 } catch (Exception e) {
3796                         logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
3797                 }
3798                 return roleDescUpdated;
3799         }
3800
3801 }