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